/// <summary> /// Serializes a reply message from a specified message version, array of parameters, and a return value. /// </summary> /// <param name="messageVersion"> /// The SOAP message version. /// </param> /// <param name="parameters"> /// The out parameters. /// </param> /// <param name="result"> /// The return value. /// </param> /// <returns> /// The serialized reply message. /// </returns> public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result) { // An AMF operation if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MessagingHeaders.InvokerMessageBody)) { var requestMessage = (AmfMessage)OperationContext.Current.IncomingMessageProperties[MessagingHeaders.InvokerMessageBody]; // An RPC operation if (OperationContext.Current.IncomingMessageProperties.ContainsKey(MessagingHeaders.RemotingMessage)) { var rpcMessage = (RemotingMessage) OperationContext.Current.IncomingMessageProperties[MessagingHeaders.RemotingMessage]; AcknowledgeMessage acknowledge = AmfOperationUtil.BuildAcknowledgeMessage(rpcMessage); acknowledge.Body = result; result = acknowledge; } var replyHeaders = new Dictionary <string, AmfHeader>(); var replyMessage = new AmfMessage { Data = result, Target = AmfOperationUtil.CreateResultReplyTarget(requestMessage), Response = string.Empty }; return(new AmfGenericMessage(replyHeaders, replyMessage)); } throw new OperationCanceledException(Errors.AmfGenericOperationFormatter_SerializeReply_InvalidOperation); }
private AcknowledgeMessage ExecuteGetSequenceIdOperation(IMessage message) { DataMessage dataMessage = message as DataMessage; AcknowledgeMessage responseMessage = null; DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination; //2 cases: body set or identity set if (dataMessage.body != null && dataMessage.body is IList) { dataMessage.operation = DataMessage.FillOperation; IList result = dataDestination.ServiceAdapter.Invoke(message) as IList;//Fill returns an IList responseMessage = dataDestination.SequenceManager.ManageSequence(dataMessage, result); dataMessage.operation = DataMessage.GetSequenceIdOperation; } else { dataMessage.operation = DataMessage.GetOperation; object result = dataDestination.ServiceAdapter.Invoke(message); if (result != null) { ArrayList collection = new ArrayList(1); collection.Add(result); responseMessage = dataDestination.SequenceManager.ManageSequence(dataMessage, collection); } else { SequencedMessage sequencedMessage = new SequencedMessage(); sequencedMessage.sequenceId = -1;//no sequence responseMessage = sequencedMessage; } dataMessage.operation = DataMessage.GetSequenceIdOperation; } return(responseMessage); }
private AcknowledgeMessage ExecuteGetSequenceIdOperation(IMessage message) { DataMessage message2 = message as DataMessage; AcknowledgeMessage message3 = null; DataDestination destination = base.GetDestination(message2) as DataDestination; if ((message2.body != null) && (message2.body is IList)) { message2.operation = 1; IList items = destination.ServiceAdapter.Invoke(message) as IList; message3 = destination.SequenceManager.ManageSequence(message2, items); message2.operation = 12; return(message3); } message2.operation = 2; object obj2 = destination.ServiceAdapter.Invoke(message); if (obj2 != null) { ArrayList list2 = new ArrayList(1); list2.Add(obj2); message3 = destination.SequenceManager.ManageSequence(message2, list2); } else { SequencedMessage message4 = new SequencedMessage { sequenceId = -1 }; message3 = message4; } message2.operation = 12; return(message3); }
public AcknowledgeMessage ManageSequence(DataMessage dataMessage, IList items, DataServiceTransaction dataServiceTransaction) { AcknowledgeMessage acknowledgeMessage = null; switch (dataMessage.operation) { case DataMessage.FillOperation: { Sequence sequence = CreateSequence(dataMessage.clientId as string, items, dataMessage.body as IList, dataServiceTransaction); acknowledgeMessage = GetSequencedMessage(dataMessage, sequence); } break; case DataMessage.GetOperation: case DataMessage.GetSequenceIdOperation: { Sequence sequence = CreateSequence(dataMessage.clientId as string, items, null, dataServiceTransaction); acknowledgeMessage = GetSequencedMessage(dataMessage, sequence); } break; default: { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.SequenceManager_Unknown, dataMessage.operation)); } } break; } return(acknowledgeMessage); }
public void AcknowledgeMessageEncoding() { AcknowledgeMessage originalMessage = new AcknowledgeMessage(); originalMessage.AddPacketId(1); originalMessage.AddPacketId(2); originalMessage.AddPacketId(3); originalMessage.AddPacketId(4); originalMessage.AddPacketId(5); Assert.AreEqual(5, originalMessage.PacketIdCount); byte[] encodedBytes = new byte[256]; int dataLength = originalMessage.EncodeFrameData(0, encodedBytes, 0); AcknowledgeMessage decodedMessage = new AcknowledgeMessage(); decodedMessage.DecodeFrameData(0, encodedBytes, 0, dataLength); decodedMessage.MessageId = originalMessage.MessageId; String originalMessageString = originalMessage.ToString(); String decodedMessageString = decodedMessage.ToString(); Assert.AreEqual(originalMessageString, decodedMessageString); Assert.AreEqual((uint)1, decodedMessage.GetPacketId(0)); Assert.AreEqual((uint)2, decodedMessage.GetPacketId(1)); Assert.AreEqual((uint)3, decodedMessage.GetPacketId(2)); Assert.AreEqual((uint)4, decodedMessage.GetPacketId(3)); Assert.AreEqual((uint)5, decodedMessage.GetPacketId(4)); }
private AcknowledgeMessage ExecuteReleaseItemOperation(IMessage message) { AcknowledgeMessage message2 = new AcknowledgeMessage(); DataMessage message3 = message as DataMessage; DataDestination destination = base.GetDestination(message3) as DataDestination; destination.SequenceManager.ReleaseItemOperation(message3); return(message2); }
/// <summary> /// Call this method in order to send a message from your code into the message routing system. /// The message is routed to a service that is defined to handle messages of this type. /// Once the service is identified, the destination property of the message is used to find a destination configured for that service. /// The adapter defined for that destination is used to handle the message. /// </summary> /// <param name="message">The message to be routed to a service.</param> /// <param name="endpoint">This can identify the endpoint that is sending the message but it is currently not used so you may pass in null.</param> /// <returns>The result of the message routing.</returns> internal IMessage RouteMessage(IMessage message, IEndpoint endpoint) { IService service = null; object result = null; IMessage responseMessage = null; CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation) { responseMessage = new AcknowledgeMessage(); responseMessage.body = true; } else { //log.Debug(string.Format("Locate service for message {0}", message.GetType().Name)); service = GetService(message); if (service != null) { try { result = service.ServiceMessage(message); } catch (Exception exception) { result = ErrorMessage.GetErrorMessage(message, exception); } } else { string msg = __Res.GetString(__Res.Destination_NotFound, message.destination); result = ErrorMessage.GetErrorMessage(message, new AMFException(msg)); } if (!(result is IMessage)) { responseMessage = new AcknowledgeMessage(); responseMessage.body = result; } else { responseMessage = result as IMessage; } } if (responseMessage is AsyncMessage) { ((AsyncMessage)responseMessage).correlationId = message.messageId; } responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; //The only case when we do not have context should be when the server side initiates a push if (Context.AMFContext.Current != null && Context.AMFContext.Current.Client != null) { responseMessage.SetHeader(MessageBase.FlexClientIdHeader, Context.AMFContext.Current.Client.Id); } return(responseMessage); }
private AcknowledgeMessage ExecuteReleaseItemOperation(IMessage message) { AcknowledgeMessage responseMessage = new AcknowledgeMessage(); DataMessage dataMessage = message as DataMessage; DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination; dataDestination.SequenceManager.ReleaseItemOperation(dataMessage); return(responseMessage); }
private AcknowledgeMessage ExecuteFillOperation(IMessage message) { DataMessage dataMessage = message as DataMessage; AcknowledgeMessage responseMessage = null; DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination; IList collection = dataDestination.ServiceAdapter.Invoke(message) as IList; responseMessage = dataDestination.SequenceManager.ManageSequence(dataMessage, collection); return(responseMessage); }
/// <summary> /// 解析响应报文,把报文内容以字符串的形式返回 /// </summary> /// <param name="response">响应报文</param> /// <returns>返回报文内容字符串</returns> public static string GetText(this WebResponse response) { using (Stream stream = response.GetResponseStream()) { using (AMFDeserializer amfDeserializer = new AMFDeserializer(stream)) { AcknowledgeMessage msg = (AcknowledgeMessage)amfDeserializer.ReadAMFMessage().Bodies[0].Content; return(Convert.ToString(msg.body)); } } }
public CachedBody(AMFBody requestBody, IMessage message, object content) : base(requestBody, content) { AcknowledgeMessage message2 = new AcknowledgeMessage { body = content, correlationId = message.messageId, destination = message.destination, clientId = message.clientId }; base.Content = message2; }
public override object ServiceMessage(IMessage message) { IMessage responseMessage = null; CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null) { switch (commandMessage.operation) { case CommandMessage.LoginOperation: IPrincipal principal = null; try { principal = Authenticate(message); } catch (SecurityException) { throw; } catch (UnauthorizedAccessException) { throw; } catch (Exception exception) { string msg = __Res.GetString(__Res.Security_AuthenticationFailed); if (log.IsErrorEnabled) { log.Error(msg, exception); } throw new SecurityException(msg, exception); } if (principal == null) { string msg = __Res.GetString(__Res.Security_AuthenticationFailed); throw new SecurityException(msg); } responseMessage = new AcknowledgeMessage(); responseMessage.body = "success"; break; case CommandMessage.LogoutOperation: //TODO: Logs the user out of the destination. Logging out of a destination applies to everything connected using the same ChannelSet as specified in the server configuration. //For example, if you're connected over the my-rtmp channel and you log out using one of your RPC components, anything that was //connected over the same ChannelSet is logged out. _messageBroker.LoginManager.Logout(); responseMessage = new AcknowledgeMessage(); responseMessage.body = "success"; break; } } return(responseMessage); }
private AcknowledgeMessage ExecuteMultiBatchOperation(IMessage message) { //May contain multiple batched, create, update or delete operations that involve //more than one destination, that is, more than one remote adapter AcknowledgeMessage responseMessage = null; DataMessage dataMessage = message as DataMessage; IList messages = dataMessage.body as IList; DataServiceTransaction dataServiceTransaction = DataServiceTransaction.Begin(this); dataServiceTransaction.ClientId = message.clientId as string; //correlate al generated messages dataServiceTransaction.CorrelationId = message.messageId; string currentDestination = null; ArrayList currentMessageBatch = new ArrayList(); for (int i = 0; i < messages.Count; i++) { DataMessage batchMessage = messages[i] as DataMessage; string destination = batchMessage.destination; DataDestination dataDestination = GetDestination(batchMessage) as DataDestination; if (currentDestination != null && destination != currentDestination && currentMessageBatch.Count > 0) { MessageBatch messageBatch = ServiceBatch(message, currentMessageBatch); dataServiceTransaction.AddProcessedMessageBatch(messageBatch); currentMessageBatch = new ArrayList(); } currentMessageBatch.Add(batchMessage); currentDestination = destination; if (batchMessage is UpdateCollectionMessage) { dataServiceTransaction.AddClientUpdateCollection(batchMessage as UpdateCollectionMessage); } } if (currentMessageBatch.Count > 0) { MessageBatch messageBatch = ServiceBatch(message, currentMessageBatch); dataServiceTransaction.AddProcessedMessageBatch(messageBatch); } dataServiceTransaction.Commit(); IList outgoingMessages = dataServiceTransaction.GetOutgoingMessages(); responseMessage = new AcknowledgeMessage(); object[] result = new object[outgoingMessages.Count]; outgoingMessages.CopyTo(result, 0); responseMessage.body = result; //outgoingMessages.ToArray(typeof(object)); return(responseMessage); }
public CachedBody(AMFBody requestBody, IMessage message, object content) : base(requestBody, content) { //Fix content of body for flex messages AcknowledgeMessage responseMessage = new AcknowledgeMessage(); responseMessage.body = content; responseMessage.correlationId = message.messageId; responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; this.Content = responseMessage; }
/// <summary> /// Handle command message: a clinet ping. /// </summary> /// <param name="request"> /// The request. /// </param> /// <param name="message"> /// The message. /// </param> /// <returns> /// The <see cref="AmfGenericMessage"/>. /// </returns> private AmfGenericMessage HandleClientPing(AmfGenericMessage request, CommandMessage message) { AcknowledgeMessage acknowledge = AmfOperationUtil.BuildAcknowledgeMessage(message); acknowledge.Headers = new Dictionary <string, object> { { CommandMessageHeader.MessagingVersion, this.Capabilities.MessagingVersion } }; return(AmfOperationUtil.BuildMessageReply(request, acknowledge)); }
public void ResultReceived(IPendingServiceCall call) { //Unwrap flex messages if (call.Result is ErrorMessage) { call.Status = Messaging.Rtmp.Service.Call.STATUS_INVOCATION_EXCEPTION; } else if (call.Result is AcknowledgeMessage) { AcknowledgeMessage ack = call.Result as AcknowledgeMessage; call.Result = ack.body; call.Status = Messaging.Rtmp.Service.Call.STATUS_SUCCESS_RESULT; } _callback.ResultReceived(call); }
public void AcknowledgeMessageClear() { AcknowledgeMessage originalMessage = new AcknowledgeMessage(); originalMessage.AddPacketId(1); originalMessage.AddPacketId(2); originalMessage.AddPacketId(3); originalMessage.AddPacketId(4); originalMessage.AddPacketId(5); originalMessage.Clear(); AcknowledgeMessage emptyMessage = new AcknowledgeMessage(); emptyMessage.MessageId = originalMessage.MessageId; Assert.AreEqual(originalMessage.ToString(), emptyMessage.ToString()); }
/// <summary> /// Adds given packet id to existing acknowledge message or creates new acknowledge message and adds to it. /// </summary> /// <param name="packetId"> /// A packet id to be acknowledged.<see cref="System.UInt32"/> /// </param> public void AddAcknowledge(uint packetId) { lock (outboundAcknowledgeMessages) { if (outboundAcknowledgeMessages.Count == 0) { outboundAcknowledgeMessages.Add((AcknowledgeMessage)MessageFactory.Current.ReserveMessage(typeof(AcknowledgeMessage))); } AcknowledgeMessage acknowledgeMessage = outboundAcknowledgeMessages[outboundAcknowledgeMessages.Count - 1]; if (acknowledgeMessage.PacketIdCount == acknowledgeMessage.MaxPacketIdCount) { outboundAcknowledgeMessages.Add((AcknowledgeMessage)MessageFactory.Current.ReserveMessage(typeof(AcknowledgeMessage))); acknowledgeMessage = outboundAcknowledgeMessages[outboundAcknowledgeMessages.Count - 1]; } acknowledgeMessage.AddPacketId(packetId); } }
private AcknowledgeMessage ExecuteMultiBatchOperation(IMessage message) { AcknowledgeMessage message2 = null; MessageBatch batch; DataMessage message3 = message as DataMessage; IList body = message3.body as IList; DataServiceTransaction transaction = DataServiceTransaction.Begin(this); transaction.ClientId = message.clientId as string; transaction.CorrelationId = message.messageId; string str = null; ArrayList messages = new ArrayList(); for (int i = 0; i < body.Count; i++) { DataMessage message4 = body[i] as DataMessage; string str2 = message4.destination; DataDestination destination = base.GetDestination(message4) as DataDestination; if (((str != null) && (str2 != str)) && (messages.Count > 0)) { batch = this.ServiceBatch(message, messages); transaction.AddProcessedMessageBatch(batch); messages = new ArrayList(); } messages.Add(message4); str = str2; if (message4 is UpdateCollectionMessage) { transaction.AddClientUpdateCollection(message4 as UpdateCollectionMessage); } } if (messages.Count > 0) { batch = this.ServiceBatch(message, messages); transaction.AddProcessedMessageBatch(batch); } transaction.Commit(); IList outgoingMessages = transaction.GetOutgoingMessages(); message2 = new AcknowledgeMessage(); object[] array = new object[outgoingMessages.Count]; outgoingMessages.CopyTo(array, 0); message2.body = array; return(message2); }
public void BeginTask() { switch (requestMessage.Operation) { case CommandMessage.OperationCode.ClientPing: responseMessage = AcknowledgeMessage.CreateAcknowledgeResponse(requestMessage, null); SignalCompletion(true); break; default: responseMessage = ErrorMessage.CreateErrorResponse(requestMessage, String.Format(CultureInfo.CurrentCulture, "Operation '{0}' is not supported by the default command service.", requestMessage.Operation), "Gateway.DefaultCommandService.UnsupportedOperation", null); SignalCompletion(true); break; } }
public void BeginTask() { CommandMessage commandMessage = requestMessage as CommandMessage; if (commandMessage != null) { responseMessage = ErrorMessage.CreateErrorResponse(requestMessage, "Remoting service does not handle command messages currently.", "Gateway.RemotingService.UnsupportedCommandMessage", null); SignalCompletion(true); return; } RemotingMessage remotingMessage = (RemotingMessage)requestMessage; responseMessage = AcknowledgeMessage.CreateAcknowledgeResponse(remotingMessage, new object[] { "Response!" }); SignalCompletion(true); }
private AcknowledgeMessage ExecuteGetOperation(IMessage message) { DataMessage dataMessage = message as DataMessage; AcknowledgeMessage responseMessage = null; DataDestination dataDestination = this.GetDestination(dataMessage) as DataDestination; object result = dataDestination.ServiceAdapter.Invoke(message); if (result == null) { responseMessage = new AcknowledgeMessage(); } else { ArrayList collection = new ArrayList(1); collection.Add(result); responseMessage = dataDestination.SequenceManager.ManageSequence(dataMessage, collection); } return(responseMessage); }
public void ResultReceived(IPendingServiceCall call) { //Unwrap flex messages if (call.Result is ErrorMessage) { StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction; if (statusFunction != null) { statusFunction(new Fault(call.Result as ErrorMessage)); } } else if (call.Result is AcknowledgeMessage) { AcknowledgeMessage ack = call.Result as AcknowledgeMessage; Delegate resultFunction = _responder.GetType().GetProperty("Result").GetValue(_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 if (call.IsSuccess) { Delegate resultFunction = _responder.GetType().GetProperty("Result").GetValue(_responder, null) as Delegate; if (resultFunction != null) { ParameterInfo[] arguments = resultFunction.Method.GetParameters(); object result = TypeHelper.ChangeType(call.Result, arguments[0].ParameterType); resultFunction.DynamicInvoke(result); } } else { StatusFunction statusFunction = _responder.GetType().GetProperty("Status").GetValue(_responder, null) as StatusFunction; if (statusFunction != null) { statusFunction(new Fault(call.Result)); } } }
internal void Receive(Message message, bool fromPartials = false) { this.lastReceiveActivity = Stopwatch.GetTimestamp(); var args = new MessageEventArgs(this, message); if (!fromPartials && message.Header.MessageId != 0 && (args.Message.MustBeReliable || args.Message.PreferReliable)) { // We generally always need to ACK. partials have their pieces acked individually. var ack = new AcknowledgeMessage { MessageIds = new[] { message.Header.MessageId } }; bool isConnect = (message is ConnectMessage); if (!isConnect) { SendAsync(ack); } List <MessageEventArgs> messages; if (this.rqueue.TryEnqueue(args, out messages)) { if (messages != null) { foreach (MessageEventArgs messageEventArgs in messages) { RouteMessage(messageEventArgs); } } } // We ACK for Connect after it's routed so it can setup the serializers if (isConnect) { SendAsync(ack); } } else { RouteMessage(args); } }
internal IMessage RouteMessage(IMessage message, IEndpoint endpoint) { IService service = null; object obj2 = null; IMessage errorMessage = null; Exception exception2; CommandMessage message3 = message as CommandMessage; if ((message3 != null) && ((message3.operation == 8) || (message3.operation == 9))) { log.Debug(string.Format("Routing CommandMessage operation = {0}", message3.operation)); try { errorMessage = this.GetService("authentication-service").ServiceMessage(message3) as IMessage; } catch (SecurityException exception) { if (log.get_IsDebugEnabled()) { log.Debug(exception.Message); } errorMessage = ErrorMessage.GetErrorMessage(message, exception); } catch (Exception exception4) { exception2 = exception4; if (log.get_IsErrorEnabled()) { log.Error(__Res.GetString("MessageBroker_RoutingError"), exception2); } errorMessage = ErrorMessage.GetErrorMessage(message, exception2); } } else if ((message3 != null) && (message3.operation == 5)) { log.Debug("Routing CommandMessage ping"); errorMessage = new AcknowledgeMessage { body = true }; } else { log.Debug(string.Format("Routing message {0}", message.GetType().Name)); if (FluorineContext.Current != null) { FluorineContext.Current.RestorePrincipal(this.LoginCommand); } service = this.GetService(message); if (service != null) { try { service.CheckSecurity(message); obj2 = service.ServiceMessage(message); } catch (UnauthorizedAccessException exception3) { if (log.get_IsDebugEnabled()) { log.Debug(exception3.Message); } obj2 = ErrorMessage.GetErrorMessage(message, exception3); } catch (Exception exception6) { exception2 = exception6; if (log.get_IsErrorEnabled()) { log.Error(exception2.Message, exception2); } obj2 = ErrorMessage.GetErrorMessage(message, exception2); } } else { string str = __Res.GetString("Destination_NotFound", new object[] { message.destination }); if (log.get_IsErrorEnabled()) { log.Error(str); } obj2 = ErrorMessage.GetErrorMessage(message, new FluorineException(str)); } if (obj2 is IMessage) { errorMessage = obj2 as IMessage; } else { errorMessage = new AcknowledgeMessage { body = obj2 }; } } if (errorMessage is AsyncMessage) { ((AsyncMessage)errorMessage).correlationId = message.messageId; } errorMessage.destination = message.destination; errorMessage.clientId = message.clientId; if (message.HeaderExists("amf_server_debug")) { log.Debug("MessageBroker processing debug header"); ArrayList traceStack = NetDebug.GetTraceStack(); errorMessage.SetHeader("amf_server_debug", traceStack.ToArray(typeof(object)) as object[]); NetDebug.Clear(); } if ((FluorineContext.Current != null) && (FluorineContext.Current.Client != null)) { errorMessage.SetHeader("DSId", FluorineContext.Current.Client.Id); } return(errorMessage); }
/// <summary> /// Call this method in order to send a message from your code into the message routing system. /// The message is routed to a service that is defined to handle messages of this type. /// Once the service is identified, the destination property of the message is used to find a destination configured for that service. /// The adapter defined for that destination is used to handle the message. /// </summary> /// <param name="message">The message to be routed to a service.</param> /// <param name="endpoint">This can identify the endpoint that is sending the message but it is currently not used so you may pass in null.</param> /// <returns>The result of the message routing.</returns> internal IMessage RouteMessage(IMessage message, IEndpoint endpoint) { IService service = null; object result = null; IMessage responseMessage = null; if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageBroker_RoutingMessage, message.ToString())); } CommandMessage commandMessage = message as CommandMessage; if (commandMessage != null && (commandMessage.operation == CommandMessage.LoginOperation || commandMessage.operation == CommandMessage.LogoutOperation)) //Login, Logout { try { service = GetService(AuthenticationService.ServiceId); result = service.ServiceMessage(commandMessage); responseMessage = result as IMessage; } catch (UnauthorizedAccessException uae) { if (log.IsDebugEnabled) { log.Debug(uae.Message); } responseMessage = ErrorMessage.GetErrorMessage(message, uae); } catch (SecurityException exception) { if (log.IsDebugEnabled) { log.Debug(exception.Message); } responseMessage = ErrorMessage.GetErrorMessage(message, exception); } catch (Exception exception) { if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.MessageBroker_RoutingError), exception); } responseMessage = ErrorMessage.GetErrorMessage(message, exception); } } else if (commandMessage != null && commandMessage.operation == CommandMessage.ClientPingOperation) { responseMessage = new AcknowledgeMessage(); responseMessage.body = true; } else { //The only case when context is not set should be when one starts a new thread in the backend //if( FluorineContext.Current != null ) // FluorineContext.Current.RestorePrincipal(this.LoginCommand); _loginManager.RestorePrincipal(); service = GetService(message); if (service != null) { try { service.CheckSecurity(message); result = service.ServiceMessage(message); } catch (UnauthorizedAccessException uae) { if (log.IsDebugEnabled) { log.Debug(uae.Message); } result = ErrorMessage.GetErrorMessage(message, uae); } catch (SecurityException exception) { if (log.IsDebugEnabled) { log.Debug(exception.Message); } result = ErrorMessage.GetErrorMessage(message, exception); } catch (ServiceException exception) { if (log.IsDebugEnabled) { log.Debug(exception.Message); } result = ErrorMessage.GetErrorMessage(message, exception); } catch (Exception exception) { if (log.IsErrorEnabled) { log.Error(exception.Message, exception); } result = ErrorMessage.GetErrorMessage(message, exception); } } else { string msg = __Res.GetString(__Res.Destination_NotFound, message.destination); if (log.IsErrorEnabled) { log.Error(msg); } result = ErrorMessage.GetErrorMessage(message, new FluorineException(msg)); } if (!(result is IMessage)) { responseMessage = new AcknowledgeMessage(); responseMessage.body = result; } else { responseMessage = result as IMessage; } } if (responseMessage is AsyncMessage) { ((AsyncMessage)responseMessage).correlationId = message.messageId; } responseMessage.destination = message.destination; responseMessage.clientId = message.clientId; //Debug if (message.HeaderExists(AMFHeader.DebugHeader)) { log.Debug("MessageBroker processing debug header"); ArrayList traceStack = NetDebug.GetTraceStack(); responseMessage.SetHeader(AMFHeader.DebugHeader, traceStack.ToArray(typeof(object)) as object[]); NetDebug.Clear(); } //The only case when we do not have context should be when the server side initiates a push if (FluorineContext.Current != null && FluorineContext.Current.Client != null) { responseMessage.SetHeader(MessageBase.FlexClientIdHeader, FluorineContext.Current.Client.Id); } if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageBroker_Response, responseMessage.ToString())); } return(responseMessage); }
public async Task Handle(NotificationMessage input, IAddress address) { log.LogInformation("{@Address}; message body: '{body}'", address, BitConverter.ToString(input.Body.ToArray())); var message = new AcknowledgeMessage(_bleCommand.Command, new byte[] { 0x00, 0x01 }); await _messageBus.Publish(message, address.TransportName); }
private void HandleFlexClientStreamingOpenRequest(HttpRequest request, HttpResponse response, IClient flexClient) { Session session = FluorineContext.Current.Session as Session; if (session == null) { string msg = string.Format("Cannot grant streaming connection when ASP.NET session state is disabled", this.Id); if (log.IsWarnEnabled) { log.Warn(msg); } try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } if (!_canStream || !session.CanStream) { string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } bool canStream = false; lock (this.SyncRoot) { _streamingClientsCount.Increment(); if (_streamingClientsCount.Value == this.MaxStreamingClients) { canStream = true; // This thread got the last spot. _canStream = false; } else if (_streamingClientsCount.Value > this.MaxStreamingClients) { canStream = false; // This thread lost the last spot. _streamingClientsCount.Decrement(); // We're not going to grant the streaming right to the client. } else { // Allow this thread to stream. canStream = true; } } if (!canStream) { string msg = string.Format("Cannot service streaming request, max-streaming-clients reached in endpoint {0}", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } UserAgent userAgent = this.ChannelDefinition.Properties.UserAgentSettings[request.Browser.Browser]; if (userAgent != null) { lock (session.SyncRoot) { session.MaxConnectionsPerSession = userAgent.MaxStreamingConnectionsPerSession; } } lock (session.SyncRoot) { session.StreamingConnectionsCount++; if (session.StreamingConnectionsCount == session.MaxConnectionsPerSession) { canStream = true; // This thread got the last spot in the session. session.CanStream = false; } else if (session.StreamingConnectionsCount > session.MaxConnectionsPerSession) { canStream = false; session.StreamingConnectionsCount--; _streamingClientsCount.Decrement(); } else { canStream = true; } } if (!canStream) { string msg = string.Format("Cannot grant streaming connection, limit has been reached", this.Id); try { HandleBadRequest(msg, HttpContext.Current.Response); } catch (HttpException) { } return; } EndpointPushNotifier notifier = null; try { response.ContentType = ContentType.AMF; response.AppendHeader("Cache-Control", "no-cache"); response.AppendHeader("Pragma", "no-cache"); response.AppendHeader("Connection", "close"); //response.AppendHeader("Transfer-Encoding", "chunked"); response.Flush(); // Setup for specific user agents. byte[] kickStartBytesToStream = null; int kickStartBytes = userAgent != null ? userAgent.KickstartBytes : 0; if (kickStartBytes > 0) { // The minimum number of actual bytes that need to be sent to kickstart, taking into account transfer-encoding overhead. try { int chunkLengthHeaderSize = System.Text.Encoding.ASCII.GetBytes(System.Convert.ToString(kickStartBytes, 0x10)).Length; //System.Text.ASCIIEncoding.ASCII.GetBytes(kickStartBytes.ToString("X")).Length; int chunkOverhead = chunkLengthHeaderSize + 4; // 4 for the 2 wrapping CRLF tokens. int minimumKickstartBytes = kickStartBytes - chunkOverhead; kickStartBytesToStream = new byte[(minimumKickstartBytes > 0) ? minimumKickstartBytes : kickStartBytes]; } catch { kickStartBytesToStream = new byte[kickStartBytes]; } } if (kickStartBytesToStream != null) { StreamChunk(kickStartBytesToStream, response); } try { notifier = new EndpointPushNotifier(this, flexClient); lock (_currentStreamingRequests.SyncRoot) { _currentStreamingRequests.Add(notifier.Id, notifier); } // Push down an acknowledgement for the 'connect' request containing the unique id for this specific stream. AcknowledgeMessage connectAck = new AcknowledgeMessage(); connectAck.body = notifier.Id; connectAck.correlationId = OpenCommand; StreamMessage(connectAck, response); } catch (MessageException) { } if (log.IsDebugEnabled) { string msg = string.Format("Start streaming for endpoint with id {0} and client with id {1}", this.Id, flexClient.Id); log.Debug(msg); } int serverToClientHeartbeatMillis = this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis >= 0 ? this.ChannelDefinition.Properties.ServerToClientHeartbeatMillis : 0; serverToClientHeartbeatMillis = 100; while (!notifier.IsClosed) { IList messages = notifier.GetPendingMessages(); StreamMessages(messages, response); lock (notifier.SyncRoot) { Monitor.Wait(notifier.SyncRoot, serverToClientHeartbeatMillis); messages = notifier.GetPendingMessages(); // If there are no messages to send to the client, send a 0 // byte as a heartbeat to make sure the client is still valid. if ((messages == null || messages.Count == 0) && serverToClientHeartbeatMillis > 0) { try { StreamChunk(Heartbeat, response); response.Flush(); } catch (HttpException) { break; } catch (IOException) { break; } } else { StreamMessages(messages, response); } } } // Terminate the response. StreamChunk(null, response); if (log.IsDebugEnabled) { string msg = string.Format("Releasing streaming connection for endpoint with id {0} and and client with id {1}", this.Id, flexClient.Id); log.Debug(msg); } } catch (IOException ex) //HttpException? { if (log.IsWarnEnabled) { log.Warn("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an IO error.", ex); } } catch (Exception ex) { if (log.IsErrorEnabled) { log.Error("Streaming thread for endpoint with id " + this.Id + " is closing connection due to an error.", ex); } } finally { if (notifier != null && _currentStreamingRequests != null) { if (_currentStreamingRequests != null) { lock (_currentStreamingRequests.SyncRoot) { _currentStreamingRequests.Remove(notifier.Id); } } notifier.Close(); } _streamingClientsCount.Decrement(); lock (session.SyncRoot) { session.StreamingConnectionsCount--; session.CanStream = session.StreamingConnectionsCount < session.MaxConnectionsPerSession; } } }
public AcknowledgeMessageExt(AcknowledgeMessage message):base() { _message = message; }
public void Acknowledge() { var m = new AcknowledgeMessage(AppModel.Instance.LocalDevice); SendUdpMessage(m); }
/// <summary> /// Handles a message routed to the service by the MessageBroker. /// </summary> /// <param name="message">The message that should be handled by the service.</param> /// <returns>The result of the message processing.</returns> public override object ServiceMessage(IMessage message) { CommandMessage commandMessage = message as CommandMessage; MessageDestination messageDestination = GetDestination(message) as MessageDestination; if (commandMessage != null) { string clientId = commandMessage.clientId as string; MessageClient messageClient = messageDestination.SubscriptionManager.GetSubscriber(clientId); AcknowledgeMessage acknowledgeMessage = null; switch (commandMessage.operation) { case CommandMessage.SubscribeOperation: if (messageClient == null) { if (clientId == null) { clientId = Guid.NewGuid().ToString("D"); } if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServiceSubscribe, messageDestination.Id, clientId)); } string endpointId = commandMessage.GetHeader(MessageBase.EndpointHeader) as string; if (_messageBroker.GetEndpoint(endpointId) == null) { ServiceException serviceException = new ServiceException("Endpoint was not specified"); serviceException.FaultCode = "Server.Processing.MissingEndpoint"; throw serviceException; } commandMessage.clientId = clientId; if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions) { try { acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage; } catch (MessageException me) { acknowledgeMessage = me.GetErrorMessage(); //Leave, do not subscribe return(acknowledgeMessage); } catch (Exception ex) { //Guard against service adapter failure acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex); if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex); } //Leave, do not subscribe return(acknowledgeMessage); } } Subtopic subtopic = null; Selector selector = null; if (commandMessage.headers != null) { if (commandMessage.headers.ContainsKey(CommandMessage.SelectorHeader)) { selector = Selector.CreateSelector(commandMessage.headers[CommandMessage.SelectorHeader] as string); } if (commandMessage.headers.ContainsKey(AsyncMessage.SubtopicHeader)) { subtopic = new Subtopic(commandMessage.headers[AsyncMessage.SubtopicHeader] as string); } } IClient client = FluorineContext.Current.Client; client.Renew(); messageClient = messageDestination.SubscriptionManager.AddSubscriber(clientId, endpointId, subtopic, selector); if (acknowledgeMessage == null) { acknowledgeMessage = new AcknowledgeMessage(); } acknowledgeMessage.clientId = clientId; } else { acknowledgeMessage = new AcknowledgeMessage(); acknowledgeMessage.clientId = clientId; } return(acknowledgeMessage); case CommandMessage.UnsubscribeOperation: if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServiceUnsubscribe, messageDestination.Id, clientId)); } if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions) { try { acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage; } catch (MessageException me) { acknowledgeMessage = me.GetErrorMessage(); } catch (Exception ex) { //Guard against service adapter failure acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex); if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex); } } } if (messageClient != null) { messageDestination.SubscriptionManager.RemoveSubscriber(messageClient); } if (acknowledgeMessage == null) { acknowledgeMessage = new AcknowledgeMessage(); } return(acknowledgeMessage); case CommandMessage.PollOperation: { if (messageClient == null) { ServiceException serviceException = new ServiceException(string.Format("MessageClient is not subscribed to {0}", commandMessage.destination)); serviceException.FaultCode = "Server.Processing.NotSubscribed"; throw serviceException; } IClient client = FluorineContext.Current.Client; client.Renew(); try { acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage; } catch (MessageException me) { acknowledgeMessage = me.GetErrorMessage(); } catch (Exception ex) { //Guard against service adapter failure acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex); if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex); } } if (acknowledgeMessage == null) { acknowledgeMessage = new AcknowledgeMessage(); } return(acknowledgeMessage); } case CommandMessage.ClientPingOperation: if (messageDestination.ServiceAdapter != null && messageDestination.ServiceAdapter.HandlesSubscriptions) { try { messageDestination.ServiceAdapter.Manage(commandMessage); } catch (MessageException) { return(false); } catch (Exception ex) { //Guard against service adapter failure if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex); } return(false); } } return(true); default: if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServiceUnknown, commandMessage.operation, messageDestination.Id)); } try { acknowledgeMessage = messageDestination.ServiceAdapter.Manage(commandMessage) as AcknowledgeMessage; } catch (MessageException me) { acknowledgeMessage = me.GetErrorMessage(); } catch (Exception ex) { //Guard against service adapter failure acknowledgeMessage = ErrorMessage.GetErrorMessage(commandMessage, ex); if (log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.ServiceAdapter_ManageFail, this.id, messageDestination.Id, commandMessage), ex); } } if (acknowledgeMessage == null) { acknowledgeMessage = new AcknowledgeMessage(); } return(acknowledgeMessage); } } else { if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.MessageServiceRoute, messageDestination.Id, message.clientId)); } if (FluorineContext.Current != null && FluorineContext.Current.Client != null)//Not set when user code initiates push { IClient client = FluorineContext.Current.Client; client.Renew(); } object result = messageDestination.ServiceAdapter.Invoke(message); return(result); } }
private async Task ListenAsync(short channel) { bool listening = true; while (listening) { var result = await Client.ReceiveAsync(); var message = Messaging.ReceiveMessage(result.Buffer); switch (message.Type) { case MessageType.Disconnect: case MessageType.Terminate: await EndConnection(channel, true); listening = false; break; case MessageType.Acknowledge: var acknowledgeMessage = new AcknowledgeMessage(message.Payload); ClientResolutionChanged?.Invoke(this, new ClientResolutionChangedEventArgs(acknowledgeMessage.ScreenWidth, acknowledgeMessage.ScreenHeight)); IsConnected = true; break; case MessageType.Sharing: var sharingMessage = new SharingMessage(message.Payload); Sharing?.Invoke(this, sharingMessage.IsSharing); break; case MessageType.Image: var imageMessage = new ImageMessage(message.Payload); try { var imageFragment = ImageFragments.FirstOrDefault(mf => mf.MessageId.Equals(message.MessageId)); if (imageFragment == null) { imageFragment = new ImageFragment(message.MessageId, imageMessage); ImageFragments.Add(imageFragment); } else imageFragment.AddFragment(imageMessage); } catch (Exception ex) { Console.WriteLine($"Something bad happened: {ex.Message}"); } break; case MessageType.MouseMessage: var mouseMessage = new MouseMessage(message.Payload); MouseMove?.Invoke(this, new MouseMoveEventArgs(mouseMessage.X, mouseMessage.Y, mouseMessage.ScreenWidth, mouseMessage.ScreenHeight)); break; } } }