public void UpdateAppliedMigrations(MigrationHistoryRow appliedMigration) { Guard.ArgumentNotNull(nameof(appliedMigration), appliedMigration); var allAppliedMigrations = GetAllAppliedMigrations(); if (allAppliedMigrations.AllMigrations.Any(x => x.Prefix == appliedMigration.Prefix)) { var currentMigrations = allAppliedMigrations.AllMigrations.First(x => x.Prefix == appliedMigration.Prefix); currentMigrations.AppliedMigrations = appliedMigration.AppliedMigrations; } else { allAppliedMigrations.AllMigrations.Add(appliedMigration); } using var connection = _connectionFactory.CreateConnection(); using var model = connection.CreateModel(); model.BasicGet(Constants.HistoryQueue, true); var messageText = JsonConvertHelper.SerializeObjectToByteArray(allAppliedMigrations); var messageProps = model.CreateBasicProperties(); messageProps.Persistent = true; model.BasicPublish(Constants.DefaultExchange, Constants.HistoryQueue, messageProps, messageText); }
public string ReadStatus() { JArray Monthstatusjarr = JArray.Parse(this._MonthstatusStr); Dictionary <string, ListStatusByFac> MonthstatusObj = BuildMonthObj(Monthstatusjarr); return(JsonConvertHelper.SerializeObject(MonthstatusObj)); }
protected void btSave_Click(object sender, EventArgs e) { SupplyInfo info = new SupplyInfo(); SupplyInfoBLL bll = null; try { UIBindHelper.BindModelByControls(this.Page, info); bll = BLLFactory.CreateBLL <SupplyInfoBLL>(); info.Details = JsonConvertHelper.DeserializeObject <List <SupplyMaterialInfo> >(this.hiMaterialList.Value); info.BATCHNUMBER = this.PLANID.SelectedItem.Text; if (this.hiID.Value == "") { bll.Insert(info); } else { info.CREATEUSER = this.HiCREATEUSER.Value; info.CREATETIME = DateTime.Parse(this.HiCREATETIME.Value); info.PID = this.hiID.Value; info.PLANID = this.hiPlanID.Value; info.PLName = this.PLNAME.Text; bll.Update(info); } ClientScript.RegisterStartupScript(this.GetType(), "myjs", "parent.refreshData();parent.closeAppWindow1();", true); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Search(string keyword) { if (string.IsNullOrEmpty(keyword)) { return(Redirect("/")); } var apiService = _configuration.GetApiServiceInfo(); ViewBag.Keyword = keyword; if (!string.IsNullOrEmpty(keyword)) { keyword = keyword.Trim().StripVietnameseChars().ToUpper(); } var products = await _productService.ProductSearch(apiService.TenantId, CultureInfo.CurrentCulture.Name, keyword, null, null, null, 1, 100); ViewBag.ListProduct = JsonConvertHelper.GetObjectFromObject <List <ProductSearchViewModel> >(products?.Items); var news = await _newsService.Search(apiService.TenantId, CultureInfo.CurrentCulture.Name, keyword, null, null, null, 1, 100); ViewBag.ListNews = JsonConvertHelper.GetObjectFromObject <List <NewsSearchViewModel> >(news?.Items); return(View()); }
public void TestUpdateAppliedMigrationsExistingPrefix() { _rabbitMqHistory.Init(); SetupDefaultExchange(); PushDummyMigrationHistoryMessage(); var migrationHistoryRow = new MigrationHistoryRow { Prefix = "test" }; migrationHistoryRow.AppliedMigrations.Add(new MigrationHistoryRowDetails { Name = "001_TestMigration" }); migrationHistoryRow.AppliedMigrations.Add(new MigrationHistoryRowDetails { Name = "002_TestMigrationAddQueue" }); _rabbitMqHistory.UpdateAppliedMigrations(migrationHistoryRow); using (var connection = _connectionFactory.CreateConnection()) using (var channel = connection.CreateModel()) { var message = channel.BasicGet(Constants.HistoryQueue, true); Assert.IsNotNull(message); var migrationHistory = JsonConvertHelper.DeserializeObject <MigrationHistory>(message.Body); Assert.IsNotNull(migrationHistory); Assert.AreEqual(1, migrationHistory.AllMigrations.Count); var migration = migrationHistory.AllMigrations.First(); Assert.AreEqual("test", migration.Prefix); Assert.AreEqual(2, migration.AppliedMigrations.Count); CollectionAssert.AreEqual(migrationHistoryRow.AppliedMigrations.ToList(), migration.AppliedMigrations.ToList(), new AppliedMigrationsComparer()); } }
private void PushDummyMigrationHistoryMessage() { var migrationHistoryRow = new MigrationHistoryRow { Prefix = "test" }; migrationHistoryRow.AppliedMigrations.Add(new MigrationHistoryRowDetails { Name = "001_TestMigration", Hash = "a0b87bef6d840b00ac344eb2a204442760794512bb8bc0873b63d8c7d5849e9f", DownOperations = new List <BaseOperation> { new DeleteQueueOperation().SetName("bar"), new DeleteExchangeOperation().SetName("foo") } }); var migrationHistory = new MigrationHistory(); migrationHistory.AllMigrations.Add(migrationHistoryRow); using (var connection = _connectionFactory.CreateConnection()) using (var channel = connection.CreateModel()) { var messageBody = JsonConvertHelper.SerializeObjectToByteArray(migrationHistory); channel.BasicPublish("", Constants.HistoryQueue, false, null, messageBody); } }
public async Task <IActionResult> About() { var apiService = _configuration.GetApiServiceInfo(); var listCoreValue = await _coreService.GetAllActivatedCoreValueAsync(apiService.TenantId, CultureInfo.CurrentCulture.Name); if (listCoreValue != null) { ViewBag.ListCoreValue = JsonConvertHelper.GetObjectFromObject <List <ValueViewModel> >(listCoreValue); } if (_cache.TryGetValue($"{CacheParam.MenuMiddle}{CultureInfo.CurrentCulture.Name}", out MenuDetailViewModel CategoryMiddleCache)) { ViewBag.MenuContact = CategoryMiddleCache; } else { var menuMiddle = await _menuService.GetAllActivatedMenuByPositionAsync(apiService.TenantId, CultureInfo.CurrentCulture.Name, WebsiteClient.Api.Domain.Constants.Position.Middle); var menuMiddleData = JsonConvertHelper.GetObjectFromObject <MenuDetailViewModel>(menuMiddle); _cache.Set($"{CacheParam.MenuMiddle}{CultureInfo.CurrentCulture.Name}", menuMiddleData, TimeSpan.FromHours(1)); ViewBag.MenuContact = menuMiddleData; } return(View()); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteStartObject(); IPageResponse message = value as IPageResponse; if (message != null) { writer.WritePropertyName("sEcho"); writer.WriteValue(message.Draw); writer.WritePropertyName("iTotalRecords"); writer.WriteValue(message.TotalRecords); writer.WritePropertyName("iTotalDisplayRecords"); writer.WriteValue(message.TotalFilteredRecords); writer.WritePropertyName("aaData"); serializer.Serialize(writer, message.Data); } JsonConvertHelper.WriteJson(message, writer, serializer, prop => JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse)).Select(x => x.Name).Contains(prop.Name) || JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse <>)).Select(x => x.Name).Contains(prop.Name)); writer.WriteEndObject(); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { var code = new HttpResponseMessage(HttpStatusCode.InternalServerError).StatusCode;//设置错误代码:例如:500 404 actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError); string msg = JsonConvert.SerializeObject(new BaseResult() { success = false, message = actionExecutedContext.Exception.Message }); //返回异常错误提示 //写入错误日志相关实现 var portLogEntity = new PortLogEntity { PortName = actionExecutedContext.Request.RequestUri.AbsolutePath, RequestType = actionExecutedContext.Request.Method.ToString(), //StatusCode = Convert.ToInt32(code), ClientIp = GetClientIp(), ParameterList = JsonConvertHelper.ConvertToJson(actionExecutedContext.ActionContext.ActionArguments), Success = false, ErrorMessage = msg }; LogHelper.error("服务器错误信息:\r\n" + JsonConvertHelper.ConvertToJson(portLogEntity)); //result msg = JsonConvertHelper.ConvertToJson( new ResultDataModel <BaseResult> { Code = 4003, Messages = "全局接口异常捕捉到的错误,请联系研发人员处理" }); actionExecutedContext.Response.Content = new StringContent(msg, Encoding.UTF8); }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteStartObject(); IPageResponse message = value as IPageResponse; if (message != null) { writer.WritePropertyName("draw"); writer.WriteValue(message.Draw); writer.WritePropertyName("recordsTotal"); writer.WriteValue(message.TotalRecords); writer.WritePropertyName("recordsFiltered"); writer.WriteValue(message.TotalFilteredRecords); writer.WritePropertyName("data"); serializer.Serialize(writer, message.Data); if (!string.IsNullOrWhiteSpace(message.Error)) { writer.WritePropertyName("error"); writer.WriteValue(message.Error); } } JsonConvertHelper.WriteJson(message, writer, serializer, prop => JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse)).Select(x => x.Name).Contains(prop.Name) || JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse <>)).Select(x => x.Name).Contains(prop.Name)); writer.WriteEndObject(); }
public void PrintResult(string strJsonProducts) { var products = JsonConvertHelper.JsonDeserialize <string[]>(strJsonProducts); ProductsBusiness service = new ProductsBusiness(); service.PrintResult(products); }
/// <summary> /// 确认 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btConfirm_Click(object sender, EventArgs e) { CheckStockBill info = new CheckStockBill(); CheckStockBLL bll = null; try { UIBindHelper.BindModelByControls(this.Page, info); bll = BLLFactory.CreateBLL <CheckStockBLL>(); info.Details = JsonConvertHelper.DeserializeObject <List <CheckStockDetail> >(this.hiCheckList.Value); info.CREATEUSER = this.HiCREATEUSER.Value; info.CREATETIME = DateTime.Parse(this.HiCREATETIME.Value); info.ID = this.hiID.Value; bll.ConfirmCheck(info); ClientScript.RegisterStartupScript(this.GetType(), "myjs", "parent.refreshData();parent.closeAppWindow1();", true); } catch (Exception ex) { throw ex; } }
protected virtual async Task <List <TModel> > Query(string key = "") { string queryUri = $"{ConfigHelper.WebAPIAddress}/{this.ModelType.Name}/Query?key={key}"; LogHelper <TModel> .Debug($"查询地址:{queryUri}"); try { using (var response = await WebHelper.GetAsync(queryUri)) { LogHelper <TModel> .Debug($"接收到响应数据,状态代码:{response.StatusCode}"); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); var models = JsonConvertHelper.DeserializeObject <List <TModel> >(content); LogHelper <TModel> .Debug($"接收到 {models.Count} 条数据。"); return(models); } else { return(default);
public ActionResult OnPostGridUpdateUserInfo([C1JsonRequest] CollectionViewEditRequest <UserInfo> requestData) { return(JsonConvertHelper.C1Json(CollectionViewHelper.Edit <UserInfo>(requestData, item => { string error = string.Empty; bool success = true; try { var resultItem = Users.Find(u => u.Id == item.Id); var index = Users.IndexOf(resultItem); Users.Remove(resultItem); Users.Insert(index, item); } catch (Exception e) { error = e.Message; success = false; } return new CollectionViewItemResult <UserInfo> { Error = error, Success = success, Data = item }; }, () => Users))); }
public async Task <IActionResult> Add([FromForm] string value) { if (string.IsNullOrWhiteSpace(value)) { this.logger.LogWarning($"{this.HttpContext.Connection.RemoteIpAddress} 请求新增空数据的 {typeof(TModel).Name} 对象"); return(this.StatusCode(StatusCodes.Status422UnprocessableEntity)); } try { var model = JsonConvertHelper.DeserializeObject <TModel>(value); if (model == null) { this.logger.LogWarning($"{this.HttpContext.Connection.RemoteIpAddress} 请求新增的数据转义为 {typeof(TModel).Name} 对象为空引用"); return(this.StatusCode(StatusCodes.Status422UnprocessableEntity)); } await this.context.Set <TModel>().AddAsync(model); await this.context.SaveChangesAsync(); this.logger.LogDebug($"{this.HttpContext.Connection.RemoteIpAddress} 请求新增 ID 为 {model.ID} 的 {typeof(TModel).Name} 对象"); return(this.StatusCode(StatusCodes.Status201Created, model.ID)); } catch (Exception ex) { this.logger.LogError(ex, $"{this.HttpContext.Connection.RemoteIpAddress} 请求新增 {typeof(TModel).Name} 对象遇到异常"); return(this.StatusCode(StatusCodes.Status417ExpectationFailed, ex.Message)); } }
public async Task <IActionResult> Get(string id) { if (string.IsNullOrWhiteSpace(id)) { this.logger.LogWarning($"{this.HttpContext.Connection.RemoteIpAddress} 请求查询空 ID 的 {typeof(TModel).Name} 数据"); return(this.StatusCode(StatusCodes.Status406NotAcceptable)); } try { var model = await this.context.Set <TModel>().FindAsync(id); if (model == null) { this.logger.LogWarning($"{this.HttpContext.Connection.RemoteIpAddress} 请求查询 ID 不存在的 {typeof(TModel).Name} 数据"); return(this.StatusCode(StatusCodes.Status406NotAcceptable)); } else { this.logger.LogDebug($"{this.HttpContext.Connection.RemoteIpAddress} 请求查询 ID 为 {id} 的 {typeof(TModel).Name} 数据"); return(this.Content(JsonConvertHelper.SerializeObject(model))); } } catch (Exception ex) { this.logger.LogError(ex, $"{this.HttpContext.Connection.RemoteIpAddress} 请求查询 ID 为 {id} 的 {typeof(TModel).Name} 数据遇到异常"); return(this.StatusCode(StatusCodes.Status417ExpectationFailed, ex.Message)); } }
private async void btnChangeAvater_Tapped(object sender, TappedRoutedEventArgs e) { FileOpenPicker picker = new FileOpenPicker(); picker.ViewMode = PickerViewMode.Thumbnail; picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); // 选取单个文件 StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { var stream = await file.OpenSequentialReadAsync(); await WebProvider.GetInstance().SendPostRequestAsync("http://news-at.zhihu.com/api/4/avatar", stream); string resJosn = await WebProvider.GetInstance().GetRequestDataAsync("http://news-at.zhihu.com/api/4/account"); var UserInfo = JsonConvertHelper.JsonDeserialize <UserInfo>(resJosn); ViewModel.ViewModelLocator.AppShell.UserInfo.Avatar = UserInfo.Avatar; ViewModel.ViewModelLocator.AppShell.UserInfo.Name = UserInfo.Name; ViewModel.ViewModelLocator.AppShell.UserInfo.BoundServices = UserInfo.BoundServices; AppSettings.Instance.UserInfoJson = JsonConvertHelper.JsonSerializer(ViewModel.ViewModelLocator.AppShell.UserInfo); } }
protected void btSave_Click(object sender, EventArgs e) { ProduceBOM info = new ProduceBOM(); ProduceDOMBLL bll = null; try { UIBindHelper.BindModelByControls(this.Page, info); bll = BLLFactory.CreateBLL <ProduceDOMBLL>(); info.Details = JsonConvertHelper.DeserializeObject <List <BOMDetail> >(this.hiBomDetailList.Value); if (this.hiID.Value == "") { bll.Insert(info); } else { info.CREATEUSER = this.HiCREATEUSER.Value; info.CREATETIME = DateTime.Parse(this.HiCREATETIME.Value); info.PID = this.hiID.Value; bll.Update(info); } ClientScript.RegisterStartupScript(this.GetType(), "myjs", "parent.refreshData();parent.closeAppWindow1();", true); } catch (Exception ex) { throw ex; } }
public async Task <IActionResult> Agency() { var listProvince = await _coreService.GetProvinceByNationId(1); ViewBag.ListProvice = JsonConvertHelper.GetObjectFromObject <List <ObjectViewModel> >(listProvince); ViewBag.Message = "Chúc mừng bạn đã đăng ký đại lý thành công. Chúng tôi sẽ liên hệ với bạn trong thời gian sớm nhất để xác nhận."; return(View()); }
/// <summary> /// 获取列表 /// </summary> /// <param name="tableName"></param> /// <returns></returns> public static List <TableModel> GetListTable() { string filepath = "table.json"; string json = JsonHelper.GetFile(filepath); List <TableModel> tableModels = JsonConvertHelper.DeserializeObject <List <TableModel> >(json) as List <TableModel>; return(tableModels); }
public async void LoadContent(long commentId) { string resJosn = await WebProvider.GetInstance().GetRequestDataAsync($"http://news-at.zhihu.com/api/4/comment/{commentId}/replies"); if (resJosn != string.Empty) { NotificationReply = JsonConvertHelper.JsonDeserialize <NotificationReply>(resJosn); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); IEnumerable <JProperty> properties = jsonObject.Properties(); Dictionary <string, JProperty> otherProperties = new Dictionary <string, JProperty>(); IPageResponse message = Activator.CreateInstance(objectType) as IPageResponse; foreach (JProperty property in properties) { if (property.Name == "draw") { message.Draw = property.Value.ToObject <int>(); } else if (property.Name == "recordsTotal") { message.TotalRecords = property.Value.ToObject <int>(); } else if (property.Name == "recordsFiltered") { message.TotalFilteredRecords = property.Value.ToObject <int>(); } else if (property.Name == "data") { if (objectType.IsGenericType) { Type genericType = objectType.GetGenericArguments()[0].MakeArrayType(); object genericArray = property.Value.ToObject(genericType); message.Data = (object[])genericArray; } else { message.Data = property.Value.ToObject <object[]>(); } } else if (property.Name == "error") { message.Error = property.Value.ToObject <string>(); } else { otherProperties.Add(property.Name, property); } } JsonConvertHelper.ReadJson(message, otherProperties, serializer, prop => JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse)).Select(x => x.Name).Contains(prop.Name) || JsonConvertHelper.GetPropertiesFromType(typeof(IPageResponse <>)).Select(x => x.Name).Contains(prop.Name)); return(message); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jsonObject = JObject.Load(reader); IEnumerable <JProperty> properties = jsonObject.Properties(); Dictionary <string, JProperty> otherProperties = new Dictionary <string, JProperty>(); IFilterRequest message = Activator.CreateInstance(objectType) as IFilterRequest; foreach (JProperty property in properties) { if (property.Name == "draw") { message.Draw = property.Value.ToObject <int>(); } else if (property.Name == "start") { message.Start = property.Value.ToObject <int>(); } else if (property.Name == "length") { message.Length = property.Value.ToObject <int>(); } else if (property.Name == "search[value]") { message.Search.Value = property.Value.ToObject <string>(); } else if (property.Name == "search[regex]") { message.Search.IsRegex = property.Value.ToObject <bool>(); } else if (property.Name.StartsWith("order")) { ReadSortConfiguration(ref message, property); } else if (property.Name.StartsWith("columns")) { ReadColumnConfiguration(ref message, property); } else { otherProperties.Add(property.Name, property); } } JsonConvertHelper.ReadJson(message, otherProperties, serializer, prop => JsonConvertHelper.GetPropertiesFromType(typeof(IFilterRequest)).Select(x => x.Name).Contains(prop.Name)); return(message); }
public async void LoadContent() { string resJosn = await WebProvider.GetInstance().GetRequestDataAsync("http://news-at.zhihu.com/api/4/notifications"); if (resJosn != string.Empty) { var jsonObj = Windows.Data.Json.JsonObject.Parse(resJosn); Notifications = JsonConvertHelper.JsonDeserialize <List <Notification> >(jsonObj["notifications"].ToString()); } }
public async Task <IActionResult> GetNewsByCategory(int categoryId, int page = 3, int pageSize = 6) { var apiService = _configuration.GetApiServiceInfo(); var listNews = await _newsService.GetNewsByCategoryIdAsync(apiService.TenantId, CultureInfo.CurrentCulture.Name, categoryId, page, pageSize); var listNewsData = JsonConvertHelper.GetObjectFromObject <CategoryWidthNewsViewModel>(listNews.Data); return(Json(listNewsData.ListNews)); }
/// <summary> /// 将日志转成字符串 /// </summary> /// <param name="log">日志信息</param> /// <returns>字符串</returns> private string GetLogString(LogInfo log) { List <string> infos = new List <string>(); try { //客户端IP if (string.IsNullOrEmpty(log.ClientIP) == false) { infos.Add(log.ClientIP); } else { infos.Add("null"); } //登录用户名 if (string.IsNullOrEmpty(log.UserName) == false) { infos.Add(log.UserName); } else { infos.Add("null"); } //动作信息 if (string.IsNullOrEmpty(log.Info) == false) { infos.Add(log.Info); } else { infos.Add("null"); } //数据 if (log.Tag != null) { infos.Add(JsonConvertHelper.GetSerializes(log.Tag)); } else { infos.Add("null"); } return(string.Join(" ", infos)); } catch (Exception ex) { throw ex; } }
public void AutoLogin() { string userInfoJson = AppSettings.Instance.UserInfoJson; if (userInfoJson != string.Empty) { UserInfo userInfo = JsonConvertHelper.JsonDeserialize <UserInfo>(userInfoJson); ViewModel.ViewModelLocator.AppShell.UserInfo = userInfo; } }
public ActionResult OnPostBind([C1JsonRequest] CollectionViewRequest <Sale> requestData) { var extraData = requestData.ExtraRequestData .ToDictionary(kvp => kvp.Key, kvp => new StringValues(kvp.Value.ToString())); var data = new FormCollection(extraData); _gridDataModel.LoadPostData(data); var model = Sale.GetData(Convert.ToInt32(_gridDataModel.Options["items"].CurrentValue)); return(JsonConvertHelper.C1Json(CollectionViewHelper.Read(requestData, model))); }
public async Task <JsonResult> GetComment(string objectId, int objectType, int page = 1, int pageSize = 20) { var apiService = _configuration.GetApiServiceInfo(); var commentMeta = await _feedbackService.GetComment(apiService.TenantId, objectId, objectType, page, pageSize); var comment = JsonConvertHelper.GetObjectFromObject <SearchResult <CommentViewModel> >(commentMeta); var result = RenderTree(comment.Items, null); return(Json(new { Items = result, comment.TotalRows })); }
public async Task <OAuthToken> RefreshToken(string refreshToken) { Dictionary <string, string> contentDict = new Dictionary <string, string>() { { "grant_type", "refresh_token" }, { "refresh_token", refreshToken } }; string requestContent = JsonConvertHelper.SerializeObject(contentDict); OAuthToken oAuthToken = await RequestToken(contentDict); return(oAuthToken); }