/// <summary> /// 从请求流中反序列化构造参数值 /// </summary> /// <param name="p"></param> /// <param name="requst"></param> /// <returns></returns> public virtual object FromBodyDeserializeObject(ParameterInfo p, HttpRequest requst) { // 从请求流中反序列化对象中,要注意三点: // 1、忽略参数的名称 // 2、直接使用参数类型,不做可空类型处理 // 3、仅支持 JSON, XML 的数据格式 SerializeFormat format = RequestContentType.GetFormat(requst.ContentType); if (format == SerializeFormat.Json) { string text = requst.GetPostText(); return(JsonExtensions.FromJson(text, p.ParameterType)); } if (format == SerializeFormat.Xml) { string text = requst.GetPostText(); return(XmlExtensions.FromXml(text, p.ParameterType)); } // 仅仅是需要读取整个请求流字符串, // 而且目标类型已经是字符串,就没有必要反序列化了,所以就直接以字符串返回 if (p.ParameterType == typeof(string)) { return(requst.GetPostText()); } throw new NotSupportedException("[FromBody]标记只能配合 JSON/XML 数据格式来使用。"); }
/// <summary> /// 通过json获取传过来的MenuModel,执行Add或Update /// </summary> /// <param name="input"></param> /// <returns></returns> public string addMenu(string input) { if (string.IsNullOrEmpty(input)) { return(JsonExtensions.ToJson(new MyHttpResult { result = false, msg = "提交数据错误!" })); } MenuModel menu = JsonExtensions.FromJson <MenuModel>(input); int iResult; if (menu.id == 0) { iResult = menu.Insert(); } else { iResult = menu.Update(); } return(JsonExtensions.ToJson(new MyHttpResult { result = iResult > 0 ? true : false, })); }
public static IObservable <Unit> ReloadWithTestWorker(params string[] args) { return(Rxn.Create <Unit>(o => { var apiName = args.Skip(1).FirstOrDefault(); var testHostUrl = GetTestarenaUrlFromArgs(args); theBfg.Args = args; RxnExtensions.DeserialiseImpl = (t, json) => JsonExtensions.FromJson(json, t); RxnExtensions.SerialiseImpl = (json) => JsonExtensions.ToJson(json); var cfg = RxnAppCfg.Detect(args); //var appStore = new CurrentDirectoryAppUpdateStore(); //var clusterHost = OutOfProcessFactory.CreateClusterHost(args, appStore, cfg); return theBfgDef.TestWorker(apiName, testHostUrl, RxnApp.SpareReator(testHostUrl)).ToRxns() .Named(new bfgAppInfo("bfgWorker")) .OnHost(new ConsoleHostedApp(), cfg) .SelectMany(h => h.Run().Do(app => { theBfg.IsReady.OnNext(app); })) .Select(app => { return new Unit(); }) .Subscribe(o); })); }
private string AddUnit(string input) { if (string.IsNullOrEmpty(input)) { return(JsonExtensions.ToJson(new MyHttpResult { result = false, msg = "提交数据错误!" })); } BusinessUnitModel bu = JsonExtensions.FromJson <BusinessUnitModel>(input); var userid = ((UserModel)Public.User_Info).id; bu.createby = Convert.ToInt32(1); bu.createon = DateTime.Now; int iResult; if (bu.id == 0)//新增id=0 { iResult = bu.Insert(); } else { iResult = bu.Update(); } return(JsonExtensions.ToJson(new MyHttpResult { result = iResult > 0 ? true : false, })); }
public void JsonSerialiationTestMitEinemKommando() { dynamic eingangsObjekt = new ExpandoObject(); eingangsObjekt.cmd = "Fragebogen anzeigen"; eingangsObjekt.payload = new ExpandoObject(); eingangsObjekt.payload.Fragen = Util.FrageListeErstellen(); Console.WriteLine(eingangsObjekt.payload.Fragen[0].Text); // wandeln in json und zurück wandeln var json = JsonExtensions.ToJson(eingangsObjekt); dynamic ausgangsObjekt = JsonExtensions.FromJson(json); Assert.IsNotNull(ausgangsObjekt); Assert.AreEqual(eingangsObjekt.cmd, ausgangsObjekt.cmd); Console.WriteLine(ausgangsObjekt.cmd); Assert.IsNotNull(ausgangsObjekt.payload.Fragen); Assert.IsNotNull(ausgangsObjekt.payload.Fragen[0], "Fragen[0] darf nicht null sein"); dynamic f = ausgangsObjekt.payload.Fragen[0]; Assert.AreEqual(eingangsObjekt.payload.Fragen[0].Text, f.Text, "Text aus der ersten Frage als dynamic gecastet muss dem EingangsObjekt-Text entprechen."); Assert.IsNotNull(ausgangsObjekt.payload.Fragen[0].Text, "Fragen[0].Text darf nicht null sein"); Console.WriteLine(ausgangsObjekt.payload.Fragen[0].Text); Assert.AreEqual(eingangsObjekt.payload.Fragen[0].Text, ausgangsObjekt.payload.Fragen[0].Text); }
private string SaveArticle(string input) { if (string.IsNullOrEmpty(input)) { return(new MyHttpResult(false, "入参不符合要求").ToString()); } ArticleModel artM = JsonExtensions.FromJson <ArticleModel>(input); MyHttpResult myRtn; if (artM.id == 0) { var user = (UserModel)Public.User_Info; artM.createby = user.id; artM.create_user = user.nickname; artM.create_date = DateTime.Now; myRtn = new MyHttpResult(artM.Insert() > 0 ? true : false, ""); } else { ArticleModel artM_old = (new ArticleBLL()).GetModel(artM.id); artM_old.title = artM.title; artM_old.art_type = artM.art_type; artM_old.content = artM.content; artM_old.ispublish = artM.ispublish; artM_old.description = (string.IsNullOrEmpty(artM.description) ? artM_old.description : artM.description); myRtn = new MyHttpResult((new ArticleBLL()).Update(artM_old) > 0 ? true : false, ""); } return(myRtn.ToString()); }
public void FromJsonString_Whitespace_ThrowsException() { string original = " "; _ = Assert.Throws <ArgumentException>( () => JsonExtensions .FromJson <DataContractClass>(original)); }
public void FromJsonString_NonJson_ThrowsException() { string original = "<value>1</value>"; _ = Assert.Throws <SerializationException>( () => JsonExtensions .FromJson <DataContractClass>(original)); }
public void FromJsonString_JsonWrongType_ThrowsException() { string original = "{\"anotherField\":\"value\"}"; _ = Assert.Throws <SerializationException>( () => JsonExtensions .FromJson <DataContractClass>(original)); }
public void FromJsonStream_Null_ThrowsException() { Stream original = null; _ = Assert.Throws <ArgumentNullException>( () => JsonExtensions .FromJson <DataContractClass>(original)); }
public void FromJsonStream_FilledEmpty_ThrowsException() { using Stream original = new MemoryStream(10); _ = Assert.Throws <ArgumentException>( () => JsonExtensions .FromJson <DataContractClass>(original)); }
private object GetObjectFromString(string input, ActionDescription action) { if (action.Parameters[0].ParameterType == typeof(string)) // 参数要求以 string 形式接收 { return(input); } return(JsonExtensions.FromJson(input, action.Parameters[0].ParameterType)); }
public void GETUserById() { var userID = 1; var request = new RestRequest($"/users/{userID}"); var response = _restclient.Get(request); var users = JsonExtensions.FromJson <User>(response.Content); Assert.IsTrue(response.IsSuccessful); }
private ISettings Load(string filePath) { if (!System.IO.File.Exists(filePath)) { throw new FileNotFoundException($"Settings file '{filePath}' does not exist."); } using var reader = System.IO.File.OpenText(filePath); return(JsonExtensions.FromJson <ISettings>(reader.ReadToEnd()) ?? throw new InvalidSettingsFileException(filePath)); }
public void GETBookById() { int bookID = 1; var request = new RestRequest($"/books/{bookID}"); var response = _restclient.Get(request); var book = JsonExtensions.FromJson <Book>(response.Content); Assert.IsTrue(response.IsSuccessful); }
public void FromJsonStream_WrongType_ThrowsException() { string original = "{\"anotherField\":\"value\"}"; var bytes = Encoding.UTF8.GetBytes(original); using Stream stream = new MemoryStream(bytes); _ = Assert.Throws <SerializationException>( () => JsonExtensions .FromJson <DataContractClass>(stream)); }
public void CreateOrUpdateRuleTest() { RuleCreateOrUpdateParameters expectedParameters = GetCreateOrUpdateRuleParameter(); var handler = new RecordedDelegatingHandler(); var insightsClient = GetInsightsManagementClient(handler); insightsClient.AlertOperations.CreateOrUpdateRule(resourceGroupName: "rg1", parameters: expectedParameters); var actualParameters = JsonExtensions.FromJson <RuleCreateOrUpdateParameters>(handler.Request); AreEqual(expectedParameters, actualParameters); }
public long CreateNewHousehold() { var household = HouseholdFactory.CreateNewHousehold(); var jsonHousehold = JsonExtensions.ToJson(household); var request = new RestRequest("/households", Method.POST); request.AddJsonBody(jsonHousehold); var response = _restclient.Post(request); var householdID = JsonExtensions.FromJson <Household>(response.Content).Id; Assert.IsTrue(response.IsSuccessful); return(householdID); }
public long CreateNewUser(long householdID) { var user = UserFactory.CreateNewUser(householdID); var jsonUser = JsonExtensions.ToJson(user); var request = new RestRequest("/users", Method.POST); request.AddJsonBody(jsonUser); var response = _restclient.Post(request); var wishlistID = JsonExtensions.FromJson <User>(response.Content).WishlistId; Assert.IsTrue(response.IsSuccessful); return(wishlistID); }
public void Input_Product() { string requestText = @" POST http://www.fish-web-demo.com/Ajax/test/ComplexDataType/Input_Product.aspx HTTP/1.1 X-Result-Format: JSON " + s_ProductFormData; // 测试:按FROM的键值对方式输入一个对象,要求在服务端反序列化成对象,并以JSON形式返回结果 string result = ExecuteService(requestText); Product p = JsonExtensions.FromJson <Product>(result); AssertProductFor_Input_Product(p); }
private static Response ExecuteMethod(RequestEpn request) { var data = request.ToJson(); string response; using (var webClient = new WebClient()) { response = webClient.UploadString(Url, data); } var responseObj = JsonExtensions.FromJson <Response>(response); return(responseObj); }
private List <GroupDailySummary2> LoadDataFromFile(DateTime day) { string filename = GetDataFileName(day); if (File.Exists(filename)) { string json = File.ReadAllText(filename, Encoding.UTF8); return(JsonExtensions.FromJson <List <GroupDailySummary2> >(json)); } else { return(null); } }
public void Input_int_Product() { string requestText = @" POST http://www.fish-web-demo.com/Ajax/test/ComplexDataType/Input_int_Product.aspx HTTP/1.1 " + s_ProductFormData + "&a=10"; // 测试:按FROM的键值对方式输入一个对象和一个整数参数 string result = ExecuteService(requestText); Product p = JsonExtensions.FromJson <Product>(result); p.Quantity -= 9; AssertProductFor_Input_Product(p); }
public void ListRulesTest() { RuleResourceCollection expectedRuleResourceCollection = JsonExtensions.FromJson <RuleResourceCollection>(ListRulesContent); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(ListRulesContent) }; var handler = new RecordedDelegatingHandler(response); var insightsClient = GetInsightsManagementClient(handler); RuleListResponse actualResponse = insightsClient.AlertOperations.ListRules(resourceGroupName: " rg1", targetResourceUri: "resUri"); AreEqual(expectedRuleResourceCollection, actualResponse.RuleResourceCollection); }
public static IObservable <Unit> ReloadAnd(string url = "http://*****:*****@test.dll and fire".LogDebug(); "fire".LogDebug(); "fire @url".LogDebug(); "fire rapidly {{threadCount | max}} | will fire on multiple threads simultatiously".LogDebug(); "fire compete | shard test-suite execution across multiple nodes".LogDebug(); "".LogDebug(); "launch [email protected] | deploy apps to worker nodes automatically during CI/CD. Worker integration via complementary C# api: theBfgApi.launch(\"app\", \"dir\")".LogDebug(); "".LogDebug(); "".LogDebug(); "<<USE WITH CAUTION>>".LogDebug(); "".LogDebug(); break; } return Disposable.Empty; })); }
public void Input_Product4() { string requestText = @" POST http://www.fish-mvc-demo.com/Ajax/test/ComplexDataType/Input_Product.aspx HTTP/1.1 X-Result-Format: JSON Content-Type: application/json " + s_ProductJson; // 测试:按JSON字符串方式输入一个对象,要求在服务端反序列化成对象,并以JSON形式返回结果 string result = ExecuteService(requestText); Product p = JsonExtensions.FromJson <Product>(result); AssertProductFor_Input_Product(p); }
public void CreateOrUpdateConfigurationTest() { MonitoringConfigurationCreateOrUpdateParameters expectedParameters = GetCreateOrUpdateConfigurationParameters(); var handler = new RecordedDelegatingHandler(); var insightsClient = GetInsightsManagementClient(handler); insightsClient.MonitoringConfigurationOperations.CreateOrUpdateConfiguration( resourceUri: "res1", parameters: expectedParameters); var fixedRequestString = handler.Request .Replace("\"aggregations\":", "\"metricAggregations\":"); var actualParameters = JsonExtensions.FromJson <MonitoringConfigurationCreateOrUpdateParameters>(fixedRequestString); AreEqual(expectedParameters.Properties, actualParameters.Properties); }
public void CreateOrUpdateSettingTest() { var handler = new RecordedDelegatingHandler(); InsightsManagementClient customClient = this.GetInsightsManagementClient(handler); AutoscaleSettingCreateOrUpdateParameters parameters = new AutoscaleSettingCreateOrUpdateParameters { Properties = CreateAutoscaleSetting(ResourceUri, "CpuPercentage", string.Empty), Location = "East US", Tags = new Dictionary <string, string> { { "tag1", "value1" } } }; customClient.AutoscaleOperations.CreateOrUpdateSetting("resourceGroup1", "setting1", parameters); var actualResponse = JsonExtensions.FromJson <AutoscaleSettingCreateOrUpdateParameters>(handler.Request); AreEqual(parameters.Properties, actualResponse.Properties); }
public void LogProfiles_PutTest() { var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(string.Empty), }; var handler = new RecordedDelegatingHandler(response); InsightsManagementClient customClient = this.GetInsightsManagementClient(handler); var parameters = new ServiceDiagnosticSettingsPutParameters { Properties = CreateDiagnosticSettings() }; customClient.ServiceDiagnosticSettingsOperations.Put(ResourceUri, parameters); var actualResponse = JsonExtensions.FromJson <ServiceDiagnosticSettingsPutParameters>(handler.Request); AreEqual(parameters.Properties, actualResponse.Properties); }
/// <summary> /// Role实体和权限字符串 /// </summary> /// <param name="auth"></param> /// <param name="json"></param> /// <returns></returns> public string addRole(string auth, string json) { if (string.IsNullOrEmpty(json)) { return(new MyHttpResult(false, "提交数据错误!").ToString()); } RoleModel model = JsonExtensions.FromJson <RoleModel>(json); int result; //1.判断是新增角色还是编辑角色 if (model.id == 0)//新增 { //1.新增角色 result = model.Insert(); //2.获得该实体的ID model.id = (new RoleBLL()).getByMax().id; } else //编辑 { result = model.Update(); } //2.删除该角色的所有权限 AccessBLL accessbll = new AccessBLL(); accessbll.deleteByRoleId(model.id.ToString()); //3.insert所有权限 if (!string.IsNullOrEmpty(auth)) { foreach (string roleAuth in auth.Split(",".ToCharArray())) { if (roleAuth != "") { AccessModel accessModel = new AccessModel(); accessModel.node_id = int.Parse(roleAuth); accessModel.role_id = model.id; result = accessModel.Insert(); } } } return(new MyHttpResult(result > 0 ? true : false, "").ToString()); }