public static void Handle(Message message, DofusClient client) { if (message.IsNull() && !client.IsNull()) { Logger.Init2("[Rcv] Client " + client.SSyncClient.Ip + " send unknown datas, they wont be handled"); return; } var handler = Handlers.FirstOrDefault(x => x.Key == message.MessageId); if (!handler.Value.IsNull()) { { if (ConfigurationManager.Instance.ShowProtocolMessages) Logger.Write("[Rcv] Message: " + message.ToString(), ConsoleColor.Gray); try { handler.Value.DynamicInvoke(null, message, client); } catch (Exception ex) { Logger.Error(string.Format("Unable to handle message {0} {1} : '{2}'", message.ToString(), handler.Value.Method.Name, ex.InnerException.ToString())); ErrorLogsManager.AddLog(ex.InnerException.ToString(), client.SSyncClient.Ip); client.SendRaw("forcedbugreport"); } } } else { if (ConfigurationManager.Instance.ShowProtocolMessages) Logger.Log(string.Format("[Rcv] No Handler: ({0}) {1}", message.MessageId, message.ToString())); } }
private static string CreateIncomingMessage(Message request, string serviceName) { #region Aggregate Data var messageProperties = OperationContext.Current.IncomingMessageProperties; var remoteEndpointMessageProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty; var sourceAddress = remoteEndpointMessageProperty != null ? remoteEndpointMessageProperty.Address : m_Unknown; var sourcePort = remoteEndpointMessageProperty != null ? remoteEndpointMessageProperty.Port.ToString() : m_Unknown; var targetUri = request.Headers.To.ToString(); var webOperationContext = WebOperationContext.Current; var method = webOperationContext != null ? webOperationContext.IncomingRequest.Method : m_Unknown; var authorizationKey = webOperationContext != null ? webOperationContext.IncomingRequest.Headers[HttpRequestHeader.Authorization] : null; #endregion #region Compose logging message var stringBuilder = new StringBuilder(); stringBuilder.AppendLine(); stringBuilder.AppendLine(string.Format("-------- Incoming message received on {0}. Details:", serviceName)); stringBuilder.AppendLine(string.Format("Source address: {0} ({1})", sourceAddress, sourcePort)); stringBuilder.AppendLine(string.Format("Target URI: {0}", targetUri)); if (method != null) stringBuilder.AppendLine(string.Format("HTTP method: {0}", method)); if (authorizationKey != null) stringBuilder.AppendLine(string.Format("Authorization key: {0}", authorizationKey)); stringBuilder.AppendLine("Incoming Message:"); stringBuilder.AppendLine(string.IsNullOrEmpty(request.ToString()) ? "<No incoming message>" : request.ToString()); stringBuilder.AppendLine("--------"); #endregion return stringBuilder.ToString(); }
/// <summary> /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application. /// </summary> /// <param name="reply">The message to be transformed into types and handed back to the client application.</param> /// <param name="correlationState">Correlation state data.</param> public void AfterReceiveReply( ref Message reply, object correlationState ) { if( correlationState != null ) this._logger.Trace( @"Response {{{0}}}: {1}", correlationState.ToString(), reply.ToString() ); else this._logger.Trace( @"Response: {0}", reply.ToString() ); }
public void ReturnFriendlyDescription() { var id = Guid.NewGuid(); var message = new Message<Object>(id, HeaderCollection.Empty, new Object()); Assert.Equal($"{id} - System.Object", message.ToString()); }
public override string ToString() { var redact = false; var redactionLevel = LogManager.RedactionLevel; switch (redactionLevel) { case RedactionLevel.Full: redact = true; break; case RedactionLevel.None: break; case RedactionLevel.Partial: redact = (RedactionType == _user); break; default: throw new ArgumentOutOfRangeException(Enum.GetName(typeof(RedactionLevel), redactionLevel), "Unexpected redaction level: {redactionLevel}"); } return(redact ? string.Concat("<", RedactionType, ">", Message, "</", RedactionType, ">") : Message?.ToString()); }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { var logger = ObjectFactory.GetInstance<ILogger>(); logger.StartAction(request.Headers.To.ToString()); logger.Write("Incoming Message", request.ToString()); return null; }
/// <summary>Enables inspection or modification of a message before a request message is sent to a service.</summary> /// <param name="request">The message to be sent to the service.</param> /// <param name="channel">The client object channel.</param> /// <returns> /// The object that is returned as the <c>correlationState</c> argument of the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)"/> method. This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid"/> to ensure that no two <c>correlationState</c> objects are the same. /// </returns> public object BeforeSendRequest( ref Message request, IClientChannel channel ) { var correlationState = Guid.NewGuid(); this._logger.Trace( @"Request {{{0}}}: {1}", correlationState.ToString(), request.ToString() ); return correlationState; }
public object BeforeSendRequest( ref Message request, IClientChannel channel) { reqPayload = request.ToString(); return null; }
/// <summary> /// Called after response is received /// </summary> /// <param name="reply"></param> /// <param name="correlationState"></param> public void AfterReceiveReply(ref Message reply, object correlationState) { if (this.config.HttpHeaderLoggingEnabled) { //logging http headers HttpResponseMessageProperty httpResponse = reply.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; if (httpResponse != null && httpResponse.Headers != null && httpResponse.Headers.Count > 0) { string httpHeaderMessage = "---[HTTP Response Headers]---\r\n"; foreach (string headerName in httpResponse.Headers.AllKeys) { httpHeaderMessage += headerName + " : " + httpResponse.Headers[headerName] + "\r\n"; } //logger.Info(httpHeaderMessage); } else { //logger.Info("HTTP Response Headers is not available!"); } } if (this.config.SoapMessageLoggingEnabled) { //logging soap message string soapMessage = "receiving soap request message ...\r\n" + reply.ToString(); //logger.Info(soapMessage); } }
public void InformationalWithEnum(Message message) { if (this.IsEnabled()) { this.WriteEvent(1, message.ToString()); } }
/// <summary> /// This is a simple demonstration of zeroMQ sockets using netMQ and protocol-buffer /// This code demonstrates two things /// /// 1. Use of zeroMQ REQUEST-RESPONSE socket using NetMQ library /// 2. Serialization and Deserialization using protocol-buf library /// /// NOTE: Request-Response pattern is strictly sequential /// </summary> /// <param name="args"></param> static void Main(string[] args) { const string serverAddress = "tcp://localhost:5556"; const string serverIdentifier = "Response Server"; using (var context = NetMQContext.Create()) using (var server = context.CreateResponseSocket()) using (var client = context.CreateRequestSocket()) { // Bind the server to a local TCP address // Server is the stable infrastructure and that should BIND server.Bind(serverAddress); // Connect the client to the server. Client is dynamic so it CONNECTs to the address client.Connect(serverAddress); { var clientMsg = new Message(); clientMsg.initMessage("Request Client1", serverIdentifier, "hello", "getting introduced"); Console.WriteLine("Client sending message: {0}", clientMsg.ToString()); // Send a message from the client socket client.SendFrame(clientMsg.Serialize()); } // Receive the message from the server socket { byte[] rawmsg = server.ReceiveFrameBytes(); if (rawmsg != null && rawmsg.Length > 0) { var receivedMsg = Message.Deserialize(rawmsg); Console.WriteLine("Server Received Message From Client: {0}", receivedMsg.ToString()); var serverMsg = new Message(); serverMsg.initMessage(serverIdentifier, receivedMsg.Source, "hello " + receivedMsg.Source, "Server has a new connection!"); Console.WriteLine("Server sending message: {0}", serverMsg.ToString()); // Send a response back from the server server.SendFrame(serverMsg.Serialize()); } } // Now client should receive the message { byte[] rawmsg = client.ReceiveFrameBytes(); if (rawmsg != null && rawmsg.Length > 0) { var receivedMsg = Message.Deserialize(rawmsg); Console.WriteLine("Message From Server: {0}", receivedMsg.ToString()); } } Console.WriteLine("Press any key to exit ..."); Console.ReadKey(); } }
public void Send(string name, params object[] args) { var msg = new Message (name, args); msg.type = "ev"; if (SendHook != null) SendHook (this, msg); ws.Send (msg.ToString ()); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { if (string.IsNullOrEmpty(request.ToString())) { return null; } var credenciales = new EnvoltorioMensaje { FechaInicio = DateTime.Now, Request = request.ToString(), Accion = request.Headers.Action, Ip = OperationContext.Current.ObtnerIp() }; return credenciales; }
protected void Invoke(Message message, bool closeGallery) { Assert.ArgumentNotNull((object)message, "message"); SheerResponse.Eval("scForm.getParentForm().invoke(\"" + StringUtil.EscapeBackslash(message.ToString()) + "\")"); if (!closeGallery) return; SheerResponse.Eval("scForm.getParentForm().Content.closeGallery(scForm.browser.getFrameElement().id)"); }
public void AfterReceiveReply(ref Message reply, object correlationState) { var parametro = (EnvoltorioMensaje) correlationState; if (!reply.IsFault && !string.IsNullOrEmpty(reply.ToString()) && correlationState != null) { parametro.Response = reply.ToString(); } parametro.FechaFin = DateTime.Now; if (_enabled) { CustomLogManager.Instancia.RegistrarTraza(new InformacionLog { Mensaje = "Traza de mensajes Servicio Externo", DatosAdicionales = parametro.InformacionAdicional() }); } //Si la llamada demora mas del tiempo configurado se envia a una tarza especial int tiempoSegundosLimiteLlamada = HelperConfig.GetInt32("Wcf:InspectorCliente:LimiteTiempoLLamada"); if (tiempoSegundosLimiteLlamada <= 0 || tiempoSegundosLimiteLlamada >= parametro.Duracion) { return; } string mensaje = string.Format( "Tiempo Limite por Llamada excedido(max {0} seg) {4}Duracion: {1} seg {4}Accion : {2}{4}[Request]{4}{3}{4}[Response]{4}{5}", tiempoSegundosLimiteLlamada, parametro.Duracion, parametro.Accion, parametro.Request, Environment.NewLine, parametro.Response); CustomLogManager.Instancia.RegistrarAdvertencia( new InformacionLog { Mensaje = mensaje, DatosAdicionales = new Dictionary<string, object> { {"Identificador", parametro.Identificador}, {"Ip", parametro.Ip}, {"Tipo", "Llamada Larga Externa"} } } ); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { Console.WriteLine( "Sending the following request: '{0}'", request.ToString()); LogMessage("BeforeSendRequest", request); return null; }
public void BeforeSendReply(ref Message reply, object correlationState) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine( "{0:HH:mm:ss.ffff}\t{1}\n\t\t{2} ({3} bytes)", DateTime.Now, reply.Headers.RelatesTo, reply.Headers.Action, reply.ToString().Length); }
public void BeforeSendReply(ref Message reply, object correlationState) { var outgoingMessage = reply.ToString(); var signedSoapMessage = Signer.SignMessage(outgoingMessage, "ep-ov", serviceCert); var ms = new MemoryStream(Encoding.UTF8.GetBytes(signedSoapMessage)); var reader = XmlReader.Create(ms); reply = Message.CreateMessage(reader, Int32.MaxValue, reply.Version); }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { if (string.IsNullOrEmpty(request.ToString())) { return null; } var envoltorio = new EnvoltorioMensaje { FechaInicio = DateTime.Now, Request = request.ToString(), Accion = request.Headers.Action, Ip = OperationContext.Current.ObtnerIp() }; return envoltorio; }
/// <summary> /// Enables inspection or modification of a message after a reply message is received but prior to passing it back to the client application. /// </summary> /// <param name="reply">The message to be transformed into types and handed back to the client application.</param> /// <param name="correlationState">Correlation state data.</param> public void AfterReceiveReply(ref Message reply, object correlationState) { if (reply == null) return; if (IntegrationServiceCallScope.Current != null) IntegrationServiceCallScope.Current.Response = reply.ToString(); }
public void AfterReceiveReply(ref Message reply, object correlationState) { #if DEBUG var message = reply.ToString(); Console.WriteLine("Client got message:" + message); #endif ClientApplicationContext.Current = reply.GetApplicationContext<ClientApplicationContext>(); try { var setting = WcfSettingManager.CurrentClientSetting((correlationState as Type)); var logSetting = setting.WcfLogSetting; if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled) { var direct = logSetting.MessageInfoSetting.MessageDirection; if (direct == MessageDirection.Both || direct == MessageDirection.Receive) { var log = WcfLogProvider.GetClientMessageInfo( (correlationState as Type).FullName, ClientApplicationContext.Current.RequestIdentity, "ClientMessageInspector.AfterReceiveReply", MessageDirection.Receive, reply.ToString()); WcfServiceLocator.GetLogService().LogWithoutException(log); } } var securitySetting = setting.WcfSecuritySetting; if (securitySetting.PasswordCheck.Enable) { if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Reply) { if (ClientApplicationContext.Current.Password != securitySetting.PasswordCheck.Password) throw new WcfSecurityException("PasswordCheck failed in reply!"); } } } catch (Exception ex) { LocalLogService.Log(ex.ToString()); if (ex is WcfSecurityException) throw; } }
/// <summary> /// Enables inspection or modification of a message before a request message is sent to a service. /// </summary> /// <param name="request">The message to be sent to the service.</param> /// <param name="channel">The WCF client object channel.</param> /// <returns>The object that is returned as the correlationState argument of the AfterReceiveReply method. This is null if no correlation state is used.</returns> public object BeforeSendRequest(ref Message request, IClientChannel channel) { if (request == null) return null; if (IntegrationServiceCallScope.Current != null) IntegrationServiceCallScope.Current.Request = request.ToString(); return null; }
public void BeforeSendReply(ref Message reply, object correlationState) { var parametro = (EnvoltorioMensaje)correlationState; parametro.Response = reply.ToString(); parametro.FechaFin = DateTime.Now; //Si demora mas de un tiempo X deberia enviar una notificacion CustomLogManager.Instancia.RegistrarTraza(parametro.ToString()); }
internal IncomingMessageAgent(Message.Categories cat, IMessageCenter mc, ActivationDirectory ad, OrleansTaskScheduler sched, Dispatcher dispatcher) : base(cat.ToString()) { category = cat; messageCenter = mc; directory = ad; scheduler = sched; this.dispatcher = dispatcher; OnFault = FaultBehavior.RestartOnFault; }
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { #if DEBUG var message = request.ToString(); Console.WriteLine("Server got message:" + message); #endif ServerApplicationContext.Current = request.GetApplicationContext<ServerApplicationContext>(); try { var setting = WcfSettingManager.CurrentServerSetting(OperationContext.Current.GetCurrentServiceDescription().ServiceType); var logSetting = setting.WcfLogSetting; if (logSetting.Enabled && logSetting.MessageInfoSetting.Enabled) { var direct = logSetting.MessageInfoSetting.MessageDirection; if (direct == MessageDirection.Both || direct == MessageDirection.Receive) { var log = WcfLogProvider.GetServerMessageInfo( "ServerMessageInspector.AfterReceiveRequest", MessageDirection.Receive, request.ToString()); WcfServiceLocator.GetLogService().LogWithoutException(log); } } var securitySetting = setting.WcfSecuritySetting; if (securitySetting.PasswordCheck.Enable) { if (securitySetting.PasswordCheck.Direction == OperationDirection.Both || securitySetting.PasswordCheck.Direction == OperationDirection.Request) { if (ServerApplicationContext.Current.Password != securitySetting.PasswordCheck.Password) throw new WcfSecurityException("PasswordCheck failed in request!"); } } } catch (Exception ex) { LocalLogService.Log(ex.ToString()); if (ex is WcfSecurityException) throw; } return null; }
public static string GetMessageBody(Message message) { var messageBody = message.ToString(); var atts = typeof(Message).GetField( messageBody, BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public) .GetCustomAttributes(true); foreach (var att in atts.OfType<MessageParametersAttribute>()) return att.Body; return messageBody; }
public static void Report(Message msg) { ((ToolStripStatusLabel) registry[Id.STATUSBAR]).Text = msg.ToString(); Bitmap icon = null; if (msg.Result == Result.OK) { icon = Controller.AsmInfo.GetBitmap("status-ok.png"); } else if (msg.Result == Result.Fail) { icon = Controller.AsmInfo.GetBitmap("status-fail.png"); } ((ToolStripStatusLabel) registry[Id.STATUSBAR]).Image = icon; }
private void MessageManagerOnNewMessage(object _sender, Message _message) { if (_message is XLangMessage) { m_messages.Add((XLangMessage)_message); } else { Debug.WriteLine(_message.ToString()); } }
public Request Request(string name, params object[] args) { var msg = new Message (name, args); msg.type = "fn"; if (SendHook != null) SendHook (this, msg); var req = new Request (this, msg); requests.Add (msg.id, req); ws.Send (msg.ToString ()); return req; }
public void ItShouldShowElpsedSeconds_GivenLessThanOneMinuteHasPassed() { //g var tenSecondsAgo = DateTime.Now.AddSeconds(-10); var message = new Message("Alice", "I love the weather today",tenSecondsAgo); //w var text = message.ToString(); //t text.Should().Be("I love the weather today (10 seconds ago)"); }
public object AfterReceiveRequest( ref Message request, IClientChannel channel, InstanceContext instanceContext) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine( "{0:HH:mm:ss.ffff}\t{1}\n\t\t{2} ({3} bytes)\n\t\t{4}", DateTime.Now, request.Headers.MessageId, request.Headers.Action, request.ToString().Length, request.Headers.To); return null; }
void Fail(object message = null, int conditionIndex = 0) { // break a macro MacroState macroState = Far.Api.MacroState; if (macroState == MacroState.Executing || macroState == MacroState.ExecutingCommon) { Far.Api.UI.Break(); } // get the message if (message == null) { ScriptBlock messageScript = Cast <ScriptBlock> .From(Message); if (messageScript != null) { try { Message = messageScript.InvokeReturnAsIs(); } catch (RuntimeException ex) { Message = "Error in the message script: " + ex.Message; Title = null; } } } else { Message = message; } // body //! use "\n" as the separator, not "\r": PositionMessage starts with "\n". string body = Message == null ? "Assertion failed" : Message.ToString(); if (IsError) { if (conditionIndex > 0) { body = string.Concat(body, (body.Length > 0 ? "\n" : string.Empty), "Condition #", conditionIndex + 1); } //! Trim() for PowerShell 2.0 body = string.Concat(body, (body.Length > 0 ? "\n" : string.Empty), MyInvocation.PositionMessage.Trim()); } // buttons string[] buttons; if (!IsError) { buttons = new string[] { BtnStop, BtnThrow } } ; else if (string.IsNullOrEmpty(MyInvocation.ScriptName)) { buttons = new string[] { BtnStop, BtnThrow, BtnDebug } } ; else { buttons = new string[] { BtnStop, BtnEdit, BtnDebug, BtnThrow } }; // prompt int result = Far.Api.Message( body, Title ?? MyName, IsError ? (MessageOptions.Warning | MessageOptions.LeftAligned) : MessageOptions.None, buttons); switch (result < 0 ? BtnStop : buttons[result]) { case BtnStop: { throw new PipelineStoppedException(); } case BtnThrow: { throw new PSInvalidOperationException(body); } case BtnDebug: { A.InvokeCode("Set-PSBreakpoint -Variable daf01ff6-f004-43bd-b6bf-cf481e9333d3 -Mode Read"); SessionState.PSVariable.Set("daf01ff6-f004-43bd-b6bf-cf481e9333d3", null); GetVariableValue("daf01ff6-f004-43bd-b6bf-cf481e9333d3"); return; } case BtnEdit: { IEditor editor = Far.Api.CreateEditor(); editor.FileName = MyInvocation.ScriptName; editor.GoToLine(MyInvocation.ScriptLineNumber - 1); editor.Open(); throw new PipelineStoppedException(); } } } const string BtnStop = "&Stop", BtnThrow = "&Throw", BtnDebug = "&Debug", BtnEdit = "&Edit"; }
public void AfterReceiveReply(ref Message reply, object correlationState) { Debug.WriteLine(reply.ToString()); }
public void BeforeSendReply(ref Message reply, object correlationState) { bool acceptGZIP = false; if (correlationState != null) { System.Net.WebHeaderCollection headers = correlationState as System.Net.WebHeaderCollection; string acceptedEncoding = headers["Accept-Encoding"]; acceptGZIP = (!string.IsNullOrEmpty(acceptedEncoding) && Array.IndexOf(acceptedEncoding.Split(','), "gzip") >= 0); } if (GZipEncoderHelper.GZIPEncodingActive && acceptGZIP && ProcessorUsage.GetCurrentValue < 80.0F && reply.ToString().Length > GZipEncoderHelper.MinimumSizeForGZIPEncoding) { HttpResponseMessageProperty prop; if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name)) { prop = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name]; } else { prop = new HttpResponseMessageProperty(); reply.Properties.Add(HttpResponseMessageProperty.Name, prop); } // YN: Sinds 2014-04-10 (waarschijnlijk eerder maar toen hadden we geen nieuwe build) // Is het verplicht deze code altijd op te nemen! Voorheen ALLEEN als httpresponse properties niet bestond System.ServiceModel.Web.WebOperationContext.Current.OutgoingResponse.Headers["Content-Encoding"] = "gzip"; // When adding this header the body content will be encoded with gzip in the GZipMessageEncoderFactory class prop.Headers[System.Net.HttpResponseHeader.ContentEncoding] = "gzip"; } }
public void AfterReceiveReply(ref Message reply, object correlationState) { txtResponse.Text = reply.ToString(); }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { txtRequest.Text = request.ToString(); return(request); }
public override string ToString() { return(Name + "; " + Message.ToString()); }
internal Message SignBodyAndAddressingHeaders(Message requestMessage, ref string outboundXml) { XmlReader reader = XmlReader.Create(new StringReader(requestMessage.ToString())); XmlDocument xdoc = new XmlDocument(); xdoc.Load(reader); XmlElement root = xdoc.DocumentElement; string soapNs = xdoc.DocumentElement.NamespaceURI; XmlNamespaceManager nm = new XmlNamespaceManager(reader.NameTable); nm.AddNamespace("s", soapNs); nm.AddNamespace("a", "http://www.w3.org/2005/08/addressing"); nm.AddNamespace("h", UserNamespace); // Create references List <string> references = new List <string>(); // Get the body element and assign ID XmlElement bodyElement = (XmlElement)root.SelectSingleNode("//s:Body", nm); string bodyId = "body-" + Guid.NewGuid().ToString(); bodyElement.SetAttribute("xml:id", bodyId); references.Add(bodyId); // Get the user element and assign ID XmlElement userElement = (XmlElement)root.SelectSingleNode("//s:Header/h:user", nm); string userId = "user-" + Guid.NewGuid().ToString(); userElement.SetAttribute("xml:id", userId); references.Add(userId); // Get the timestamp element and assign ID XmlElement productElement = (XmlElement)root.SelectSingleNode("//s:Header/h:timestamp", nm); string timestampId = "timestamp-" + Guid.NewGuid().ToString(); productElement.SetAttribute("xml:id", timestampId); references.Add(timestampId); if (references.Count > 0) { // Create signature XmlElement signatureElement = Sign(root, signingCertificate, references); // Get the SOAP header element XmlElement headerSignatureElement = (XmlElement)root.SelectSingleNode("//s:Header/h:signature", nm); // Import and append the created signature XmlNode signatureNode = xdoc.ImportNode(signatureElement, true); headerSignatureElement.AppendChild(signatureNode); } // Get serialized text (Not necessary, just for the hell of it...) Stream tempStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(root.OuterXml)); StreamReader sr = new StreamReader(tempStream); outboundXml = sr.ReadToEnd(); //Pass certificate for validation purposes (fw 4.6.2 throws a fault when public key not passed in) bool isValid = VerifyXML(outboundXml, signingCertificate); Stream memoryStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(root.OuterXml)); XmlDictionaryReader dictionaryReader = XmlDictionaryReader.CreateTextReader(memoryStream, new XmlDictionaryReaderQuotas()); Message newMessage = Message.CreateMessage(dictionaryReader, int.MaxValue, requestMessage.Version); return(newMessage); }
public void SimpleSyncProducerSends2MessagesAndConsumerConnectorGetsThemBack() { var prodConfig = this.SyncProducerConfig1; var consumerConfig = this.ZooKeeperBasedConsumerConfig; var consConf = this.ConsumerConfig1; // first producing string payload1 = "kafka 1."; byte[] payloadData1 = Encoding.UTF8.GetBytes(payload1); var msg1 = new Message(payloadData1); string payload2 = "kafka 2."; byte[] payloadData2 = Encoding.UTF8.GetBytes(payload2); var msg2 = new Message(payloadData2); var producerRequest = new ProducerRequest(CurrentTestTopic, 0, new List <Message> { msg1, msg2 }); using (var producer = new SyncProducer(prodConfig)) { producer.Send(producerRequest); } var consumer = new Consumer(consConf); long offset = 0; var result = consumer.Fetch( new FetchRequest(CurrentTestTopic, 0, offset, 400)); foreach (var resultItem in result) { offset += resultItem.Offset; } // now consuming var resultMessages = new List <Message>(); using (IConsumerConnector consumerConnector = new ZookeeperConsumerConnector(consumerConfig, true)) { var topicCount = new Dictionary <string, int> { { CurrentTestTopic, 1 } }; var messages = consumerConnector.CreateMessageStreams(topicCount); var sets = messages[CurrentTestTopic]; try { foreach (var set in sets) { foreach (var message in set) { resultMessages.Add(message); } } } catch (ConsumerTimeoutException) { // do nothing, this is expected } } Assert.AreEqual(2, resultMessages.Count); Assert.AreEqual(msg1.ToString(), resultMessages[0].ToString()); Assert.AreEqual(msg2.ToString(), resultMessages[1].ToString()); }
public void FromApp(Message message, SessionID sessionID) { try { string msgType = message.Header.GetField(QuickFix.Fields.Tags.MsgType); // log_.OnEvent("Got message " + msgType); // System.Console.WriteLine("===got message " + msgType); Crack(message, sessionID); } catch (QuickFix.UnsupportedMessageType) { throw; } catch (System.Exception e) { log_.OnEvent("FromApp: " + e.ToString() + " while processing msg (" + message.ToString() + ")"); } }
public object BeforeSendRequest(ref Message request, IClientChannel channel) { Debug.WriteLine(request.ToString()); return(null); }
public static string ShowMessage(this Message message) { return(message.ToString().Replace("_", " ")); }
public bool ContainsHighlight() { return(ContainsHighlight(Message.ToString())); }
private string GetMessageInformation(Message message) => $"publisher confirms: {RabbitMqConfig.PublisherConfirms}, " + $"{message?.ToString() ?? "- no message information available -"}";
public void SendMessageControl(MessageState state, IMessage sourceMessage, IMessageQueueSetting messageQueueSetting, Exception exception, StateResponse stateResponse) { if (_queueClientOption.DisableMessageControl) { return; } try { using (var connection = _queueClient.Factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(_queueClientOption.MessageControlExchange, "topic", true); var messageControl = new MessageControl() { MessageId = sourceMessage.MessageID, CorrelationId = sourceMessage.CorrelationID, MessageType = sourceMessage.Type, State = state, Exchange = messageQueueSetting.Exchange, Queue = messageQueueSetting.Queue, RoutingKey = new [] { messageQueueSetting.EventType }, }; var message = new Message() { CreatedSource = _queueClientOption.SystemIdentifier }; message.SetPayload(messageControl); if (sourceMessage.Keys != null && sourceMessage.Keys.Count > 0) { foreach (var(key, value) in sourceMessage.Keys) { message.Keys.Add(key, value); } } if (stateResponse != null) { messageControl.StateResponse = stateResponse; } if (exception != null) { messageControl.StateResponse.IsSuccess = false; messageControl.StateResponse.IsRecoverable = (state == MessageState.Retry); messageControl.StateResponse.StateData.Add(StateData.GetExceptionStateData(exception)); } var properties = channel.CreateBasicProperties(); properties.Persistent = true; var body = Encoding.UTF8.GetBytes(message.ToString()); channel.BasicPublish(_queueClientOption.MessageControlExchange, "", properties, body); } } catch (Exception ex2) { _logger.LogError(ex2, "Unable to write message messageControl."); } }
public void ConsumerConnectorConsumesTwoDifferentTopics() { var prodConfig = this.SyncProducerConfig1; var consumerConfig = this.ZooKeeperBasedConsumerConfig; string topic1 = CurrentTestTopic + "1"; string topic2 = CurrentTestTopic + "2"; // first producing string payload1 = "kafka 1."; byte[] payloadData1 = Encoding.UTF8.GetBytes(payload1); var msg1 = new Message(payloadData1); string payload2 = "kafka 2."; byte[] payloadData2 = Encoding.UTF8.GetBytes(payload2); var msg2 = new Message(payloadData2); using (var producer = new SyncProducer(prodConfig)) { var producerRequest1 = new ProducerRequest(topic1, 0, new List <Message> { msg1 }); producer.Send(producerRequest1); var producerRequest2 = new ProducerRequest(topic2, 0, new List <Message> { msg2 }); producer.Send(producerRequest2); } // now consuming var resultMessages1 = new List <Message>(); var resultMessages2 = new List <Message>(); using (IConsumerConnector consumerConnector = new ZookeeperConsumerConnector(consumerConfig, true)) { var topicCount = new Dictionary <string, int> { { topic1, 1 }, { topic2, 1 } }; var messages = consumerConnector.CreateMessageStreams(topicCount); Assert.IsTrue(messages.ContainsKey(topic1)); Assert.IsTrue(messages.ContainsKey(topic2)); var sets1 = messages[topic1]; try { foreach (var set in sets1) { foreach (var message in set) { resultMessages1.Add(message); } } } catch (ConsumerTimeoutException) { // do nothing, this is expected } var sets2 = messages[topic2]; try { foreach (var set in sets2) { foreach (var message in set) { resultMessages2.Add(message); } } } catch (ConsumerTimeoutException) { // do nothing, this is expected } } Assert.AreEqual(1, resultMessages1.Count); Assert.AreEqual(msg1.ToString(), resultMessages1[0].ToString()); Assert.AreEqual(1, resultMessages2.Count); Assert.AreEqual(msg2.ToString(), resultMessages2[0].ToString()); }
public void FromAdmin(Message message, SessionID sessionID) { System.Diagnostics.Debug.WriteLine("Received FIX admin message: " + message.ToString()); }
private static async void Bot_OnMessage(object sender, MessageEventArgs e) { Message msg = e.Message; //Will give you chat id for some need /*if (msg != null) * { * Console.WriteLine(msg.Chat.Id); * }*/ if (msg == null) { return; } else if (msg.Type == Telegram.Bot.Types.Enums.MessageType.Text) { Console.WriteLine(msg.ToString()); try { //Text question-answer logic starts here, use only lower letter in comparison string s = msg.Text.ToLower(); Console.WriteLine(s); if (s == "/start") { await b.SendTextMessageAsync(msg.Chat.Id, "I'm ready when you're"); } else if (s.Contains("hello") || s.Contains("hi")) { await b.SendTextMessageAsync(msg.Chat.Id, "Hello to you, " + msg.From.FirstName + "!"); } else { await b.SendTextMessageAsync(msg.Chat.Id, "default bot response"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } else if (msg.Type == Telegram.Bot.Types.Enums.MessageType.Photo) { //await b.SendTextMessageAsync(msg.Chat.Id, "Processing request with Python..."); try { var downphoto = b.GetFileAsync(e.Message.Photo[e.Message.Photo.Count() - 1].FileId); var download_url = @"https://api.telegram.org/file/botYOURTELEGRAMAPIKEY/" + downphoto.Result.FilePath; using (WebClient client = new WebClient()) { client.DownloadFile(new Uri(download_url), @"C:\MYIMG.jpg"); } string faces = Option1_ExecProcess(); var FileUrl = @"C:\\OUTIMG.jpg"; if (faces.Length > 0) { using (var stream = System.IO.File.Open(FileUrl, FileMode.Open)) { InputOnlineFile fts = new InputOnlineFile(stream, FileUrl.Split('\\').Last()); var test = await b.SendPhotoAsync(msg.Chat.Id, fts, faces); } } else { await b.SendTextMessageAsync(msg.Chat.Id, "\U0001F648 facial detection error" + faces); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } }
public void Message_ToString_Invoke_ReturnsExpected(int msg, string expected, string additionalMsg = null) { Message message = Message.Create((IntPtr)1, msg, (IntPtr)2, (IntPtr)3); message.Result = (IntPtr)4; Assert.Equal("msg=0x" + Convert.ToString(msg, 16) + expected + " hwnd=0x1 wparam=0x2 lparam=0x3" + additionalMsg + " result=0x4", message.ToString()); }
/// <summary> /// Handles an incoming (proxied) message by rerouting it immediately and unconditionally, /// after some header massaging. /// </summary> /// <param name="msg"></param> /// <param name="receivedOnSocket"></param> protected override void HandleMessage(Message msg, Socket receivedOnSocket) { // Don't process messages that have already timed out if (msg.IsExpired) { msg.DropExpiredMessage(MessagingStatisticsGroup.Phase.Receive); return; } if (Message.WriteMessagingTraces) { msg.AddTimestamp(Message.LifecycleTag.ReceiveIncoming); } gatewayTrafficCounter.Increment(); // Are we overloaded? if ((MessageCenter.Metrics != null) && MessageCenter.Metrics.IsOverloaded) { MessagingStatisticsGroup.OnRejectedMessage(msg); Message rejection = msg.CreateRejectionResponse(Message.RejectionTypes.GatewayTooBusy, "Shedding load"); MessageCenter.TryDeliverToProxy(rejection); if (Log.IsVerbose) { Log.Verbose("Rejecting a request due to overloading: {0}", msg.ToString()); } loadSheddingCounter.Increment(); return; } gateway.RecordSendingProxiedGrain(msg.SendingGrain, receivedOnSocket); SiloAddress targetAddress = gateway.TryToReroute(msg); msg.SendingSilo = MessageCenter.MyAddress; if (targetAddress == null) { // reroute via Dispatcher msg.RemoveHeader(Message.Header.TARGET_SILO); msg.RemoveHeader(Message.Header.TARGET_ACTIVATION); if (msg.TargetGrain.IsSystemTarget) { msg.TargetSilo = MessageCenter.MyAddress; msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, MessageCenter.MyAddress); } if (Message.WriteMessagingTraces) { msg.AddTimestamp(Message.LifecycleTag.RerouteIncoming); } MessagingStatisticsGroup.OnMessageReRoute(msg); MessageCenter.RerouteMessage(msg); } else { // send directly msg.TargetSilo = targetAddress; MessageCenter.SendMessage(msg); } }
public void BeforeSendReply(ref Message reply, object correlationState) { reply = TraceMessage(reply.CreateBufferedCopy(int.MaxValue)); LogFileWriter.LogResponseBody(reply?.ToString()); }
public void AfterReceiveReply(ref Message message, object state) { SoapResponse = message.ToString(); //File.WriteAllText(string.Format("response_{0}.xml", DateTime.Now.ToString("dd-MM-yyyy HH_mm_ss_ffff")), SoapResponse); }
private void BuildProjectInformation(Message msg) { try { _projectInformation = msg.Payload.ToObject <CommonProjectContext>(); } catch (Exception ex) { Logger.Log($"{Resources.InvalidProjectInformationMessage}{Environment.NewLine}{msg?.ToString()}"); throw ex; } }
public TType MessageAs <TType>() { return(Message.ToString().JsonAs <TType>()); }
private void OnMessageSerializationFailure(Message msg, Exception exc) { // we only get here if we failed to serialize the msg (or any other catastrophic failure). // Request msg fails to serialize on the sending silo, so we just enqueue a rejection msg. // Response msg fails to serialize on the responding silo, so we try to send an error response back. Log.Warn(ErrorCode.Messaging_Gateway_SerializationError, String.Format("Unexpected error serializing message {0} on the gateway", msg.ToString()), exc); msg.ReleaseBodyAndHeaderBuffers(); MessagingStatisticsGroup.OnFailedSentMessage(msg); MessagingStatisticsGroup.OnDroppedSentMessage(msg); }
private void Can_Parse_ISOMessage() { //Arrange string ISO8583Message = "0200B2200000001000000000000000800000201" + "234000000010000110722183012345606A5DFGR021ABCDEFGHIJ 1234567890"; DataElementsDefinition dataElementsDefinition = new DataDefinitionDictionary(); ISO8583Parser parser = new ISO8583Parser(dataElementsDefinition); //Act Message message = parser.Parse(ISO8583Message); //Assert //MTI Assert.Equal(Version.ISO8583_1987, message.MessageTypeIdentifier.Version); Assert.Equal(MessageClass.Financial, message.MessageTypeIdentifier.MessageClass); Assert.Equal(MessageSubClass.Request, message.MessageTypeIdentifier.MessageSubClass); Assert.Equal("0200", message.MessageTypeIdentifier.ToString()); //BitMap Assert.Contains(3, message.BitMaps.GetPresentDataElements()); Assert.Contains(4, message.BitMaps.GetPresentDataElements()); Assert.Contains(7, message.BitMaps.GetPresentDataElements()); Assert.Contains(11, message.BitMaps.GetPresentDataElements()); Assert.Contains(44, message.BitMaps.GetPresentDataElements()); Assert.Contains(105, message.BitMaps.GetPresentDataElements()); Assert.Equal("B220000000100000", message.BitMaps[1].ToString()); Assert.Equal("0000000000800000", message.BitMaps[2].ToString()); Assert.Equal("B2200000001000000000000000800000", message.BitMaps.ToString()); //DEs Assert.Equal("201234", message.DataElements[3].GetFieldData()); Assert.Equal("20", message.DataElements[3][1].GetFieldData()); Assert.Equal("12", message.DataElements[3][2].GetFieldData()); Assert.Equal("34", message.DataElements[3][3].GetFieldData()); Assert.Equal("000000010000", message.DataElements[4].GetFieldData()); Assert.Equal("1107221830", message.DataElements[7].GetFieldData()); Assert.Equal("123456", message.DataElements[11].GetFieldData()); Assert.Equal("A5DFGR", message.DataElements[44].GetFieldData()); Assert.Equal("06A5DFGR", message.DataElements[44].ToString()); Assert.Equal("ABCDEFGHIJ 1234567890", message.DataElements[105].GetFieldData()); //Message Assert.Equal("0200B2200000001000000000000000800000201" + "234000000010000110722183012345606A5DFGR021ABCDEFGHIJ 1234567890", message.ToString()); }
private List <Message> ReplicateMessages(Message message) { long originTransId; switch (message) { case CandleMessage candleMsg: originTransId = candleMsg.OriginalTransactionId; break; case ExecutionMessage execMsg: originTransId = execMsg.OriginalTransactionId; break; case NewsMessage newsMsg: originTransId = newsMsg.OriginalTransactionId; break; default: throw new ArgumentOutOfRangeException(nameof(message), message?.ToString()); } lock (_sync) { if (!_subscribersById.TryGetValue(originTransId, out var info)) { return(null); } if (info.Message.TransactionId == originTransId && info.Subscriptions.Count > 1) { var clones = new List <Message>(info.Subscriptions.Count - 1); foreach (var subscription in info.Subscriptions) { if (subscription.TransactionId == info.Message.TransactionId) { continue; } var clone = message.Clone(); switch (clone) { case CandleMessage candleMsg: candleMsg.OriginalTransactionId = subscription.TransactionId; break; case ExecutionMessage execMsg: execMsg.OriginalTransactionId = subscription.TransactionId; break; case NewsMessage newsMsg: newsMsg.OriginalTransactionId = subscription.TransactionId; break; } clones.Add(clone); } return(clones); } } return(null); }
public void ToAdmin(Message message, SessionID sessionID) { Console.WriteLine("ToAdmin - " + sessionID.ToString() + " - " + message.ToString()); }
public object MessageAs(Type type) { return(Message.ToString().JsonAs(type)); }
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext) { // Declare variables string Service = ""; string UserToken = null; string ServiceCall = ""; string Body = ""; // Make a copy of the message for viewing / data manipulation MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue); Message msgCopy = buffer.CreateMessage(); // A message can only be consumed once, so make sure you return a copy request = buffer.CreateMessage(); // Get the XML content var strMessage = msgCopy.ToString(); // Get the SOAP XML body content XmlDictionaryReader xrdr = msgCopy.GetReaderAtBodyContents(); string bodyData = xrdr.ReadOuterXml(); // Replace the body placeholder with the actual SOAP body. strMessage = strMessage.Replace("... stream ...", bodyData); // Load the SOAP XML string into a new XML Document var doc = new XmlDocument(); doc.LoadXml(strMessage); foreach (XmlNode node in doc.DocumentElement.ChildNodes) { if (node.Name == "s:Header") { if (node.FirstChild.Name != "TokenHeader") { Service = node.FirstChild.InnerText; ServiceCall = node.LastChild.InnerText; } else { UserToken = node.FirstChild.InnerText; Service = node.ChildNodes.Item(1).InnerText; ServiceCall = node.LastChild.InnerText; } } if (node.Name == "s:Body") { Body = node.InnerXml; } } // The ExemptServiceCalls Class contains a list of services that we to NOT want to keep a record of. // The properties of this class are converted into a list. var serviceList = ExemptServiceCalls.GetExemptServices(); // Query the list to see if it contains an exempt service call var containsExemptService = serviceList.Contains(ServiceCall); // If the class does not contain en exempt service call, enter it into the database if (containsExemptService == false) { // Insert Into Activity Log table BLL.ActivityLog.InsertIntoActivityLog(Service, ServiceCall, Body, strMessage, UserToken); } return(null); }