private static ClientResult <T> HttpPost <T>(string url, Dictionary <string, object> param) { return(HttpPostBase <ClientResult <T> >(url, param, (r) => { ClientResult <T> clientResult = null; try { clientResult = new JsonProvider().Deserialize <ClientResult <T> >(r); } catch (Exception exp) { try { //clientResult返回错误时,非标准类型的data类型返回的自动修正为默认值; //标准的返回错误:data应该为返回类型的默认值。 var result = new JsonProvider().Deserialize <ClientResult <Object> >(r); if (result.success == false) { result.data = default(T); clientResult = new JsonProvider().Deserialize <ClientResult <T> >(new JsonProvider().Serializer(result)); } else { throw exp; } } catch { throw exp; } } clientResult.responsetext = r; return clientResult; })); }
/// <summary> /// 创建数据提供者 /// </summary> /// <param name="pProviderName"></param> /// <returns></returns> private IDataProvider CreateProvider(string pProviderName) { var newProvider = new JsonProvider(); dicDataProviders.Add(pProviderName, newProvider); return newProvider; }
public void SaveLocalTempData(object obj) { string filename = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + localtempdatafilename; var json = new JsonProvider().Serializer(obj); System.IO.File.WriteAllText(filename, json); }
protected override void BootstrapImpl() { lock (this.syncRoot) { try { this.State = RunState.Bootstrapping; string corePath = Path.GetDirectoryName(AppContext.BaseDirectory); JsonProvider tmpProvider = new JsonProvider(); if (tmpProvider.Init(Path.Combine(corePath, "Osrs.Runtime.Configuration.jconfig"))) { Type t = typeof(ConfigurationManager); string name = string.Format("{0}.{1}, {2}", t.Namespace, t.Name, t.GetTypeInfo().Assembly.GetName().Name); ConfigurationParameter param = tmpProvider.GetImpl(name, "provider"); if (param != null) { string fName = (string)param.Value; if (!string.IsNullOrEmpty(fName)) { TypeNameReference tnr = TypeNameReference.Parse(fName, ','); if (tnr != null) { Bootstrap(tnr, tmpProvider); return; } } } } } catch { } this.State = RunState.FailedBootstrapping; } }
public void Emit(LogEvent logEvent) { if (Operation == null) { return; } //if (Provider == null) // Operation?.Invoke(logEvent); //else //{ // var message = logEvent.RenderMessage(Provider); //// Operation?.Invoke(message); /// var buffer = new StringWriter(new StringBuilder()); SingleLineProvider.Format(logEvent, buffer); // Operation(buffer.ToString()); var json = new StringWriter(new StringBuilder()); JsonProvider.Format(logEvent, json); Operation(logEvent, buffer.ToString(), json.ToString()); // } }
public FuncResult Handler(string interfaceName, string dataJson) { FuncResult result = new FuncResult(); try { if ("sms_service".Equals(interfaceName, StringComparison.OrdinalIgnoreCase)) { var args = JsonProvider.JsonTo <SmsArgs>(dataJson); if (args == null) { return(FuncResult.FailResult("参数为空")); } result = this.Handler(args.UserCode, args.UserPwd, args.Mobileno, args.Content); } else if ("validate_code_send_service".Equals(interfaceName, StringComparison.OrdinalIgnoreCase)) { var args = JsonProvider.JsonTo <SendValidateCodeArgs>(dataJson); if (args == null) { return(FuncResult.FailResult("参数为空")); } SmsValidCodeFacade valid = new SmsValidCodeFacade(args.UserCode, args.UserPwd); bool res = valid.SendSmsValidCode(args.Mobileno, args.Gid, args.AppName); result.Success = res; result.Message = res ? null : valid.PromptInfo.CustomMessage; result.StatusCode = res ? 1 : 4; } else if ("validate_code_verify_service".Equals(interfaceName, StringComparison.OrdinalIgnoreCase)) { var args = JsonProvider.JsonTo <CodeVerificationArgs>(dataJson); if (args == null) { return(FuncResult.FailResult("参数为空")); } SmsValidCodeFacade valid = new SmsValidCodeFacade(args.UserCode, args.UserPwd); bool isSuccess = valid.ValidSmsCode(args.Mobileno, args.Gid, args.Code); result.Success = isSuccess; result.Message = isSuccess ? null : valid.PromptInfo.CustomMessage; result.StatusCode = isSuccess ? 1 : 4; } else { result.Success = false; result.Message = "未找到指定的服务[" + interfaceName + "]"; result.StatusCode = 404; } } catch (Exception ex) { Log.Error("API-Handler异常", ex); result.Success = false; result.Message = "系统错误"; result.StatusCode = 500; } return(result); }
/// <inheritdoc /> public async Task <long> SerializeCollection <T>(IAsyncEnumerable <T> collection, Stream stream, IRequest request, CancellationToken cancellationToken) where T : class { var count = await JsonProvider.SerializeCollection(collection, stream, request, cancellationToken).ConfigureAwait(false); stream.Seek(0, SeekOrigin.Begin); await XmlSerializeJsonStream(stream).ConfigureAwait(false); return(count); }
protected virtual JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonProvider jsonProvider) { return new JsonResultEx(jsonProvider) { Data = data, ContentType = contentType, ContentEncoding = contentEncoding }; }
// GET: SQLManager public ActionResult Index() { Tsql_ClassifyCollection daClassifyColl = new Tsql_ClassifyCollection(); daClassifyColl.SelectClassify(); List <Classify> classifyList = MapProvider.Map <Classify>(daClassifyColl.DataTable); ViewBag.JsonClassify = JsonProvider.ToJson(classifyList); return(View()); }
public ActionResult GetQiHao() { Tcp_Hiscode tcp = new Tcp_Hiscode(); if (!tcp.GetLastSingle()) { return(FailResult("获取失败")); } return(SuccessResult(JsonProvider.ToJson(tcp.DataRow))); }
//提交认证申请 public JsonResult Auth(AuthIdentityInfo identity) { AuthenticationProvider provider = new AuthenticationProvider(); bool res = provider.Authencate(this.Package.UserCode, identity); FuncResult result = new FuncResult(); result.Success = res; result.Message = res ? null : provider.PromptInfo.CustomMessage; result.StatusCode = res ? 1 : (int)provider.PromptInfo.ResultType; Log.Info(JsonProvider.ToJson(result)); return(Json(result)); }
public T GetLocalTempData <T>() where T : class { string filename = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + localtempdatafilename; if (!System.IO.File.Exists(filename)) { return(null); } string content = System.IO.File.ReadAllText(filename); var obj = new JsonProvider().Deserialize <T>(content); return(obj); }
public JsonResultEx(JsonProvider provider, JsonSerializerSettings settings) { this.Provider = provider; if (null == settings) { this.SerializerSettings = defautNewtonSerializerSettings; } else { this.SerializerSettings = settings; } }
public async Task Positive_CheckBranchesCollection_Async(object expectedBranch) { var branches = await new GitHubClient() .GetBranchesAsync() .ConfigureAwait(false); var branchesCollection = branches.Select(JsonProvider.Serialize); var expected = JsonProvider.Serialize(expectedBranch); CollectionAssert.Contains( branchesCollection, expected, "Actual GitHub brunches collection does not contain an expected brunch."); }
public async ValueTask <T> ReceivePocoAsync <T>(HttpResponseMessage response) { var content = response.Content; var responseText = await content.ReadAsStringAsync().ConfigureAwait(false); var poco = JsonProvider.Deserialize <T>(responseText); if (_withLog) { LogProvider.WriteResponse(response.Headers, poco); } return(poco); }
public override void OnResultExecuted(ResultExecutedContext filterContext) { base.OnResultExecuted(filterContext); if (filterContext.Result is JsonResult) { var result = filterContext.Result as JsonResult; Log.Info(JsonProvider.ToJson(result.Data)); } else if (filterContext.Result is ContentResult) { var content = filterContext.Result as ContentResult; Log.Info(content.Content); } Log.Info($"===================={_apiName}======================END"); }
public T GetDataBaseTempData <T>() where T : class { string json = null; SqlHelper.ExcuteSql(DllTask.SystemRuntimeInfo.TaskConnectString, (c) => { Dal.tb_tempdata_dal taskdal = new Dal.tb_tempdata_dal(); json = taskdal.GetTempData(c, DllTask.SystemRuntimeInfo.TaskModel.id); }); if (string.IsNullOrEmpty(json)) { return(null); } var obj = new JsonProvider().Deserialize <T>(json); return(obj); }
public void GenerateShouldBeInRange() { // Arrange IJsonProvider jsonProvider = new JsonProvider(); var json = @"{ ""firstName"" : ""TheFirstName"", ""lastName"" : ""TheLastName"" }"; // Act var result = jsonProvider.ToDictionary(json); // Assert result.Should().NotBeNull(); result.Keys.Count.Should().Be(2); result["firstName"].Should().Be("TheFirstName"); result["lastName"].Should().Be("TheLastName"); }
public void GenerateShouldBeInRange() { // Arrange IJsonProvider jsonProvider = new JsonProvider(); var json = @"{ ""uno"" : ""Uno"", ""due"" : ""Due"" }"; // Act var result = jsonProvider.ToDictionary(json); // Assert result.Should().NotBeNull(); result.Keys.Count.Should().Be(2); result["uno"].Should().Be("Uno"); result["due"].Should().Be("Due"); }
public bool sendMessage(messageModel msgModel) { Dictionary <string, string> dict = new Dictionary <string, string>(); dict.Add("Title", msgModel.Title); dict.Add("Content", msgModel.msg); SendMessageModel model = new SendMessageModel(); model.TemplateNo = msgModel.TemplateNo; model.Receiver = msgModel.Receiver; model.Parameter = dict; model.SendTime = DateTime.Now; //组装JOSN 数据 List <SendMessageModel> list = new List <SendMessageModel>(); list.Add(model); //组装JOSN数据 var jsonModel = new { Title = msgModel.Title, Body = list, MerchaanNo = AppConfig.MessageMerchantNo, ClientSource = "PC", ClientSystem = "DM-web", Version = 1, TimeStamp = DateTime.Now }; string json = JsonProvider.ToJson(jsonModel); string sign = MD5Provider.Encode(json + AppConfig.MessageKey); var request = new Winner.Framework.Utils.Network.HttpRequestProvider(); request.SetUrl(AppConfig.MessageUrl)//请求接口地址 .AddParameter("Json", json) .AddParameter("Sign", sign); var jsonResult = request.POST(); if (!jsonResult.Success) { return(false); } return(true); }
public void StoreTest() { using var file = new TemporaryFile(); File.WriteAllText(file, "{}"); var jsonProvider = new JsonProvider(file); var sample = new Sample("hello"); jsonProvider.Store("sample", sample); Task.Delay(1000).Wait(); var expect = @"{ ""sample"": { ""Key"": ""hello"" } }"; Assert.Equal(expect, File.ReadAllText(file)); }
public void GivenEventObjectSerializeObjectShouldReturnString() { //Arrange var obj = new ObjectToDeserializeTo(1, "Dupont"); string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); //Act IJsonProvider sut = new JsonProvider(); var result = sut.SerializeObject(obj); //Assert Assert.Equal(json, result); }
public void GivenStringDeserializeObjectShouldReturnObject() { //Arrange var json = @" { 'Id' :1, 'Name':'Dupont' }"; var obj = new ObjectToDeserializeTo(1, "Dupont"); //Act IJsonProvider sut = new JsonProvider(); var result = sut.DeserializeObject <ObjectToDeserializeTo>(json); //Assert Assert.Equal(obj.Id, result.Id); Assert.Equal(obj.Name, result.Name); }
public void RestoreTest() { var sampleJson = @" { ""sample"":{""Key"":""outside""}, ""list"": [ { ""Key"":""in list"" } ] }"; using var file = new TemporaryFile(); File.WriteAllText(file, sampleJson); var jsonProvider = new JsonProvider(file); Assert.Equal("outside", jsonProvider.Restore("sample", new Sample("")).Key); Assert.Collection(jsonProvider.Restore("list", new List <Sample>()), (item) => Assert.Equal("in list", item.Key)); }
//public string CreateTable(DataTable table) //{ // #region 创建头部 // StringBuilder html = new StringBuilder(); // html.Append(@"<table class='table table-bordered table-hover'><thead><tr>"); // foreach (DataColumn c in table.Columns) // { // html.AppendFormat("<th>{0}</th>", c.ColumnName); // } // html.Append("</tr></thead>"); // #endregion // #region 创建行 // foreach (DataRow row in table.Rows) // { // html.Append("<tbody><tr>"); // foreach (object o in row.ItemArray) // { // html.AppendFormat("<td>{0}</td>", o == null ? "" : o.ToString()); // } // html.Append("</tr></tbody>"); // } // html.Append("</table>"); // #endregion // return html.ToString(); //} /// <summary> /// 把DataTable数据转换成List泛型集合 /// </summary> /// <param name="dt"></param> /// <returns></returns> public List <object> TableTd(DataTable dt) { if (dt == null || dt.Columns.Count <= 0) { return(null); } var list = new List <dynamic>(); List <Dictionary <string, object> > parentRow = new List <Dictionary <string, object> >(); Dictionary <string, object> childRow; foreach (DataRow row in dt.Rows) { childRow = new Dictionary <string, object>(); foreach (DataColumn col in dt.Columns) { childRow.Add(col.ColumnName, row[col]); } parentRow.Add(childRow); } var json = JsonProvider.ToJson(parentRow); return(JsonProvider.JsonTo <List <object> >(json)); }
public static void Main() { string url = "https://www.youtube.com/feeds/videos.xml?channel_id=UCLC-vbm7OWvpbqzXaoAMGGw"; var webClient = new WebClient(); string xmlFilePath = "../../info.xml"; webClient.DownloadFile(url, xmlFilePath); var jsonProvider = new JsonProvider(); var videoManager = new VideoManager(); var htmlProvider = new HTMLProvider(); string jsonRssContent = jsonProvider.GetJSONFromXml(xmlFilePath); var videos = videoManager.GetVideosFromJSON(jsonRssContent); string resultHTML = htmlProvider.BuildVideoInformationHTML(videos); string htmlFilePath = "../../result.html"; File.WriteAllText(htmlFilePath, resultHTML); Console.WriteLine("Telerik rss feed videos have been succesfully saved in result.html"); }
public void GivenValidUri_WhenCallingDownloadJsonStringAsync_ThenStringFileReturned() { // Arrange bool actualResultValue = false; UriProvider uriProvider = new UriProvider(); Uri testUri = uriProvider.CreateWunUri(WunDataFeatures.astronomy, "INORTHLA43"); JsonProvider jsonProvider = new JsonProvider(); //Act Task <string> jsonData = jsonProvider.DownloadJsonStringAsync(testUri); if (string.IsNullOrEmpty(jsonData.Result) == true) { actualResultValue = false; } else { actualResultValue = true; } //Assert Assert.IsTrue(actualResultValue); }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } HttpRequestBase request = context.HttpContext.Request; ControllerBase controller = context.Controller; ViewDataDictionary ViewData = controller.ViewData; ModelStateDictionary modelState = ViewData.ModelState; if (request.IsAjaxRequest()) { JsonProvider provider = JsonProvider.Microsoft; if (controller is ControllerEx) { provider = ((ControllerEx)controller).DefaultJsonProvider; } JsonResultEx jr = new JsonResultEx(provider) { }; if (!modelState.IsValid) { jr.Data = new { Msg = Message, Errors = modelState.GetErrors(), ContainerId = request.Form["formContainerId"], ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } else { jr.Data = new { Msg = Message, ReloadUrl = ReloadUrl, ReloadOption = (byte)ReloadOption }; } jr.ExecuteResult(context); return; } if (ReloadUrl.IsNullOrEmpty() == false && ReloadOption == ReloadAction.Redirect) { HttpResponseBase response = context.HttpContext.Response; response.Redirect(ReloadUrl); return; } ViewData["Message"] = Message; ViewResult vr = new ViewResult() { ViewData = controller.ViewData, ViewName = "Message" }; vr.ExecuteResult(context); }
static Providers() { Json = new JsonProvider(); Excel = new ExcelProvider(); }
protected virtual JsonResult Json(object data, string contentType, JsonProvider jsonProvider) { return Json(data, contentType, null /* contentEncoding */, jsonProvider); }
private async Task SerializeContentDataCollection <T>(IAsyncEnumerable <T> dataCollection, Content content, ISerializedResult toSerialize, IContentTypeProvider contentTypeProvider, CancellationToken cancellationToken) where T : class { content.SetContentDisposition(contentTypeProvider.ContentDispositionFileExtension); if (contentTypeProvider is not IJsonProvider jsonProvider) { await contentTypeProvider.SerializeCollection(dataCollection, toSerialize.Body, content.Request, cancellationToken).ConfigureAwait(false); return; } var swr = new StreamWriter(toSerialize.Body, Encoding.UTF8, 4096, true); #if NETSTANDARD2_1 await using (swr) #else using (swr) #endif { using var jwr = JsonProvider.GetJsonWriter(swr); await jwr.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("Status", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync("success", cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("ResourceType", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(content.ResourceType.FullName, cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("Data", cancellationToken).ConfigureAwait(false); var entityCount = await jsonProvider.SerializeCollection(dataCollection, jwr, cancellationToken).ConfigureAwait(false); toSerialize.EntityCount = entityCount; await jwr.WritePropertyNameAsync("DataCount", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(entityCount, cancellationToken).ConfigureAwait(false); if (content is IEntities entities) { if (toSerialize.HasPreviousPage) { var previousPageLink = entities.GetPreviousPageLink(toSerialize.EntityCount); await jwr.WritePropertyNameAsync("PreviousPage", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(previousPageLink.ToUriString(), cancellationToken).ConfigureAwait(false); } if (toSerialize.HasNextPage) { var nextPageLink = entities.GetNextPageLink(toSerialize.EntityCount, -1); await jwr.WritePropertyNameAsync("NextPage", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(nextPageLink.ToUriString(), cancellationToken).ConfigureAwait(false); } } await jwr.WritePropertyNameAsync("TimeElapsedMs", cancellationToken).ConfigureAwait(false); var milliseconds = toSerialize.TimeElapsed.GetRESTableElapsedMs(); await jwr.WriteValueAsync(milliseconds, cancellationToken).ConfigureAwait(false); await jwr.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false); if (entityCount == 0) { content.MakeNoContent(); } } }
public JsonResultEx(JsonProvider provider) : this(JsonProvider.Microsoft, null) { }
public static void Initialise() { Config = JsonProvider.DeserialiseObject <LobbyConfig>(File.ReadAllText(@".\LobbyConfig.json")); }
private async Task SerializeError(Error error, ISerializedResult toSerialize, IContentTypeProvider contentTypeProvider, CancellationToken cancellationToken) { if (contentTypeProvider is not IJsonProvider) { return; } var swr = new StreamWriter(toSerialize.Body, Encoding.UTF8, 4096, true); #if NETSTANDARD2_1 await using (swr) #else using (swr) #endif { using var jwr = JsonProvider.GetJsonWriter(swr); await jwr.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("Status", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync("fail", cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("ErrorType", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(error.GetType().FullName, cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("Data", cancellationToken).ConfigureAwait(false); await jwr.WriteStartObjectAsync(cancellationToken).ConfigureAwait(false); if (error is InvalidInputEntity failedValidation) { foreach (var invalidMember in failedValidation.InvalidEntity.InvalidMembers) { await jwr.WritePropertyNameAsync(invalidMember.MemberName, cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(invalidMember.Message, cancellationToken).ConfigureAwait(false); } await jwr.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false); if (failedValidation.InvalidEntity.Index is long index) { await jwr.WritePropertyNameAsync("InvalidEntityIndex", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(index, cancellationToken).ConfigureAwait(false); } } else { await jwr.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false); } await jwr.WritePropertyNameAsync("ErrorCode", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(error.ErrorCode.ToString(), cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("Message", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(error.Message, cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("MoreInfoAt", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(error.Headers.Error, cancellationToken).ConfigureAwait(false); await jwr.WritePropertyNameAsync("TimeStamp", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(DateTime.UtcNow.ToString("O"), cancellationToken).ConfigureAwait(false); if (error.Request?.UriComponents is IUriComponents uriComponents) { await jwr.WritePropertyNameAsync("Uri", cancellationToken).ConfigureAwait(false); await jwr.WriteValueAsync(ToUriString(uriComponents), cancellationToken).ConfigureAwait(false); } await jwr.WritePropertyNameAsync("TimeElapsedMs", cancellationToken).ConfigureAwait(false); var milliseconds = toSerialize.TimeElapsed.GetRESTableElapsedMs(); await jwr.WriteValueAsync(milliseconds, cancellationToken).ConfigureAwait(false); await jwr.WriteEndObjectAsync(cancellationToken).ConfigureAwait(false); toSerialize.EntityCount = 0; } }
protected virtual JsonResult Json(object data, JsonProvider jsonProvider) { return Json(data, null /* contentType */, jsonProvider); }