/// <summary> /// /// </summary> /// <returns></returns> string ICallbackEventHandler.GetCallbackResult() { string argument = this._callbackArgument; this._callbackArgument = null; Dictionary <string, object> callInfo = JSONSerializerExecute.DeserializeObject(argument, typeof(Dictionary <string, object>)) as Dictionary <string, object>; string serverControlType = (string)callInfo["serverControlType"]; string originalControlID = (string)callInfo["originalControlID"]; Page page = HttpContext.Current.GetCurrentPage(); Control control = null; if (originalControlID.IsNotEmpty()) { control = page.FindControl(originalControlID); } if (control == null) { control = (Control)TypeCreator.CreateInstance(serverControlType); control.ID = originalControlID; page.Controls.Add(control); if (TargetControlLoaded != null) { TargetControlLoaded(control); } } return(ScriptObjectBuilder.ExecuteCallbackMethod(control, callInfo)); }
/// <summary> /// 加载ClientState /// </summary> /// <param name="clientState">序列化后的clientState</param> /// <remarks>加载ClientState</remarks> protected override void LoadClientState(string clientState) { base.LoadClientState(clientState); object[] foArray = JSONSerializerExecute.Deserialize <object[]>(clientState); if (foArray != null && foArray.Length > 0) { //已选择列表的Items if (foArray[0] != null && foArray.Length > 0) { this.selectedItems = (SelectItemCollection)JSONSerializerExecute.DeserializeObject(foArray[0], typeof(SelectItemCollection)); } //待选择列表的Items if (foArray[1] != null && foArray.Length > 1) { this.candidateItems = (SelectItemCollection)JSONSerializerExecute.DeserializeObject(foArray[1], typeof(SelectItemCollection)); } //按钮的Items if (foArray[2] != null && foArray.Length > 2) { this.buttonItems = (ButtonItemCollection)JSONSerializerExecute.DeserializeObject(foArray[2], typeof(ButtonItemCollection)); } //deltaItems if (foArray[3] != null && foArray.Length > 3) { this.deltaItems = (DeltaItemCollection)JSONSerializerExecute.DeserializeObject(foArray[3], typeof(DeltaItemCollection)); } } }
//---------------------------------我就素那无耻的分割线---------------------------------// #region ClientState /// <summary> /// 加载ClientState /// </summary> /// <remarks> /// 加载ClientState /// ClientState中保存的是一个长度为3的一维数组 /// 第一个为选中项目的索引值,如果没有选中则为-1 /// 第二个为选中项目的文本,或者输入的文本 /// 第三个是Items /// </remarks> /// <param name="clientState">序列化后的clientState</param> protected override void LoadClientState(string clientState) { base.LoadClientState(clientState); object[] foArray = JSONSerializerExecute.Deserialize <object[]>(clientState); if (null != foArray && foArray.Length > 0) { this.SelectedIndex = Convert.ToInt32(foArray[0]); if (foArray.Length > 1 && null != foArray[1]) { this.Text = foArray[1].ToString(); } else { this.Text = ""; } if (foArray.Length > 2 && null != foArray[2]) { this.items = (ListItemCollection)JSONSerializerExecute.DeserializeObject(foArray[2], typeof(ListItemCollection)); } else { this.items = new ListItemCollection(); } } else { this.SelectedIndex = -1; this.Text = ""; this.items = new ListItemCollection(); } }
/// <summary> /// 将ClientState字符串的信息加载到ClientState中 /// </summary> /// <remarks> /// 将ClientState字符串的信息加载到ClientState中 /// </remarks> /// <param name="clientState">ClientState字符串</param> protected override void LoadClientState(string clientState) { if (clientState == null || clientState == "null") { return; } object[] foArray = JSONSerializerExecute.Deserialize <object[]>(clientState); if (null != foArray && foArray.Length > 0) { OguDataCollection <IOguObject> objs = (OguDataCollection <IOguObject>)JSONSerializerExecute.DeserializeObject(foArray[0], typeof(OguDataCollection <IOguObject>)); this._selectedOuUserData = objs; if (foArray.Length > 1 && null != foArray[1]) { this.Text = foArray[1].ToString(); } else { this.Text = ""; } } else { this.SelectedOuUserData = new OguDataCollection <IOguObject>(); } }
/// <summary> /// 获取非固定列的总宽度 /// </summary> private void SettleTotleWidthOfNotFixeLines() { foreach (var item in this.Columns) { if (item.Visible) { IDictionary currentItemStyle = (IDictionary)JSONSerializerExecute.DeserializeObject(item.ItemStyle); string temp = "100"; if (currentItemStyle != null) { temp = DictionaryHelper.GetValue(currentItemStyle, "width", "100"); } if (temp.IndexOf("px") > 0) { temp = temp.Substring(0, temp.Length - 2); } if (temp.IndexOf("%") > 0) { temp = "160"; } if (!item.IsFixedLine) { this.TotleWidthOfNotFixeLines += int.Parse(temp); } else { this.TotleWidthOfFixeLines += int.Parse(temp); } //得到高度 IDictionary currentHeaderStyle = (IDictionary)JSONSerializerExecute.DeserializeObject(item.HeaderStyle); string temp2 = "24"; if (currentHeaderStyle != null) { temp2 = DictionaryHelper.GetValue(currentHeaderStyle, "height", "24"); } if (temp2.IndexOf("px") > 0) { temp2 = temp2.Substring(0, temp2.Length - 2); } if (temp.IndexOf("%") > 0) { this.HeadRowHeightWithFixeLines = 24; } else if (int.Parse(temp2) > HeadRowHeightWithFixeLines) { this.HeadRowHeightWithFixeLines = int.Parse(temp2); } } } }
public void DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters) { object bodyFormatProperty; if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("服务行为配置错误,请将WebHttpBinding的ContentTypeMapper属性设置为WfRawWebContentTypeMapper类型"); } try { PerformanceMonitorHelper.GetDefaultMonitor().WriteExecutionDuration("DeserializeRequest", () => { string jsonStr = WcfUtils.GetMessageRawContent(message); Dictionary <string, object> paramsInfo = JSONSerializerExecute.Deserialize <Dictionary <string, object> >(jsonStr); Dictionary <string, object> headers = PopHeaderInfo(paramsInfo); PushHeaderInfoToMessageProperties(message, headers); Dictionary <string, string> connectionMappings = PopConnectionMappings(paramsInfo); PushConnectionMappingsToMessageProperties(message, connectionMappings); Dictionary <string, object> context = PopContextInfo(paramsInfo); PushContextToMessageProperties(message, context); GenericTicketTokenContainer container = PopGenericTicketTokenContainer(paramsInfo); PushGenericTicketTokenContainer(message, container); for (int i = 0; i < _OperationDesc.Messages[0].Body.Parts.Count; i++) { string paramName = _OperationDesc.Messages[0].Body.Parts[i].Name; Type targetType = this._OperationDesc.Messages[0].Body.Parts[i].Type; object val = paramsInfo[paramName]; try { parameters[i] = JSONSerializerExecute.DeserializeObject(val, targetType); } catch (System.Exception ex) { string errorMessage = string.Format("反序列化参数{0}错误,类型为{1}:{2}", paramName, targetType.ToString(), ex.Message); throw new InvalidDataException(errorMessage, ex); } } }); } catch (Exception ex) { throw new InvalidOperationException("传入的JSON格式错误:" + ex.Message, ex); } }
public override object Deserialize(IDictionary <string, object> dictionary, Type type, JavaScriptSerializer serializer) { #region "base Deserialize" string key = DictionaryHelper.GetValue(dictionary, "Key", string.Empty); WfActivityDescriptor actDesp = (WfActivityDescriptor)CreateInstance(key, dictionary, type, serializer); actDesp.Name = DictionaryHelper.GetValue(dictionary, "Name", string.Empty);; actDesp.Enabled = DictionaryHelper.GetValue(dictionary, "Enabled", false); actDesp.Description = DictionaryHelper.GetValue(dictionary, "Description", string.Empty); Dictionary <string, object> activityProperties = new Dictionary <string, object>(); Dictionary <string, Type> constKey = new Dictionary <string, Type>(); constKey.Add("Variables", typeof(WfVariableDescriptorCollection)); constKey.Add("Condition", typeof(WfConditionDescriptor)); constKey.Add("BranchProcessTemplates", typeof(WfBranchProcessTemplateCollection)); constKey.Add("Resources", typeof(WfResourceDescriptorCollection)); constKey.Add("RelativeLinks", typeof(WfRelativeLinkDescriptorCollection)); constKey.Add("EnterEventReceivers", typeof(WfResourceDescriptorCollection)); constKey.Add("LeaveEventReceivers", typeof(WfResourceDescriptorCollection)); constKey.Add("InternalRelativeUsers", typeof(WfResourceDescriptorCollection)); constKey.Add("ExternalUsers", typeof(WfExternalUserCollection)); constKey.Add("EnterEventExecuteServices", typeof(WfServiceOperationDefinitionCollection)); constKey.Add("LeaveEventExecuteServices", typeof(WfServiceOperationDefinitionCollection)); constKey.Add("WithdrawExecuteServices", typeof(WfServiceOperationDefinitionCollection)); constKey.Add("BeWithdrawnExecuteServices", typeof(WfServiceOperationDefinitionCollection)); constKey.Add("ParametersNeedToBeCollected", typeof(WfParameterNeedToBeCollected)); if (dictionary.ContainsKey("Properties")) { PropertyValueCollection properties = JSONSerializerExecute.Deserialize <PropertyValueCollection>(dictionary["Properties"]); properties.Remove(p => string.Compare(p.Definition.Name, "ImportWfMatrix") == 0); //properties.Remove(p => string.Compare(p.Definition.Name, "BranchProcessTemplates") == 0); actDesp.Properties.Clear(); foreach (PropertyValue pv in properties) { if (constKey.ContainsKey(pv.Definition.Name)) { var objValue = JSONSerializerExecute.DeserializeObject(pv.StringValue, constKey[pv.Definition.Name]); activityProperties.Add(pv.Definition.Name, objValue); } else { actDesp.Properties.Add(pv); } } } #endregion actDesp.ActivityType = DictionaryHelper.GetValue(dictionary, "ActivityType", WfActivityType.NormalActivity); ClearAllProperties(actDesp); SetActivityProperties(actDesp, activityProperties, dictionary); return(actDesp); }
protected virtual string GetCallbackResult() { string argument = _callbackArgument; _callbackArgument = null; Dictionary <string, object> callInfo = JSONSerializerExecute.DeserializeObject(argument, typeof(Dictionary <string, object>)) as Dictionary <string, object>; return(ScriptObjectBuilder.ExecuteCallbackMethod(this, callInfo)); }
public static RelativeTicket DecryptFromString(string ticketString) { ExceptionHelper.CheckStringIsNullOrEmpty(ticketString, "ticketString"); byte[] data = Convert.FromBase64String(ticketString); string decData = RelativeTicketSettings.GetConfig().Encryptor.DecryptString(data); RelativeTicket ticket = (RelativeTicket)JSONSerializerExecute.DeserializeObject(decData, typeof(RelativeTicket)); return(ticket); }
protected override void OnInit(EventArgs e) { if (WebUtility.GetRequestQueryString("_op", string.Empty) == "lockCallBack") { if (string.Compare(Page.Request.HttpMethod, "POST", true) == 0) { string cmd = WebUtility.GetRequestQueryString("cmd", string.Empty); string requestData = string.Empty; string result = string.Empty; try { using (StreamReader sr = new StreamReader(Page.Request.InputStream)) { requestData = sr.ReadToEnd(); Lock[] locks = (Lock[])JSONSerializerExecute.DeserializeObject(requestData, typeof(Lock[])); List <Lock> addLocks = new List <Lock>(); switch (cmd) { case "checkLock": Array.ForEach(locks, l => addLocks.Add(LockAdapter.SetLock(l).NewLock)); break; case "unlock": LockAdapter.Unlock(locks); break; default: throw new ApplicationException(string.Format("Invalid command {0}", cmd)); } result = JSONSerializerExecute.Serialize(addLocks.ToArray()); } } catch (System.Exception ex) { var err = new { type = "$ErrorType", message = ex.Message }; result = JSONSerializerExecute.Serialize(err); } finally { Page.Response.Write(result); Page.Response.End(); } } } else { base.OnInit(e); } }
/// <summary> /// 如果内部保存了Json,则返回反序列化的字典。否则直接返回Value /// </summary> /// <returns></returns> public object GetDeserializedValue() { object result = this._Value; if (this._ParamJsonValue.IsNotEmpty()) { ExceptionHelper.DoSilentAction(() => result = JSONSerializerExecute.DeserializeObject(this._ParamJsonValue)); } return(result); }
private static object DeserializeJson(object originalValue, string json) { object result = originalValue; if (originalValue is UnknownSerializationType && json.IsNotEmpty()) { ExceptionHelper.DoSilentAction(() => result = JSONSerializerExecute.DeserializeObject(json)); } return(result); }
protected override void LoadClientState(string clientState) { string[] state = (string[])JSONSerializerExecute.DeserializeObject(clientState, typeof(string[])); this.opinionText = state[0]; this.opinionType = state[1]; if (string.IsNullOrEmpty(opinionType) == false) { OpinionInput.SetOpinionType(this.opinionType); } }
public void Int32To64JsonTest() { Int64 ticks = 32L; string json = JSONSerializerExecute.Serialize(ticks); Console.WriteLine(json); Int64 deserialized = (Int64)JSONSerializerExecute.DeserializeObject(ticks.ToString(), typeof(Int64)); Assert.AreEqual(ticks, deserialized); }
protected void Page_Load(object sender, EventArgs e) { //JavaScriptSerializer s = JSONSerializerFactory.GetJavaScriptSerializer(typeof(MCS.Web.WebControls.SampleObject)); Label1.Style.Add("Width", "200px"); Label1.Style.Add("Height", "100px"); //s.Serialize(Label1.Style); TextBox1.Text = "{\"DT\":\"\\/Date(1181611809135)\\/\",\"Name\":\"Hujintao\",\"Height\":180,\"__type\":\"MCS.Web.WebControls.SampleObject\"}";//"{\"name\":\"SetSampleObject\",\"args\":[{\"DT\":\"\\/Date(1181611809135)\\/\",\"Name\":\"Hujintao\",\"Height\":180,\"__type\":\"MCS.Web.WebControls.SampleObject, MCS.Web.WebControls\"}],\"state\":null}";// s.Serialize(Label1.Style); object o = JSONSerializerExecute.DeserializeObject(TextBox1.Text, typeof(MCS.Web.WebControls.SampleObject)); Response.Write(o.GetType().AssemblyQualifiedName); }
private void ProcessUploadData() { HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; try { ExceptionHelper.FalseThrow(request["postedData"].IsNotEmpty(), Translator.Translate(Define.DefaultCulture, "没有上传的数据")); ProcessProgress.Current.RegisterResponser(UploadProgressResponser.Instance); response.Write(new string(' ', 4096)); this.ClientExtraPostedData = request.Form["clientExtraPostedData"]; PostProgressPrepareDataEventArgs prepareDataArgs = new PostProgressPrepareDataEventArgs() { SerializedData = request["postedData"] }; OnPrepareData(this, prepareDataArgs); if (prepareDataArgs.DeserializedData == null) { prepareDataArgs.DeserializedData = (IList)JSONSerializerExecute.DeserializeObject(prepareDataArgs.SerializedData); } response.Buffer = false; response.BufferOutput = false; UploadProgressResult result = new UploadProgressResult(); OnDoPostedData(this, new PostProgressDoPostedDataEventArgs() { Result = result, ClientExtraPostedData = this.ClientExtraPostedData, Steps = prepareDataArgs.DeserializedData }); result.Response(); } catch (System.Exception ex) { response.Write(string.Format("<script type=\"text/javascript\">top.document.getElementById(\"resetInterfaceButton\").click();</script>")); WebUtility.ResponseShowClientErrorScriptBlock(ex.Message, ex.StackTrace, Translator.Translate(Define.DefaultCulture, "错误")); } finally { response.End(); } }
protected void BtnUpdateUserSetting(object sender, EventArgs e) { try { UserSettings objUserSettings = (UserSettings)JSONSerializerExecute.DeserializeObject(txtDataSource.Text, typeof(UserSettings)); objUserSettings.Update(); this.ClientScript.RegisterClientScriptBlock(this.GetType(), "RefreshParent", "<script type = 'text/javascript'>window.returnValue = 'reload';</script>"); WebUtility.CloseWindow(); } catch (Exception ex) { WebUtility.ShowClientError(ex.Message, ex.StackTrace, "错误"); } }
public void SyncPropertiesToFields(PropertyValue property) { if (property != null) { this.Clear(); if (property.StringValue.IsNotEmpty()) { IEnumerable <T> deserializedData = (IEnumerable <T>)JSONSerializerExecute.DeserializeObject(property.StringValue, this.GetType()); this.CopyFrom(deserializedData); } } }
protected override void LoadClientState(string clientState) { object[] state = JSONSerializerExecute.Deserialize <object[]>(HttpUtility.UrlDecode(clientState)); if (state[1] != null) { string typeDesp = (string)state[1]; if (string.IsNullOrEmpty(typeDesp) == false && state[0] != null) { Type type = TypeCreator.GetTypeInfo(typeDesp); this.initialData = (IList)JSONSerializerExecute.DeserializeObject(state[0], type); } } }
protected override void LoadClientState(string clientState) { if (string.IsNullOrEmpty(clientState) == false) { object[] state = (object[])JSONSerializerExecute.DeserializeObject(clientState, typeof(object[])); object[] state0 = (object[])state[0]; List <IOguObject> selectedResult = new List <IOguObject>(); foreach (IOguObject obj in state0) { selectedResult.Add(obj); } this.selectedOuUserData = new OguDataCollection <IOguObject>(selectedResult); } }
/// <summary> /// 加载ClientState /// </summary> /// <param name="clientState">客户端状态</param> protected override void LoadClientState(string clientState) { if (string.IsNullOrEmpty(clientState) == false) { object[] state = (object[])JSONSerializerExecute.DeserializeObject(clientState, typeof(object[])); this.scrollLeft = (int)state[0]; this.scrollTop = (int)state[1]; DeluxeTreeNode[] nodes = JSONSerializerExecute.Deserialize <DeluxeTreeNode[]>(state[2]); this.nodes.Clear(); foreach (DeluxeTreeNode node in nodes) { this.nodes.Add(node); } } }
protected override void LoadClientState(string clientState) { object[] state = (object[])JSONSerializerExecute.DeserializeObject(clientState); object tempState; if (state[0] is object[]) { object[] tempResult = (object[])state[0]; tempState = tempResult[0]; } else { tempState = state[0]; } this.imgProp = JSONSerializerExecute.Deserialize <ImageProperty>(tempState); string postedControlID = GetPostedControlID(); if (postedControlID.IsNullOrEmpty()) { postedControlID = ((string)state[1]).Replace('_', '$'); } HttpPostedFile file = GetPostFile(postedControlID); if (file != null) { if (this.imgProp.ID.IsNullOrEmpty()) { this.imgProp.ID = UuidHelper.NewUuidString(); } this.imgProp.NewName = UuidHelper.NewUuidString() + Path.GetExtension(imgProp.OriginalName); this.imgProp.Changed = true; string filePath; ImageUploadHelper.UploadFile(this, file, this.imgProp.OriginalName, this.imgProp.NewName, out filePath); } }
/// <summary> /// 反序列化服务调用的返回结果 /// </summary> /// <param name="message"></param> /// <param name="parameters"></param> /// <returns></returns> public object DeserializeReply(System.ServiceModel.Channels.Message message, object[] parameters) { object bodyFormatProperty; if (message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) == false || (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw) { throw new InvalidOperationException("服务行为配置错误,请将WebHttpBinding的ContentTypeMapper属性设置为WfRawWebContentTypeMapper类型"); } try { string jsonStr = WcfUtils.GetMessageRawContent(message); return(JSONSerializerExecute.DeserializeObject(jsonStr, _OperationDesc.Messages[1].Body.ReturnValue.Type)); } catch (Exception ex) { throw new InvalidOperationException("传入的JSON格式错误:" + ex.Message, ex); } }
private void PrepareDataButton_Click(object sender, EventArgs e) { try { if (this.ExecutePrepareData != null) { HttpContext.Current.Response.Buffer = false; string serializedData = HttpContext.Current.Request.Form["preparedData"]; object data = JSONSerializerExecute.DeserializeObject(serializedData); object result = this.ExecutePrepareData(data, this); ResponsePrepareDataResult(result); } } catch (System.Exception ex) { ResponseExceptionInfo(ex); } finally { HttpContext.Current.Response.End(); } }
public override object Deserialize(IDictionary <string, object> dictionary, Type type, System.Web.Script.Serialization.JavaScriptSerializer serializer) { //WfProcessDescriptor processDesp = (WfProcessDescriptor)base.Deserialize(dictionary, type, serializer); #region "base Deserialize" string key = DictionaryHelper.GetValue(dictionary, "Key", string.Empty); WfProcessDescriptor processDesp = (WfProcessDescriptor)CreateInstance(key, dictionary, type, serializer); processDesp.Name = DictionaryHelper.GetValue(dictionary, "Name", string.Empty);; processDesp.Enabled = DictionaryHelper.GetValue(dictionary, "Enabled", false); processDesp.Description = DictionaryHelper.GetValue(dictionary, "Description", string.Empty); Dictionary <string, object> processProperties = new Dictionary <string, object>(); Dictionary <string, Type> constKey = new Dictionary <string, Type>(); constKey.Add("RelativeLinks", typeof(WfRelativeLinkDescriptorCollection)); constKey.Add("CancelEventReceivers", typeof(WfResourceDescriptorCollection)); constKey.Add("CompleteEventReceivers", typeof(WfResourceDescriptorCollection)); constKey.Add("InternalRelativeUsers", typeof(WfResourceDescriptorCollection)); constKey.Add("ExternalUsers", typeof(WfExternalUserCollection)); constKey.Add("Variables", typeof(WfVariableDescriptorCollection)); constKey.Add("ParametersNeedToBeCollected", typeof(WfParameterNeedToBeCollected)); constKey.Add("CancelBeforeExecuteServices", typeof(WfServiceOperationDefinitionCollection)); constKey.Add("CancelAfterExecuteServices", typeof(WfServiceOperationDefinitionCollection)); if (dictionary.ContainsKey("Properties")) { PropertyValueCollection properties = JSONSerializerExecute.Deserialize <PropertyValueCollection>(dictionary["Properties"]); properties.Remove(p => string.Compare(p.Definition.Name, "ImportWfMatrix") == 0); processDesp.Properties.Clear(); foreach (PropertyValue pv in properties) { if (constKey.ContainsKey(pv.Definition.Name)) { var objValue = JSONSerializerExecute.DeserializeObject(pv.StringValue, constKey[pv.Definition.Name]); processProperties.Add(pv.Definition.Name, objValue); } else { processDesp.Properties.Add(pv); } } } #endregion processDesp.GraphDescription = DictionaryHelper.GetValue(dictionary, "GraphDescription", string.Empty); WfActivityDescriptorCollection activities = JSONSerializerExecute.Deserialize <WfActivityDescriptorCollection>(dictionary["Activities"]); processDesp.Activities.Clear(); processDesp.Activities.CopyFrom(activities); ClearAllProperties(processDesp); SetProcessProperties(processDesp, processProperties, dictionary); ToTransitionsDescriptorCollection transitions = JSONSerializerExecute.Deserialize <ToTransitionsDescriptorCollection>(dictionary["Transitions"]); foreach (WfTransitionDescriptor tranDesp in transitions) { WfActivityDescriptor fromActDesc = (WfActivityDescriptor)processDesp.Activities[tranDesp.FromActivityKey]; WfActivityDescriptor toActDesc = (WfActivityDescriptor)processDesp.Activities[tranDesp.ToActivityKey]; if (fromActDesc != null && toActDesc != null) { fromActDesc.ToTransitions.AddTransition(toActDesc, tranDesp); } } return(processDesp); }
public static string ExecuteCallbackMethod(Control control, Dictionary <string, object> callInfo) { string methodName = (string)callInfo["name"]; object[] args = (object[])callInfo["args"]; string clientState = (string)callInfo["state"]; // Attempt to load the client state IClientStateManager csm = control as IClientStateManager; if (csm != null && csm.SupportsClientState) { csm.LoadClientState(clientState); } // call the method object result = null; Dictionary <string, object> error = null; Type controlType = control.GetType(); try { // Find a matching static or instance method. Only public methods can be invoked MethodInfo mi = controlType.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance); if (mi == null) { throw new MissingMethodException(controlType.FullName, methodName); } // Verify that the method has the corrent number of parameters as well as the ScriptControlMethodAttribute ParameterInfo[] methodParams = mi.GetParameters(); ScriptControlMethodAttribute methAttr = (ScriptControlMethodAttribute)Attribute.GetCustomAttribute(mi, typeof(ScriptControlMethodAttribute)); if (methAttr == null || !methAttr.IsScriptMethod || args.Length != methodParams.Length) { throw new MissingMethodException(controlType.FullName, methodName); } // Convert each argument to the parameter type if possible // NOTE: I'd rather have the ObjectConverter from within Microsoft.Web.Script.Serialization namespace for this object[] targetArgs = new object[args.Length]; for (int i = 0; i < targetArgs.Length; i++) { if (args[i] == null) { continue; } targetArgs[i] = JSONSerializerExecute.DeserializeObject(args[i], methodParams[i].ParameterType); } result = mi.Invoke(control, targetArgs); } catch (Exception ex) { // Catch the exception information to relay back to the client if (ex is TargetInvocationException) { ex = ex.InnerException; } error = new Dictionary <string, object>(); error["name"] = ex.GetType().FullName; error["message"] = ex.Message; if (WebAppSettings.AllowResponseExceptionStackTrace()) { error["stackTrace"] = ex.StackTrace; } else { error["stackTrace"] = string.Empty; } TryWriteLog(ex, control); } // return the result Dictionary <string, object> resultInfo = new Dictionary <string, object>(); if (error == null) { resultInfo["result"] = result; if (csm != null && csm.SupportsClientState) { resultInfo["state"] = csm.SaveClientState(); } } else { resultInfo["error"] = error; } // Serialize the result info into JSON return(JSONSerializerExecute.Serialize(resultInfo)); }
protected override void LoadClientState(string clientState) { if (string.IsNullOrEmpty(clientState) == false) { DoActionAfterRegisterContextConverter(() => this._MoveToSelectedResult = (WfMoveToSelectedResult)JSONSerializerExecute.DeserializeObject(clientState, typeof(WfMoveToSelectedResult))); } }
/// <summary> /// 调用服务 /// </summary> /// <param name="timeout">请求超时时间,单位毫秒</param> /// <param name="context">上下文参数</param> /// <returns></returns> public object Invoke(TimeSpan timeout, WfApplicationRuntimeParameters context) { try { if (context == null) { context = WfServiceInvoker.InvokeContext; } HttpWebRequest request = GenerateWebRequestObj(timeout, context); try { using (WebResponse response = request.GetResponse()) { using (Stream stream = response.GetResponseStream()) { object result = null; if (stream != null) { StreamReader streamReader = new StreamReader(stream, Encoding.UTF8); string rtnContent = streamReader.ReadToEnd(); result = ParseServiceResultToObject(rtnContent); if (result == null) { result = ExceptionHelper.DoSilentFunc(() => JSONSerializerExecute.DeserializeObject(rtnContent), rtnContent); if (result is WfErrorDTO) { string errorMessage = ((WfErrorDTO)result).ToString() + Environment.NewLine + request.RequestUri.ToString(); throw new WfServiceInvokeException(((WfErrorDTO)result).ToString()); } } } if (result is IDictionary <string, object> ) { foreach (KeyValuePair <string, object> kp in (IDictionary <string, object>)result) { context[kp.Key] = kp.Value; } } if (this._SvcOperationDef.RtnXmlStoreParamName.IsNotEmpty()) { context[this._SvcOperationDef.RtnXmlStoreParamName] = result; } return(result); } } } catch (WebException ex) { if (ex.Response == null) { throw new WfServiceInvokeException(string.Format("调用服务时发生了异常,{0},但无响应内容。HTTP状态为{1}", ex.Message, ex.Status), ex); } else { throw WfServiceInvokeException.FromWebResponse(ex.Response); } } } catch (WebException ex) { throw new WfServiceInvokeException(ex.Message, ex); } }
/// <summary> /// 在此处理客户端传来的ClientState字符串值 /// </summary> /// <param name="clientState"></param> protected override void LoadClientState(string clientState) { List <SampleObject> objs = (List <SampleObject>)JSONSerializerExecute.DeserializeObject(clientState, typeof(List <SampleObject>)); }