public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { //Flash if (FluorineConfiguration.Instance.ServiceMap != null) { string typeName = amfBody.TypeName; string method = amfBody.Method; if (typeName != null && FluorineConfiguration.Instance.ServiceMap.Contains(typeName)) { string serviceLocation = FluorineConfiguration.Instance.ServiceMap.GetServiceLocation(typeName); method = FluorineConfiguration.Instance.ServiceMap.GetMethod(typeName, method); string target = serviceLocation + "." + method; if (log != null && log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Service_Mapping, amfBody.Target, target)); } amfBody.Target = target; } } } } }
public void SpecialConstructorInitializesProperties() { ASString content = new ASString("abc"); AMFBody body = new AMFBody("request", "response", content); Assert.AreEqual("request", body.RequestTarget); Assert.AreEqual("response", body.ResponseTarget); Assert.AreSame(content, body.Content); }
public ResponseBody GetResponse(AMFBody requestBody) { for(var i = 0; i < _bodies.Count; i++) { var responseBody = _bodies[i] as ResponseBody; if( responseBody.RequestBody == requestBody ) return responseBody; } return null; }
public ResponseBody(AMFBody requestBody, object content) { _requestBody = requestBody; _target = requestBody.Response + AMFBody.OnResult; _content = content; _response = "null"; }
public override void Invoke(AMFContext context) { AMFMessage amfMessage = context.AMFMessage; AMFHeader amfHeader = amfMessage.GetHeader(AMFHeader.ServiceBrowserHeader); if (amfHeader != null) { AMFBody amfBody = amfMessage.GetBodyAt(0); amfBody.IsDescribeService = true; } }
public override void Invoke(AMFContext context) { AMFMessage amfMessage = context.AMFMessage; AMFHeader amfHeader = amfMessage.GetHeader(AMFHeader.DebugHeader); if (amfHeader != null) { //The value of the header ASObject asObject = amfHeader.Content as ASObject; //["error"]: {true} //["trace"]: {true} //["httpheaders"]: {false} //["coldfusion"]: {true} //["amf"]: {false} //["m_debug"]: {true} //["amfheaders"]: {false} //["recordset"]: {true} AMFBody amfBody = amfMessage.GetBodyAt(amfMessage.BodyCount - 1); //last body ResponseBody amfBodyOut = new ResponseBody(); amfBodyOut.Target = amfBody.Response + AMFBody.OnDebugEvents; amfBodyOut.Response = null; amfBodyOut.IsDebug = true; ArrayList headerResults = new ArrayList(); ArrayList result = new ArrayList(); headerResults.Add(result); if ((bool)asObject["httpheaders"] == true) { //If the client wants http headers result.Add(new HttpHeader( )); } if ((bool)asObject["amfheaders"] == true) { result.Add(new AMFRequestHeaders(amfMessage)); } ArrayList traceStack = NetDebug.GetTraceStack(); if ((bool)asObject["trace"] == true && traceStack != null && traceStack.Count > 0) { ArrayList tmp = new ArrayList(traceStack); result.Add(new TraceHeader(tmp)); NetDebug.Clear(); } //http://osflash.org/amf/envelopes/remoting/debuginfo amfBodyOut.Content = headerResults; context.MessageOutput.AddBody(amfBodyOut); } NetDebug.Clear(); }
public ResponseBody GetResponse(AMFBody requestBody) { for (var i = 0; i < _bodies.Count; i++) { var responseBody = _bodies[i] as ResponseBody; if (responseBody.RequestBody == requestBody) { return(responseBody); } } return(null); }
private void BeginResponseFlashCall(IAsyncResult ar) { try { RequestData asyncState = ar.AsyncState as RequestData; if (asyncState != null) { HttpWebResponse response = (HttpWebResponse)asyncState.Request.EndGetResponse(ar); if (response != null) { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { AMFMessage message = new AMFDeserializer(responseStream).ReadAMFMessage(); AMFBody bodyAt = message.GetBodyAt(0); for (int i = 0; i < message.HeaderCount; i++) { AMFHeader headerAt = message.GetHeaderAt(i); if (headerAt.Name == "RequestPersistentHeader") { this._netConnection.AddHeader(headerAt.Name, headerAt.MustUnderstand, headerAt.Content); } } PendingCall call = asyncState.Call; call.Result = bodyAt.Content; if (bodyAt.Target.EndsWith("/onStatus")) { call.Status = 0x13; } else { call.Status = 2; } asyncState.Callback.ResultReceived(call); } else { this._netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } } else { this._netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
/// <summary> /// Сериализует объект в буффер AMF. /// </summary> /// <param name="sourceObject">Исходный объект.</param> /// <param name="version">Версия AMF.</param> /// <returns></returns> public static byte[] SerializeToAmf(this object sourceObject, ushort version) { using (MemoryStream memoryStream = new MemoryStream()) // Открываем поток для записи данных в буфер. using (AMFSerializer amfSerializer = new AMFSerializer(memoryStream)) // Инициализируем сериализатор для AMF. { AMFMessage amfMessage = new AMFMessage(version); // Создаём сообщение для передачи серверу с заданным номером версии AMF. AMFBody amfBody = new AMFBody(AMFBody.OnResult, null, GenerateType(sourceObject)); // Создаём тело для сообщения AMF. amfMessage.AddBody(amfBody); // Добавляем body для сообщения AMF. amfSerializer.WriteMessage(amfMessage); // Сериализуем сообщение. return(memoryStream.ToArray()); // Преобразовывает поток памяти в буфер и возвращает. } }
public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments) { if (this._netConnection.ObjectEncoding == ObjectEncoding.AMF0) { throw new NotSupportedException("AMF0 not supported for Flex RPC"); } try { TypeHelper._Init(); Uri requestUri = new Uri(this._gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri); request.ContentType = "application/x-amf"; request.Method = "POST"; request.CookieContainer = this._netConnection.CookieContainer; AMFMessage amfMessage = new AMFMessage((ushort)this._netConnection.ObjectEncoding); RemotingMessage message2 = new RemotingMessage { clientId = Guid.NewGuid().ToString("D"), destination = destination, messageId = Guid.NewGuid().ToString("D"), timestamp = 0L, timeToLive = 0L }; message2.SetHeader("DSEndpoint", endpoint); if (this._netConnection.ClientId == null) { message2.SetHeader("DSId", "nil"); } else { message2.SetHeader("DSId", this._netConnection.ClientId); } message2.source = source; message2.operation = operation; message2.body = arguments; foreach (KeyValuePair <string, AMFHeader> pair in this._netConnection.Headers) { amfMessage.AddHeader(pair.Value); } AMFBody body = new AMFBody(null, null, new object[] { message2 }); amfMessage.AddBody(body); PendingCall call = new PendingCall(source, operation, arguments); RequestData state = new RequestData(request, amfMessage, call, callback); request.BeginGetRequestStream(new AsyncCallback(this.BeginRequestFlexCall), state); } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
private AMFMessage ReadMessage(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { throw new JsonReaderException("AMFMessage must be a JSON Object"); } AMFMessage message = new AMFMessage(); for (reader.Read(); reader.TokenType != JsonToken.EndObject; reader.Read()) { if (reader.TokenType != JsonToken.PropertyName) { throw new JsonReaderException("JSON format error, JSON Object must have property"); } string propertyName = (string)reader.Value; switch (propertyName) { case "Version": reader.Read(); if (reader.TokenType != JsonToken.Integer) { throw new JsonReaderException("AMFMessage 'Version' must be JSON Number"); } message = new AMFMessage(Convert.ToUInt16(reader.Value)); break; case "Bodies": reader.Read(); if (reader.TokenType != JsonToken.StartArray) { throw new JsonReaderException("AMFMessage 'Bodies' must be JSON Array"); } for (reader.Read(); reader.TokenType != JsonToken.EndArray; reader.Read()) { AMFBody body = serializer.Deserialize <AMFBody>(reader); message.AddBody(body); } break; default: throw new NotSupportedException("AMFMessage dont support property " + propertyName + ", please report this"); break; } } return(message); }
public void Call(string endpoint, string destination, string source, string operation, IPendingServiceCallback callback, params object[] arguments) { if (_netConnection.ObjectEncoding == ObjectEncoding.AMF0) { throw new NotSupportedException("AMF0 not supported for Flex RPC"); } try { TypeHelper._Init(); Uri uri = new Uri(_gatewayUrl); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); request.ContentType = ContentType.AMF; request.Method = "POST"; #if !(SILVERLIGHT) request.CookieContainer = _netConnection.CookieContainer; #endif AMFMessage amfMessage = new AMFMessage((ushort)_netConnection.ObjectEncoding); RemotingMessage remotingMessage = new RemotingMessage(); remotingMessage.clientId = Guid.NewGuid().ToString("D"); remotingMessage.destination = destination; remotingMessage.messageId = Guid.NewGuid().ToString("D"); remotingMessage.timestamp = 0; remotingMessage.timeToLive = 0; remotingMessage.SetHeader(MessageBase.EndpointHeader, endpoint); remotingMessage.SetHeader(MessageBase.FlexClientIdHeader, _netConnection.ClientId ?? "nil"); //Service stuff remotingMessage.source = source; remotingMessage.operation = operation; remotingMessage.body = arguments; foreach (KeyValuePair <string, AMFHeader> entry in _netConnection.Headers) { amfMessage.AddHeader(entry.Value); } AMFBody amfBody = new AMFBody(null, null, new object[] { remotingMessage }); amfMessage.AddBody(amfBody); PendingCall call = new PendingCall(source, operation, arguments); AmfRequestData amfRequestData = new AmfRequestData(request, amfMessage, call, callback, null); request.BeginGetRequestStream(BeginRequestFlexCall, amfRequestData); } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
public void CanGetAndSetProperties() { ASString content = new ASString("abc"); AMFBody body = new AMFBody(); Assert.IsNull(body.Content); body.Content = content; Assert.AreSame(content, body.Content); Assert.IsNull(body.RequestTarget); body.RequestTarget = "abc"; Assert.AreEqual("abc", body.RequestTarget); Assert.IsNull(body.ResponseTarget); body.ResponseTarget = "def"; Assert.AreEqual("def", body.ResponseTarget); }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.Count > 0) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); //Check if response exists. ResponseBody responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { //AuthenticationFilter may insert response. continue; } if (!amfBody.IsEmptyTarget) { string source = amfBody.Target; IList arguments = amfBody.GetParameterList(); string key = FluorineFx.Configuration.CacheMap.GenerateCacheKey(source, arguments); //Flash message if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key)) { object cachedContent = FluorineConfiguration.Instance.CacheMap.Get(key); if (log != null && log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Cache_HitKey, amfBody.Target, key)); } CachedBody cachedBody = new CachedBody(amfBody, cachedContent); messageOutput.AddBody(cachedBody); } } } } }
/// <summary> /// 用户认证 /// </summary> /// <returns></returns> private byte[] AuthenticateUser(string userID, string psd, string responseNo) { RemotingMessage rtMsg = new RemotingMessage(); rtMsg.source = null; rtMsg.operation = "authenticateUser"; rtMsg.clientId = Guid.NewGuid().ToString().ToUpper(); rtMsg.messageId = Guid.NewGuid().ToString().ToUpper(); rtMsg.destination = "userRO"; rtMsg.timestamp = 0; rtMsg.timeToLive = 0; rtMsg.headers.Add(RemotingMessage.FlexClientIdHeader, Guid.NewGuid().ToString().ToUpper()); rtMsg.headers.Add(RemotingMessage.EndpointHeader, "my-amf"); List <object> bodys = new List <object>(); bodys.Add(userID); bodys.Add(psd); rtMsg.body = bodys.ToArray(); AMFMessage _amf3 = new AMFMessage(3);// 创建 AMF List <RemotingMessage> lstR = new List <RemotingMessage>(); lstR.Add(rtMsg); AMFBody _amfbody = new AMFBody("null", "/" + responseNo, lstR.ToArray()); _amf3.AddBody(_amfbody); MemoryStream _Memory = new MemoryStream(); //内存流 AMFSerializer _Serializer = new AMFSerializer(_Memory); //序列化 _Serializer.WriteMessage(_amf3); //将消息写入 return(_Memory.ToArray()); }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody bodyAt = context.AMFMessage.GetBodyAt(i); if (!bodyAt.IsEmptyTarget && (FluorineConfiguration.Instance.ServiceMap != null)) { string typeName = bodyAt.TypeName; string method = bodyAt.Method; if ((typeName != null) && FluorineConfiguration.Instance.ServiceMap.Contains(typeName)) { string serviceLocation = FluorineConfiguration.Instance.ServiceMap.GetServiceLocation(typeName); method = FluorineConfiguration.Instance.ServiceMap.GetMethod(typeName, method); string str4 = serviceLocation + "." + method; if ((log != null) && log.get_IsDebugEnabled()) { log.Debug(__Res.GetString("Service_Mapping", new object[] { bodyAt.Target, str4 })); } bodyAt.Target = str4; } } } }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { //Flash if (AMFConfiguration.Instance.ServiceMap != null) { string typeName = amfBody.TypeName; string method = amfBody.Method; if (typeName != null && AMFConfiguration.Instance.ServiceMap.Contains(typeName)) { string serviceLocation = AMFConfiguration.Instance.ServiceMap.GetServiceLocation(typeName); method = AMFConfiguration.Instance.ServiceMap.GetMethod(typeName, method); string target = serviceLocation + "." + method; amfBody.Target = target; } } } } }
public override void Invoke(AMFContext context) { AMFMessage aMFMessage = context.AMFMessage; AMFHeader header = aMFMessage.GetHeader("amf_server_debug"); if (header != null) { ASObject content = header.Content as ASObject; AMFBody bodyAt = aMFMessage.GetBodyAt(aMFMessage.BodyCount - 1); ResponseBody body = new ResponseBody { Target = bodyAt.Response + "/onDebugEvents", Response = null, IsDebug = true }; ArrayList list = new ArrayList(); ArrayList list2 = new ArrayList(); list.Add(list2); if ((bool)content["httpheaders"]) { list2.Add(new HttpHeader()); } if ((bool)content["amfheaders"]) { list2.Add(new AMFRequestHeaders(aMFMessage)); } ArrayList traceStack = NetDebug.GetTraceStack(); if ((((bool)content["trace"]) && (traceStack != null)) && (traceStack.Count > 0)) { ArrayList list4 = new ArrayList(traceStack); list2.Add(new TraceHeader(list4)); NetDebug.Clear(); } body.Content = list; context.MessageOutput.AddBody(body); } NetDebug.Clear(); }
public void Fail(AMFBody amfBody, Exception exception) { throw new NotImplementedException(); }
public bool ContainsResponse(AMFBody requestBody) { return(GetResponse(requestBody) != null); }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { Type typeForWebService; Exception exception; ErrorResponseBody body2; AMFBody bodyAt = context.AMFMessage.GetBodyAt(i); if (!bodyAt.IsEmptyTarget) { if (bodyAt.IsWebService) { try { typeForWebService = this.GetTypeForWebService(bodyAt.TypeName); if (typeForWebService != null) { bodyAt.Target = typeForWebService.FullName + "." + bodyAt.Method; } else { exception = new TypeInitializationException(bodyAt.TypeName, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception1) { exception = exception1; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } } else { object content = bodyAt.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if ((message != null) && (message is RemotingMessage)) { RemotingMessage message2 = message as RemotingMessage; string source = message2.source; if ((source != null) && source.ToLower().EndsWith(".asmx")) { try { typeForWebService = this.GetTypeForWebService(source); if (typeForWebService != null) { message2.source = typeForWebService.FullName; } else { exception = new TypeInitializationException(source, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception2) { exception = exception2; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } } } } }
public bool ContainsResponse(AMFBody requestBody) { return GetResponse(requestBody) != null; }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); //Check for Flex2 messages if (amfBody.IsEmptyTarget) { object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null) { Client client = null; HttpSession session = null; if (FluorineContext.Current.Client == null) { IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry; string clientId = message.GetFlexClientId(); if (!clientRegistry.HasClient(clientId)) { lock (clientRegistry.SyncRoot) { if (!clientRegistry.HasClient(clientId)) { client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client; } } } if (client == null) { client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client; } FluorineContext.Current.SetClient(client); } session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current); FluorineContext.Current.SetSession(session); //Context initialized, notify listeners. if (session != null && session.IsNew) { session.NotifyCreated(); } if (client != null) { if (session != null) { client.RegisterSession(session); } if (client.IsNew) { client.Renew(_endpoint.ClientLeaseTime); client.NotifyCreated(); } } /* * RemotingConnection remotingConnection = null; * foreach (IConnection connection in client.Connections) * { * if (connection is RemotingConnection) * { * remotingConnection = connection as RemotingConnection; * break; * } * } * if (remotingConnection == null) * { * remotingConnection = new RemotingConnection(_endpoint, null, client.Id, null); * remotingConnection.Initialize(client, session); * } * FluorineContext.Current.SetConnection(remotingConnection); */ } } else { //Flash remoting AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.AMFDSIdHeader); string amfDSId = null; if (amfHeader == null) { amfDSId = Guid.NewGuid().ToString("D"); ASObject asoObjectDSId = new ASObject(); asoObjectDSId["name"] = AMFHeader.AMFDSIdHeader; asoObjectDSId["mustUnderstand"] = false; asoObjectDSId["data"] = amfDSId;//set AMFHeader headerDSId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectDSId); context.MessageOutput.AddHeader(headerDSId); } else { amfDSId = amfHeader.Content as string; } Client client = null; HttpSession session = null; if (FluorineContext.Current.Client == null) { IClientRegistry clientRegistry = _endpoint.GetMessageBroker().ClientRegistry; string clientId = amfDSId; if (!clientRegistry.HasClient(clientId)) { lock (clientRegistry.SyncRoot) { if (!clientRegistry.HasClient(clientId)) { client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client; } } } if (client == null) { client = _endpoint.GetMessageBroker().ClientRegistry.GetClient(clientId) as Client; } } FluorineContext.Current.SetClient(client); session = _endpoint.GetMessageBroker().SessionManager.GetHttpSession(HttpContext.Current); FluorineContext.Current.SetSession(session); //Context initialized, notify listeners. if (session != null && session.IsNew) { session.NotifyCreated(); } if (client != null) { if (session != null) { client.RegisterSession(session); } if (client.IsNew) { client.Renew(_endpoint.ClientLeaseTime); client.NotifyCreated(); } } } } }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { continue; } object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; //Check for Flex2 messages and handle if (message != null) { if (Context.AMFContext.Current.Client == null) { Context.AMFContext.Current.SetCurrentClient(_endpoint.GetMessageBroker().ClientRegistry.GetClient(message)); } if (message.clientId == null) { message.clientId = Guid.NewGuid().ToString("D"); } //Check if response exists. ResponseBody responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { if (context.AMFMessage.BodyCount > 1) { CommandMessage commandMessage = message as CommandMessage; //Suppress poll wait if there are more messages to process if (commandMessage != null && commandMessage.operation == CommandMessage.PollOperation) { commandMessage.SetHeader(CommandMessage.AMFSuppressPollWaitHeader, null); } } IMessage resultMessage = _endpoint.ServiceMessage(message); if (resultMessage is ErrorMessage) { ErrorMessage errorMessage = resultMessage as ErrorMessage; responseBody = new ErrorResponseBody(amfBody, message, resultMessage as ErrorMessage); if (errorMessage.faultCode == ErrorMessage.ClientAuthenticationError) { messageOutput.AddBody(responseBody); for (int j = i + 1; j < context.AMFMessage.BodyCount; j++) { amfBody = context.AMFMessage.GetBodyAt(j); if (!amfBody.IsEmptyTarget) { continue; } content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } message = content as IMessage; //Check for Flex2 messages and handle if (message != null) { responseBody = new ErrorResponseBody(amfBody, message, new SecurityException(errorMessage.faultString)); messageOutput.AddBody(responseBody); } } //Leave further processing return; } } else { responseBody = new ResponseBody(amfBody, resultMessage); } } catch (Exception exception) { responseBody = new ErrorResponseBody(amfBody, message, exception); } messageOutput.AddBody(responseBody); } } }
private void BeginResponseFlexCall(IAsyncResult ar) { try { AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData; if (amfRequestData != null) { HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar); if (response != null) { //Get response and deserialize Stream responseStream = response.GetResponseStream(); if (responseStream != null) { AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream); AMFMessage responseMessage = amfDeserializer.ReadAMFMessage(); AMFBody responseBody = responseMessage.GetBodyAt(0); for (int i = 0; i < responseMessage.HeaderCount; i++) { AMFHeader header = responseMessage.GetHeaderAt(i); if (header.Name == AMFHeader.RequestPersistentHeader) _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content); } object message = responseBody.Content; if (message is ErrorMessage) { /* ASObject status = new ASObject(); status["level"] = "error"; status["code"] = "NetConnection.Call.Failed"; status["description"] = (result as ErrorMessage).faultString; status["details"] = result; _netConnection.RaiseNetStatus(status); */ if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = message; call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction; if (statusFunction != null) statusFunction(new Fault(message as ErrorMessage)); } } else if (message is AcknowledgeMessage) { AcknowledgeMessage ack = message as AcknowledgeMessage; if (_netConnection.ClientId == null && ack.HeaderExists(MessageBase.FlexClientIdHeader)) _netConnection.SetClientId(ack.GetHeader(MessageBase.FlexClientIdHeader) as string); if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = ack.body; call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate; if (resultFunction != null) { ParameterInfo[] arguments = resultFunction.Method.GetParameters(); object result = TypeHelper.ChangeType(ack.body, arguments[0].ParameterType); resultFunction.DynamicInvoke(result); } } } } else _netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } else _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
public override Task Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ResponseBody responseBody = null; //Check for Flex2 messages and skip if (amfBody.IsEmptyTarget) { continue; } //Check if response exists. responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { MessageBroker messageBroker = _endpoint.GetMessageBroker(); RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService; if (remotingService == null) { string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId); responseBody = new ErrorResponseBody(amfBody, new AMFException(serviceNotFound)); messageOutput.AddBody(responseBody); continue; } Destination destination = null; if (destination == null) { destination = remotingService.GetDestinationWithSource(amfBody.TypeName); } if (destination == null) { destination = remotingService.DefaultDestination; } //At this moment we got a destination with the exact source or we have a default destination with the "*" source. if (destination == null) { string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new AMFException(destinationNotFound)); messageOutput.AddBody(responseBody); continue; } //Cache check string source = amfBody.TypeName + "." + amfBody.Method; IList parameterList = amfBody.GetParameterList(); FactoryInstance factoryInstance = destination.GetFactoryInstance(); factoryInstance.Source = amfBody.TypeName; object instance = factoryInstance.Lookup(); if (instance != null) { bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType()); if (!isAccessible) { string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new AMFException(msg)); messageOutput.AddBody(responseBody); continue; } MethodInfo mi = null; if (!amfBody.IsRecordsetDelivery) { mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, amfBody.GetParameterList()); } else { //will receive recordsetid only (ignore) mi = instance.GetType().GetMethod(amfBody.Method); } if (mi != null) { #region Invocation handling ParameterInfo[] parameterInfos = mi.GetParameters(); //Try to handle missing/optional parameters. object[] args = new object[parameterInfos.Length]; if (!amfBody.IsRecordsetDelivery) { if (args.Length != parameterList.Count) { string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length); responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg)); messageOutput.AddBody(responseBody); continue; } parameterList.CopyTo(args, 0); } else { if (amfBody.Target.EndsWith(".release")) { responseBody = new ResponseBody(amfBody, null); messageOutput.AddBody(responseBody); continue; } string recordsetId = parameterList[0] as string; string recordetDeliveryParameters = amfBody.GetRecordsetArgs(); byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters); recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer); if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty) { string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' }); for (int j = 0; j < stringParameters.Length; j++) { if (stringParameters[j] == string.Empty) { args[j] = null; } else { args[j] = stringParameters[j]; } } //TypeHelper.NarrowValues(argsStore, parameterInfos); } } TypeHelper.NarrowValues(args, parameterInfos); try { InvocationHandler invocationHandler = new InvocationHandler(mi); object result = invocationHandler.Invoke(instance, args); responseBody = new ResponseBody(amfBody, result); } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); } catch (Exception exception) { if (exception is TargetInvocationException && exception.InnerException != null) { responseBody = new ErrorResponseBody(amfBody, exception.InnerException); } else { responseBody = new ErrorResponseBody(amfBody, exception); } } #endregion Invocation handling } else { responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method)); } } else { responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null)); } } catch (Exception exception) { responseBody = new ErrorResponseBody(amfBody, exception); } messageOutput.AddBody(responseBody); } return(Task.FromResult <object>(null)); }
private void BeginResponseFlashCall(IAsyncResult ar) { try { AmfRequestData amfRequestData = ar.AsyncState as AmfRequestData; if (amfRequestData != null) { HttpWebResponse response = (HttpWebResponse)amfRequestData.Request.EndGetResponse(ar); if (response != null) { //Get response and deserialize Stream responseStream = response.GetResponseStream(); if (responseStream != null) { AMFDeserializer amfDeserializer = new AMFDeserializer(responseStream); AMFMessage responseMessage = amfDeserializer.ReadAMFMessage(); AMFBody responseBody = responseMessage.GetBodyAt(0); for (int i = 0; i < responseMessage.HeaderCount; i++) { AMFHeader header = responseMessage.GetHeaderAt(i); if (header.Name == AMFHeader.RequestPersistentHeader) _netConnection.AddHeader(header.Name, header.MustUnderstand, header.Content); } if (amfRequestData.Call != null) { PendingCall call = amfRequestData.Call; call.Result = responseBody.Content; call.Status = responseBody.Target.EndsWith(AMFBody.OnStatus) ? Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION : Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT; amfRequestData.Callback.ResultReceived(call); } if (amfRequestData.Responder != null) { if (responseBody.Target.EndsWith(AMFBody.OnStatus)) { StatusFunction statusFunction = amfRequestData.Responder.GetType().GetProperty("Status").GetValue(amfRequestData.Responder, null) as StatusFunction; if (statusFunction != null) statusFunction(new Fault(responseBody.Content)); } else { Delegate resultFunction = amfRequestData.Responder.GetType().GetProperty("Result").GetValue(amfRequestData.Responder, null) as Delegate; if (resultFunction != null) { ParameterInfo[] arguments = resultFunction.Method.GetParameters(); object result = TypeHelper.ChangeType(responseBody.Content, arguments[0].ParameterType); resultFunction.DynamicInvoke(result); } } } } else _netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } else _netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } catch (Exception ex) { _netConnection.RaiseNetStatus(ex); } }
public override void Invoke(AMFContext context) { MessageBroker messageBroker = _endpoint.GetMessageBroker(); try { AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsHeader); if (amfHeader != null && amfHeader.Content != null) { string userId = ((ASObject)amfHeader.Content)["userid"] as string; string password = ((ASObject)amfHeader.Content)["password"] as string; //Clear credentials header, further requests will not send the credentials ASObject asoObject = new ASObject(); asoObject["name"] = AMFHeader.CredentialsHeader; asoObject["mustUnderstand"] = false; asoObject["data"] = null;//clear AMFHeader header = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObject); context.MessageOutput.AddHeader(header); IPrincipal principal = _endpoint.GetMessageBroker().LoginManager.Login(userId, amfHeader.Content as IDictionary); string key = EncryptCredentials(_endpoint, principal, userId, password); ASObject asoObjectCredentialsId = new ASObject(); asoObjectCredentialsId["name"] = AMFHeader.CredentialsIdHeader; asoObjectCredentialsId["mustUnderstand"] = false; asoObjectCredentialsId["data"] = key;//set AMFHeader headerCredentialsId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectCredentialsId); context.MessageOutput.AddHeader(headerCredentialsId); } else { amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsIdHeader); if (amfHeader != null) { string key = amfHeader.Content as string; if (key != null) { _endpoint.GetMessageBroker().LoginManager.RestorePrincipal(key); } } else { _endpoint.GetMessageBroker().LoginManager.RestorePrincipal(); } } } catch (UnauthorizedAccessException exception) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(exception.Message, exception); } for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ResponseBody responseBody = null; //Check for Flex2 messages and skip if (amfBody.IsEmptyTarget) { continue; } if (amfBody.IsDebug) { continue; } if (amfBody.IsDescribeService) { responseBody = new ResponseBody(); responseBody.IgnoreResults = amfBody.IgnoreResults; responseBody.Target = amfBody.Response + AMFBody.OnResult; responseBody.Response = null; DescribeService describeService = new DescribeService(amfBody); responseBody.Content = describeService.GetDescription(); messageOutput.AddBody(responseBody); continue; } //Check if response exists. responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { MessageBroker messageBroker = _endpoint.GetMessageBroker(); RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService; if (remotingService == null) { string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId); responseBody = new ErrorResponseBody(amfBody, new FluorineException(serviceNotFound)); messageOutput.AddBody(responseBody); if (log.IsErrorEnabled) { log.Error(serviceNotFound); } continue; } Destination destination = null; if (destination == null) { destination = remotingService.GetDestinationWithSource(amfBody.TypeName); } if (destination == null) { destination = remotingService.DefaultDestination; } //At this moment we got a destination with the exact source or we have a default destination with the "*" source. if (destination == null) { string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new FluorineException(destinationNotFound)); messageOutput.AddBody(responseBody); if (log.IsErrorEnabled) { log.Error(destinationNotFound); } continue; } try { remotingService.CheckSecurity(destination); } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); if (log.IsDebugEnabled) { log.Debug(exception.Message); } continue; } //Cache check string source = amfBody.TypeName + "." + amfBody.Method; IList parameterList = amfBody.GetParameterList(); string key = FluorineFx.Configuration.CacheMap.GenerateCacheKey(source, parameterList); if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key)) { object result = FluorineFx.Configuration.FluorineConfiguration.Instance.CacheMap.Get(key); if (result != null) { if (log != null && log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Cache_HitKey, source, key)); } responseBody = new ResponseBody(amfBody, result); messageOutput.AddBody(responseBody); continue; } } object instance; FactoryInstance factoryInstance = destination.GetFactoryInstance(); lock (factoryInstance) { factoryInstance.Source = amfBody.TypeName; if (FluorineContext.Current.ActivationMode != null)//query string can override the activation mode { factoryInstance.Scope = FluorineContext.Current.ActivationMode; } instance = factoryInstance.Lookup(); } if (instance != null) { try { bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType()); if (!isAccessible) { string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName); if (log.IsErrorEnabled) { log.Error(msg); } responseBody = new ErrorResponseBody(amfBody, new FluorineException(msg)); messageOutput.AddBody(responseBody); continue; } MethodInfo mi = null; if (!amfBody.IsRecordsetDelivery) { mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, parameterList); } else { //will receive recordsetid only (ignore) mi = instance.GetType().GetMethod(amfBody.Method); } if (mi != null) { object[] roleAttributes = mi.GetCustomAttributes(typeof(RoleAttribute), true); if (roleAttributes != null && roleAttributes.Length == 1) { RoleAttribute roleAttribute = roleAttributes[0] as RoleAttribute; string[] roles = roleAttribute.Roles.Split(','); bool authorized = messageBroker.LoginManager.DoAuthorization(roles); if (!authorized) { throw new UnauthorizedAccessException(__Res.GetString(__Res.Security_AccessNotAllowed)); } } #region Invocation handling PageSizeAttribute pageSizeAttribute = null; MethodInfo miCounter = null; object[] pageSizeAttributes = mi.GetCustomAttributes(typeof(PageSizeAttribute), true); if (pageSizeAttributes != null && pageSizeAttributes.Length == 1) { pageSizeAttribute = pageSizeAttributes[0] as PageSizeAttribute; miCounter = instance.GetType().GetMethod(amfBody.Method + "Count"); if (miCounter != null && miCounter.ReturnType != typeof(System.Int32)) { miCounter = null; //check signature } } ParameterInfo[] parameterInfos = mi.GetParameters(); //Try to handle missing/optional parameters. object[] args = new object[parameterInfos.Length]; if (!amfBody.IsRecordsetDelivery) { if (args.Length != parameterList.Count) { string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length); if (log != null && log.IsErrorEnabled) { log.Error(msg); } responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg)); messageOutput.AddBody(responseBody); continue; } parameterList.CopyTo(args, 0); if (pageSizeAttribute != null) { PagingContext pagingContext = new PagingContext(pageSizeAttribute.Offset, pageSizeAttribute.Limit); PagingContext.SetPagingContext(pagingContext); } } else { if (amfBody.Target.EndsWith(".release")) { responseBody = new ResponseBody(amfBody, null); messageOutput.AddBody(responseBody); continue; } string recordsetId = parameterList[0] as string; string recordetDeliveryParameters = amfBody.GetRecordsetArgs(); byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters); recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer); if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty) { string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' }); for (int j = 0; j < stringParameters.Length; j++) { if (stringParameters[j] == string.Empty) { args[j] = null; } else { args[j] = stringParameters[j]; } } //TypeHelper.NarrowValues(argsStore, parameterInfos); } PagingContext pagingContext = new PagingContext(System.Convert.ToInt32(parameterList[1]), System.Convert.ToInt32(parameterList[2])); PagingContext.SetPagingContext(pagingContext); } TypeHelper.NarrowValues(args, parameterInfos); try { InvocationHandler invocationHandler = new InvocationHandler(mi); object result = invocationHandler.Invoke(instance, args); if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.ContainsCacheDescriptor(source)) { //The result should be cached CacheableObject cacheableObject = new CacheableObject(source, key, result); FluorineConfiguration.Instance.CacheMap.Add(cacheableObject.Source, cacheableObject.CacheKey, cacheableObject); result = cacheableObject; } responseBody = new ResponseBody(amfBody, result); if (pageSizeAttribute != null) { int totalCount = 0; string recordsetId = null; IList list = amfBody.GetParameterList(); string recordetDeliveryParameters = null; if (!amfBody.IsRecordsetDelivery) { //fist call paging object[] argsStore = new object[list.Count]; list.CopyTo(argsStore, 0); recordsetId = System.Guid.NewGuid().ToString(); if (miCounter != null) { //object[] counterArgs = new object[0]; totalCount = (int)miCounter.Invoke(instance, args); } string[] stringParameters = new string[argsStore.Length]; for (int j = 0; j < argsStore.Length; j++) { if (argsStore[j] != null) { stringParameters[j] = argsStore[j].ToString(); } else { stringParameters[j] = string.Empty; } } recordetDeliveryParameters = string.Join(",", stringParameters); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(recordetDeliveryParameters); recordetDeliveryParameters = System.Convert.ToBase64String(buffer); } else { recordsetId = amfBody.GetParameterList()[0] as string; } if (result is DataTable) { DataTable dataTable = result as DataTable; dataTable.ExtendedProperties["TotalCount"] = totalCount; dataTable.ExtendedProperties["Service"] = recordetDeliveryParameters + "/" + amfBody.Target; dataTable.ExtendedProperties["RecordsetId"] = recordsetId; if (amfBody.IsRecordsetDelivery) { dataTable.ExtendedProperties["Cursor"] = Convert.ToInt32(list[list.Count - 2]); dataTable.ExtendedProperties["DynamicPage"] = true; } } } } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); if (log.IsDebugEnabled) { log.Debug(exception.Message); } } catch (Exception exception) { if (exception is TargetInvocationException && exception.InnerException != null) { responseBody = new ErrorResponseBody(amfBody, exception.InnerException); } else { responseBody = new ErrorResponseBody(amfBody, exception); } if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.Message)); } } #endregion Invocation handling } else { responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method)); } } finally { factoryInstance.OnOperationComplete(instance); } } else { responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null)); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(exception.Message + String.Format(" (Type: {0}, Method: {1})", amfBody.TypeName, amfBody.Method), exception); } responseBody = new ErrorResponseBody(amfBody, exception); } messageOutput.AddBody(responseBody); } }
private void BeginResponseFlexCall(IAsyncResult ar) { try { RequestData asyncState = ar.AsyncState as RequestData; if (asyncState != null) { HttpWebResponse response = (HttpWebResponse)asyncState.Request.EndGetResponse(ar); if (response != null) { Stream responseStream = response.GetResponseStream(); if (responseStream != null) { PendingCall call; AMFMessage message = new AMFDeserializer(responseStream).ReadAMFMessage(); AMFBody bodyAt = message.GetBodyAt(0); for (int i = 0; i < message.HeaderCount; i++) { AMFHeader headerAt = message.GetHeaderAt(i); if (headerAt.Name == "RequestPersistentHeader") { this._netConnection.AddHeader(headerAt.Name, headerAt.MustUnderstand, headerAt.Content); } } object content = bodyAt.Content; if (content is ErrorMessage) { call = asyncState.Call; call.Result = content; call.Status = 0x13; asyncState.Callback.ResultReceived(call); } if (content is AcknowledgeMessage) { AcknowledgeMessage message2 = content as AcknowledgeMessage; if ((this._netConnection.ClientId == null) && message2.HeaderExists("DSId")) { this._netConnection.SetClientId(message2.GetHeader("DSId") as string); } call = asyncState.Call; call.Result = message2.body; call.Status = 2; asyncState.Callback.ResultReceived(call); } } else { this._netConnection.RaiseNetStatus("Could not aquire ResponseStream"); } } else { this._netConnection.RaiseNetStatus("Could not aquire HttpWebResponse"); } } } catch (Exception exception) { this._netConnection.RaiseNetStatus(exception); } }
object ProcessMessage(AMFMessage amfMessage) { // Apply AMF-based operation selector /* * Dictionary<string, string> operationNameDictionary = new Dictionary<string, string>(); * foreach (OperationDescription operation in _endpoint.Contract.Operations) * { * try * { * operationNameDictionary.Add(operation.Name.ToLower(), operation.Name); * } * catch (ArgumentException) * { * throw new Exception(String.Format("The specified contract cannot be used with case insensitive URI dispatch because there is more than one operation named {0}", operation.Name)); * } * } */ //SessionMode, CallbackContract, ProtectionLevel AMFMessage output = new AMFMessage(amfMessage.Version); for (int i = 0; i < amfMessage.BodyCount; i++) { AMFBody amfBody = amfMessage.GetBodyAt(i); object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null) { //WCF should not assign client id for Flex... if (message.clientId == null) { message.clientId = Guid.NewGuid().ToString("D"); } //IMessage resultMessage = _endpoint.ServiceMessage(message); IMessage responseMessage = null; CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation) { responseMessage = new AcknowledgeMessage(); responseMessage.body = true; } else { RemotingMessage remotingMessage = message as RemotingMessage; string operation = remotingMessage.operation; //TODO: you could use an alias for a contract to expose a different name to the clients in the metadata using the Name property of the ServiceContract attribute string source = remotingMessage.source; Type serviceType = TypeHelper.Locate(source); Type contractInterface = serviceType.GetInterface(_endpoint.Contract.ContractType.FullName); //WCF also lets you apply the ServiceContract attribute directly on the service class. Avoid using it. //ServiceContractAttribute serviceContractAttribute = ReflectionUtils.GetAttribute(typeof(ServiceContractAttribute), type, true) as ServiceContractAttribute; if (contractInterface != null) { object instance = Activator.CreateInstance(serviceType); IList parameterList = remotingMessage.body as IList; MethodInfo mi = MethodHandler.GetMethod(contractInterface, operation, parameterList, false, false); //MethodInfo mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); if (mi != null) { //TODO OperationContract attribute to alias it to a different publicly exposed name OperationContractAttribute operationContractAttribute = ReflectionUtils.GetAttribute(typeof(OperationContractAttribute), mi, true) as OperationContractAttribute; if (operationContractAttribute != null) { //mi = MethodHandler.GetMethod(serviceType, operation, parameterList, false, false); ParameterInfo[] parameterInfos = mi.GetParameters(); object[] args = new object[parameterInfos.Length]; parameterList.CopyTo(args, 0); TypeHelper.NarrowValues(args, parameterInfos); object result = mi.Invoke(instance, args); if (!(result is IMessage)) { responseMessage = new AcknowledgeMessage(); responseMessage.body = result; } else { responseMessage = result as IMessage; } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException("Method in not part of an service contract")); } } else { responseMessage = ErrorMessage.GetErrorMessage(remotingMessage, new SecurityException(String.Format("The specified contract {0} cannot be used with the source named {1} and operation named {2}", _endpoint.Contract.ContractType.Name, source, operation))); } } if (responseMessage is AsyncMessage) { ((AsyncMessage)responseMessage).correlationId = message.messageId; } responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; ResponseBody responseBody = new ResponseBody(amfBody, responseMessage); output.AddBody(responseBody); } } return(output); }
public DescribeService(AMFBody amfBody) { _amfBody = amfBody; }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { if (amfBody.IsWebService) { try { Type type = GetTypeForWebService(amfBody.TypeName); if (type != null) { //We can handle it with a LibraryAdapter now amfBody.Target = type.FullName + "." + amfBody.Method; } else { Exception exception = new TypeInitializationException(amfBody.TypeName, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } } else { //Flex message object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null && message is RemotingMessage) { RemotingMessage remotingMessage = message as RemotingMessage; //Only RemotingMessages for now string source = remotingMessage.source; if (source != null && source.ToLower().EndsWith(".asmx")) { try { Type type = GetTypeForWebService(source); if (type != null) { //We can handle it with a LibraryAdapter now remotingMessage.source = type.FullName; } else { Exception exception = new TypeInitializationException(source, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } } } } }