/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = (ResponseInfo)response; responseInfo.Headers.ContentType = responseInfo.Request.Headers[Header.Accept].Values.First(value => (value.Value == ApplicationXml) || (value.Value == TextXml)).Value; if (instance != null) { if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } var serializer = CreateSerializer(givenType, instance); serializer.WriteObject(responseInfo.Body, instance); } }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } if (givenType != typeof(byte[])) { return(CompatibilityLevel.None); } var result = CompatibilityLevel.ExactTypeMatch; var responseInfo = (ResponseInfo)response; var accept = responseInfo.Request.Headers[Header.Accept]; if (accept != null) { if (accept.Values.Any(value => (value.Value == ApplicationOctetStream))) { result |= CompatibilityLevel.ExactProtocolMatch; } else if (accept.Values.Any(value => (value.Value == AnyAny))) { result |= CompatibilityLevel.ProtocolMatch; } } return(result); }
/// <inheritdoc /> public Task Process(IResponseInfo responseInfo) { if (responseInfo == null) { throw new ArgumentNullException("responseInfo"); } var response = responseInfo as ResponseInfo; if (response == null) { throw new ArgumentOutOfRangeException("responseInfo"); } string matchingOrigin; if ((String.IsNullOrEmpty(response.Request.Headers.Origin)) || ((matchingOrigin = IsOriginAllowed(response.Request.Headers.Origin)) == null)) { return(Task.FromResult(0)); } response.Headers.AccessControlAllowOrigin = matchingOrigin; response.Headers.AccessControlExposeHeaders = (!_exposeAnyHeader ? _exposedHeaders : String.Join(", ", ExposedHeaders(response.Request.Headers))); response.Headers.AccessControlAllowHeaders = _allowedHeaders; return(Task.FromResult(0)); }
private void WriteResponseBody(IGraph graph, string mediaType, IResponseInfo response) { var writer = CreateWriter(mediaType); if (writer is RdfXmlWriter) { Stream buffer = new MemoryStream(); buffer = new UnclosableStream(buffer); using (var textWriter = new StreamWriter(buffer)) { writer.Save(graph, textWriter); } buffer.Seek(0, SeekOrigin.Begin); XmlDocument document = new XmlDocument(); document.Load(buffer); document.InsertAfter( document.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"" + DocumentationStylesheet + "\""), document.FirstChild); document.Save(response.Body); } else { using (var textWriter = new StreamWriter(response.Body)) { writer.Save(graph, textWriter); } } }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } if (givenType.GetItemType() != typeof(string)) { return(CompatibilityLevel.None); } var result = CompatibilityLevel.ExactTypeMatch; var responseInfo = (ResponseInfo)response; var accept = responseInfo.Request.Headers[Header.Accept]; if ((accept != null) && (accept.Values.Any(value => value == TextPlain))) { result |= CompatibilityLevel.ExactProtocolMatch; } return(result); }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var actualGivenType = givenType.FindItemType(); if (!typeof(IEntity).IsAssignableFrom(actualGivenType)) { return(CompatibilityLevel.None); } var result = CompatibilityLevel.ExactTypeMatch; var requestInfo = (RequestInfo)response.Request; var accept = requestInfo.Headers[Header.Accept]; if ((accept != null) && (accept.Values.Join(MediaTypes, outer => outer.Value, inner => inner, (outer, inner) => outer).Any())) { result |= CompatibilityLevel.ExactProtocolMatch; } return(result); }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = (ResponseInfo)response; responseInfo.Headers.ContentType = ApplicationOctetStream; if (response == null) { throw new ArgumentNullException("response"); } if (instance != null) { if (!givenType.IsAssignableFrom(instance.GetType())) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } using (var writer = new StreamWriter(responseInfo.Body)) { writer.Write(Convert.ToBase64String((byte[])instance)); writer.Flush(); } } }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = (ResponseInfo)response; responseInfo.Headers.ContentType = ApplicationJson; if ((instance != null) && (!givenType.IsInstanceOfType(instance))) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } using (var writer = new StreamWriter(responseInfo.Body)) using (var jsonWriter = new JsonTextWriter(writer)) { new JsonSerializer().Serialize(jsonWriter, instance); jsonWriter.Flush(); } }
private ChatResponse MapToChatResponse(IResponseInfo responseInfo, ChatSession session) { return(new ChatResponse { Message = responseInfo.Message, Session = MapToChatRequest(session) }); }
/// <inheritdoc /> public override void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = (ResponseInfo)response; var contentType = responseInfo.Request.Headers[Header.ContentType]; if ((contentType != null) && (contentType.Values.Any(value => value.Value == TextUriList))) { responseInfo.Headers.ContentType = TextUriList; if (instance != null) { if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } string content = null; if (!System.TypeExtensions.IsEnumerable(givenType)) { content = instance.ToString(); } else { var builder = new StringBuilder(1024); foreach (var item in (IEnumerable)instance) { builder.AppendFormat("{0}\r\n", item); } content = builder.ToString().TrimEnd('\r', '\n'); } using (var writer = new StreamWriter(responseInfo.Body)) { writer.Write(content); writer.Flush(); } } else if (responseInfo.Status == HttpStatusCode.OK) { responseInfo.Status = HttpStatusCode.NoContent; } } else { base.ConvertFrom(givenType, instance, response); } }
public override void Communicate(IResponseInfo info) { object obj = this.Protocol.DriverAnalysis <String, String>("writefile", info.Data, null, null); if (obj.ToString() == "0") { OnDeviceRuningLog("写入文件成功"); } else { OnDeviceRuningLog("写入文件失败"); } }
public bool Handle(IParameters parameters, string response) { if (parameters == null) throw new ArgumentNullException(nameof(parameters)); IResponseParser parser = _parsers.FirstOrDefault(m => m.CanParse(parameters)); if (parser == null) throw new RandomOrgRuntimeException(ResourceHelper.GetString(StringsConstants.ERROR_CODE_100)); ResponseInfo = parser.Parse(response); return true; }
/// <inheritdoc /> public async Task Process(IResponseInfo response) { if (response == null) { throw new ArgumentNullException("response"); } var httpResponse = response as ResponseInfo; if (httpResponse == null) { throw new ArgumentOutOfRangeException("response"); } await Challenge(httpResponse); }
/// <inheritdoc /> public virtual void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = (ResponseInfo)response; responseInfo.Headers.ContentType = StringConverter.TextPlain; if (instance == null) { return; } if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } string content; if (!System.TypeExtensions.IsEnumerable(givenType)) { content = String.Format(CultureInfo.InvariantCulture, "{0}", instance); } else { var builder = new StringBuilder(1024); foreach (var item in (IEnumerable)instance) { builder.AppendFormat(CultureInfo.InvariantCulture, "{0}\r\n", item); } content = builder.ToString().TrimEnd('\r', '\n'); } using (var writer = new StreamWriter(responseInfo.Body)) { writer.Write(content); writer.Flush(); } }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (response == null) { throw new ArgumentNullException("response"); } var result = CompatibilityLevel.ProtocolMatch; if (response is ExceptionResponseInfo) { result |= CompatibilityLevel.ExactTypeMatch; } return(result); }
/// <summary>Converts an object into a string response body.</summary> /// <param name="converterProvider">Converter provider.</param> /// <param name="value">The value.</param> /// <param name="response">Optional response.</param> /// <returns>String representation of the given <paramref name="value" />.</returns> public static string ConvertFrom(this IConverterProvider converterProvider, object value, IResponseInfo response = null) { if (value == null) { return null; } bool success; string result = ConvertUsingTypeConverters(value, out success); if (success) { return result; } if (converterProvider == null) { throw new ArgumentNullException("converterProvider"); } return ConvertUsingCustomConverters(converterProvider, response, value); }
private void ExecuteSendRequest() { IResponseInfo result = null; try { result = RestManager.GetInstance().MakeRequest(RequestUrl, SelectedHttpVerb, "text/xml", PostData); } catch (RestException restEx) { Messenger.Default.Send <GenericMessage <string> >(new GenericMessage <string>(restEx.Message), "RestException"); return; } ResponseBody = result.ResponseData; ResponseHeaders = GetResponseHeaders(result.ResponseHeaders); ResponseStatus = GetResponseStatus(result.ResponseStatusCode); Histories.Insert(0, new RequestInfo() { Url = RequestUrl, Verb = SelectedHttpVerb }); }
/// <inheritdoc /> public IConverter FindBestOutputConverter(Type expectedType, IResponseInfo response) { if (_converters == null) { throw new InvalidOperationException("Default converter provider is not initialized."); } if (expectedType == null) { throw new ArgumentNullException("expectedType"); } if (response == null) { throw new ArgumentNullException("response"); } var result = (from item in _converters let level = item.CanConvertFrom(expectedType, response) where ((level & CompatibilityLevel.ProtocolMatch) == CompatibilityLevel.ProtocolMatch) && ((level & CompatibilityLevel.TypeMatch) == CompatibilityLevel.TypeMatch) orderby level descending orderby(expectedType.GetItemType() != typeof(string) ? 1 : 0) descending select item).FirstOrDefault(); if (result != null) { return(result); } if (response.Request.OutputNeutral) { return((from item in _converters let level = item.CanConvertTo(expectedType, response.Request) orderby level descending select item).FirstOrDefault()); } return(null); }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var result = CompatibilityLevel.TypeMatch; var responseInfo = (ResponseInfo)response; var accept = responseInfo.Request.Headers[Header.Accept]; if ((accept != null) && (accept.Values.Any(value => (value.Value == ApplicationXml) || (value.Value == TextXml)))) { result |= CompatibilityLevel.ExactProtocolMatch; } return(result); }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (instance == null) { return; } if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } ProtocolException exception = ((Exception)instance).AsHttpException(); ResponseInfo responseInfo = (ResponseInfo)response; var message = String.Format( "{0:000} {1} \"{2}\"", (uint)exception.HResult % 999, exception.Source ?? responseInfo.Request.Url.Host, System.Web.HttpUtility.JavaScriptStringEncode(exception.Message)); responseInfo.Headers.Add(new Header(Header.Warning, message)); responseInfo.Status = exception.Status; using (var writer = new StreamWriter(responseInfo.Body, responseInfo.Encoding)) { writer.Write( "{{{0}\t\"title\":\"{2}\",{0}\t\"details\":\"{3}\",\"status\":{1}{0}}}", Environment.NewLine, (int)exception.Status, System.Web.HttpUtility.JavaScriptStringEncode(exception.Message), System.Web.HttpUtility.JavaScriptStringEncode(exception.InnerException != null ? exception.InnerException.StackTrace : exception.StackTrace)); } }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } if (instance == null) { return; } if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(String.Format("Instance type '{0}' mismatch from the given '{1}'.", instance.GetType(), givenType)); } var responseInfo = (ResponseInfo)response; var requestInfo = responseInfo.Request; var accept = requestInfo.Headers[Header.Accept]; var mediaType = accept.Values.Join(MediaTypes, outer => outer.Value, inner => inner, (outer, inner) => outer.Value).First(); if (String.IsNullOrEmpty(responseInfo.Headers.ContentType)) { responseInfo.Headers.ContentType = mediaType; } //// TODO: Add support for graph based serializations. var graph = CreateResultingGraph(instance, (Uri)requestInfo.Url); WriteResponseBody(graph, mediaType, response); }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom(Type givenType, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = response as ResponseInfo; if (responseInfo == null) { throw new ArgumentOutOfRangeException("response"); } var result = CompatibilityLevel.None; var accept = responseInfo.Request.Headers[Header.Accept]; if ((accept != null) && (accept.Values.Join(SupportedMediaTypes, outer => outer.Value, inner => inner, (outer, inner) => inner).Any())) { result |= CompatibilityLevel.ExactProtocolMatch; } TypeConverter typeConverter; if ((!givenType.IsValueType) && ((!(typeConverter = TypeDescriptor.GetConverter(givenType)).CanConvertTo(typeof(string))) || (typeConverter.GetType() == typeof(TypeConverter)))) { result |= CompatibilityLevel.TypeMatch; } return(result); }
private static string ConvertUsingCustomConverters(IConverterProvider converterProvider, IResponseInfo response, object value) { var converter = converterProvider.FindBestOutputConverter(value.GetType(), response); if (converter == null) { return null; } string result = null; converter.ConvertFrom(value.GetType(), value, response); using (var reader = new StreamReader(response.Body)) { result = reader.ReadToEnd(); } response.Body.Seek(0, SeekOrigin.Begin); return result; }
/// <inheritdoc /> public CompatibilityLevel CanConvertFrom <T>(IResponseInfo response) { return(CanConvertFrom(typeof(T), response)); }
/// <summary> /// 通讯中断,代表发送数据给设备后,在超时时间内没有返回任何数据信息 /// </summary> /// <param name="info"></param> public override void CommunicateInterrupt(IResponseInfo info) { _sendObject = null; OnDeviceRuningLog("通讯中断"); }
public override void CommunicateError(IResponseInfo info) { OnDeviceRuningLog("通讯干扰"); }
public override void CommunicateInterrupt(IResponseInfo info) { OnDeviceRuningLog("通讯中断"); }
private static string ConvertUsingCustomConverters(IConverterProvider converterProvider, IResponseInfo response, object value) { var converter = converterProvider.FindBestOutputConverter(value.GetType(), response); if (converter == null) { return(null); } string result = null; converter.ConvertFrom(value.GetType(), value, response); using (var reader = new StreamReader(response.Body)) { result = reader.ReadToEnd(); } response.Body.Seek(0, SeekOrigin.Begin); return(result); }
/// <summary>Converts an object into a string response body.</summary> /// <param name="converterProvider">Converter provider.</param> /// <param name="value">The value.</param> /// <param name="response">Optional response.</param> /// <returns>String representation of the given <paramref name="value" />.</returns> public static string ConvertFrom(this IConverterProvider converterProvider, object value, IResponseInfo response = null) { if (value == null) { return(null); } bool success; string result = ConvertUsingTypeConverters(value, out success); if (success) { return(result); } if (converterProvider == null) { throw new ArgumentNullException("converterProvider"); } return(ConvertUsingCustomConverters(converterProvider, response, value)); }
/// <inheritdoc /> public void ConvertFrom(Type givenType, object instance, IResponseInfo response) { if (givenType == null) { throw new ArgumentNullException("givenType"); } if (response == null) { throw new ArgumentNullException("response"); } var responseInfo = response as ResponseInfo; if (responseInfo == null) { throw new ArgumentOutOfRangeException("response"); } if (instance == null) { return; } if (!givenType.IsInstanceOfType(instance)) { throw new InvalidOperationException(); } using (var writer = new StreamWriter(responseInfo.Body)) { string separator = String.Empty; foreach (var property in givenType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(property => (property.CanRead) && ((property.CanWrite) || (System.Reflection.TypeExtensions.IsEnumerable(property.PropertyType))))) { var value = property.GetValue(instance); if (value == null) { continue; } var typeConverter = TypeDescriptor.GetConverter(property.PropertyType.FindItemType()); if ((value is IEnumerable) && (value.GetType() != typeof(string))) { if (value is byte[]) { writer.Write("{0}{1}={2}", separator, property.Name, Convert.ToBase64String(responseInfo.Encoding.GetBytes((string)value))); } else { foreach (var item in (IEnumerable)value) { writer.Write("{0}{1}={2}", separator, property.Name, HttpUtility.UrlEncode(typeConverter.ConvertToInvariantString(item))); separator = "&"; } } } else { writer.Write("{0}{1}={2}", separator, property.Name, HttpUtility.UrlEncode(typeConverter.ConvertToInvariantString(value))); } separator = "&"; } } }
/// <inheritdoc /> public void ConvertFrom <T>(T instance, IResponseInfo response) { ConvertFrom(typeof(T), instance, response); }
/// <inheritdoc /> public IConverter FindBestOutputConverter <T>(IResponseInfo response) { return(FindBestOutputConverter(typeof(T), response)); }
/// <inheritdoc /> public Task Process(IResponseInfo responseInfo) { if (responseInfo == null) { throw new ArgumentNullException("responseInfo"); } var response = responseInfo as ResponseInfo; if (response == null) { throw new ArgumentOutOfRangeException("responseInfo"); } string matchingOrigin; if ((String.IsNullOrEmpty(response.Request.Headers.Origin)) || ((matchingOrigin = IsOriginAllowed(response.Request.Headers.Origin)) == null)) { return Task.FromResult(0); } response.Headers.AccessControlAllowOrigin = matchingOrigin; response.Headers.AccessControlExposeHeaders = (!_exposeAnyHeader ? _exposedHeaders : String.Join(", ", ExposedHeaders(response.Request.Headers))); response.Headers.AccessControlAllowHeaders = _allowedHeaders; return Task.FromResult(0); }
/// <summary> /// 通讯正常,把返回的数据返回到此函数接口。在Protocol类中的CheckData函数对数据进行校验。 /// </summary> /// <param name="info"></param> public override void Communicate(IResponseInfo info) { if (_sendObject == null) { OnDeviceRuningLog("没有获得对应的发送请求实例"); return; } byte[] revData = info.Data; IModbusMessage requestMessage = _sendObject.ModbusMessage; ITag tag = _sendObject.Tag; bool deal = false; object val = null; if (tag.Function == Modbus.Modbus.ReadCoils) { #region bool[] responseVals = _modbusTcpMaster.GetReadCoilsResponse(revData, tag.Quantity, requestMessage); if (responseVals.Length >= 1) { val = responseVals[0] == true ? 1 : 0; this.DeviceDynamic.DynamicData.Write(tag.TagName, val); deal = true; } #endregion } else if (tag.Function == Modbus.Modbus.ReadInputs) { #region bool[] responseVals = _modbusTcpMaster.GetReadInputsResponse(revData, tag.Quantity, requestMessage); if (responseVals.Length >= 1) { val = responseVals[0] == true ? 1 : 0; this.DeviceDynamic.DynamicData.Write(tag.TagName, val); deal = true; } #endregion } else if (tag.Function == Modbus.Modbus.ReadHoldingRegisters) { #region ushort[] responseVals = _modbusTcpMaster.GetReadHoldingRegistersResponse(revData, requestMessage); if (responseVals.Length >= 1) { val = responseVals[0]; this.DeviceDynamic.DynamicData.Write(tag.TagName, val); deal = true; } #endregion } else if (tag.Function == Modbus.Modbus.ReadInputRegisters) { #region ushort[] responseVals = _modbusTcpMaster.GetReadInputRegistersResponse(revData, requestMessage); if (responseVals.Length >= 1) { val = responseVals[0]; this.DeviceDynamic.DynamicData.Write(tag.TagName, val); deal = true; } #endregion } if (deal && val != null) { OnDeviceRuningLog("通讯正常,已经处理数据,值:" + (val == null ? "未知" : val.ToString())); this.DeviceDynamic.Save(); } }