Пример #1
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            MessageBuffer requstBuffer = reply.CreateBufferedCopy(int.MaxValue);
            Message       msg          = requstBuffer.CreateMessage();

            reply = requstBuffer.CreateMessage();
        }
Пример #2
0
        String MessageString(ref Message m)
        {
            // copy the message into a working buffer.
            MessageBuffer mb = m.CreateBufferedCopy(int.MaxValue);

            // re-create the original message, because "copy" changes its state.
            m = mb.CreateMessage();

            Stream    s  = new MemoryStream();
            XmlWriter xw = XmlWriter.Create(s);

            mb.CreateMessage().WriteMessage(xw);
            xw.Flush();
            s.Position = 0;

            byte[] bXml = new byte[s.Length];
            s.Read(bXml, 0, (int)s.Length);

            // sometimes bXML[] starts with a BOM
            if (bXml[0] != (byte)'<')
            {
                return(Encoding.UTF8.GetString(bXml, 3, bXml.Length - 3));
            }
            return(Encoding.UTF8.GetString(bXml, 0, bXml.Length));
        }
        public string SelectOperation(ref System.ServiceModel.Channels.Message message)
        {
            MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);

            message = buffer.CreateMessage();

            var copy = buffer.CreateMessage();

            XmlDictionaryReader bodyReader  = copy.GetReaderAtBodyContents();
            XmlQualifiedName    lookupQName = new XmlQualifiedName(bodyReader.LocalName, bodyReader.NamespaceURI);

            if (dispatchDictionary.ContainsKey(lookupQName))
            {
                // Mark Soap Headers action etc as understood
                //int actionHeaderIdx = message.Headers.FindHeader("Action", "http://www.w3.org/2005/08/addressing");
                //int actionHeaderIdx2 = message.Headers.FindHeader("Action", "*");
                //message.Headers.UnderstoodHeaders.Add((MessageHeaderInfo)message.Headers[actionHeaderIdx]);
                //message.Headers.UnderstoodHeaders.Add((MessageHeaderInfo)message.Headers.FindHeader(Headers[0]);

                return(dispatchDictionary[lookupQName]);
            }
            else
            {
                return(null);
            }
        }
Пример #4
0
        /// <summary>
        /// BeforeSendReply
        /// </summary>
        /// <param name="reply"></param>
        /// <param name="correlationState"></param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            // create message copy
            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
            // fresh copy to extract response codee from
            Message msgCopy = buffer.CreateMessage();
            // fresh unread copy to return
            Message msgReturn = buffer.CreateMessage();

            // read body
            string msgBody = ReadMsgBody(msgCopy);

            // sanity check for empty bidy
            if (string.IsNullOrWhiteSpace(msgBody))
            {
                return;
            }
            // extract response code if it exists, search for "HttpResponseCodeTagName" above
            var httpResponseCode = ExtractMessageResponseCode(msgBody);

            if (!string.IsNullOrWhiteSpace(httpResponseCode))
            {
                // set response code in return msg
                SetStatusCode(httpResponseCode, msgReturn);
            }
            // set reply to copy
            reply = msgReturn;
        }
Пример #5
0
        /// <summary>
        /// Throws an AdsException if the response was a SOAP fault.
        /// </summary>
        /// <param name="reply">The response Message</param>
        /// <param name="correlationState">The correlation state returned by BeforeSendRequest</param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.IsFault)
            {
                StringBuilder xmlStringBuilder = new StringBuilder();
                using (XmlWriter xmlWriter = XmlWriter.Create(xmlStringBuilder, xmlWriterSettings))
                    using (MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue)) {
                        // Message can only be read once, so replace it with a copy.
                        reply = buffer.CreateMessage();
                        buffer.CreateMessage().WriteBody(xmlWriter);
                    }

                // Try locating the ApiExceptionFault node and deserializing it. Make sure to ignore
                // the namespace and look only for the local name.
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xmlStringBuilder.ToString());
                XmlElement faultNode = (XmlElement)xDoc.SelectSingleNode(FAULT_ELEMENT_XPATH);

                if (faultNode != null)
                {
                    // Deserialize the correct exception type and raise it.
                    string faultNodeNamespaceUri = faultNode.NamespaceURI;
                    string faultNodeContents     = faultNode.OuterXml;
                    object apiError = SerializationUtilities.DeserializeFromXmlTextCustomRootNs(
                        faultNodeContents,
                        ErrorType,
                        faultNodeNamespaceUri,
                        FAULT_ELEMENT_NAME);
                    throw (TException)Activator.CreateInstance(
                              typeof(TException),
                              new object[] { apiError });
                }
            }
        }
Пример #6
0
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            bool isVersionExist = false;

            for (int i = 0; i < request.Headers.Count; i++)
            {
                var headerInfo = request.Headers[i];
                if (headerInfo.Name == "Version" && headerInfo.Namespace == "http://WcfPoc.wcfRouting.int/Increment1")
                {
                    isVersionExist = true;
                    break;
                }
            }

            //if (!isVersionExist)
            //{
            //    throw new Exception("SOAP Message don't have VERSION header!");
            //}

            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();
            Console.WriteLine("Message Received:\n{0}", buffer.CreateMessage().ToString());

            return(null);
        }
Пример #7
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.DataLayer.FaultMessageInspector: incoming AfterReceiveReply "));
            if (reply.IsFault)
            {
                MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
                reply = buffer.CreateMessage();
                Message m = buffer.CreateMessage();
                var     bodyContententsAsString = string.Empty;

                using (XmlDictionaryReader reader = m.GetReaderAtBodyContents())
                {
                    XmlDocument document = new XmlDocument();
                    document.Load(reader);

                    using (var stringWriter = new StringWriter())
                    {
                        using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                        {
                            document.WriteTo(xmlTextWriter);
                            xmlTextWriter.Flush();
                            bodyContententsAsString = stringWriter.GetStringBuilder().ToString();
                        }
                    }
                }

                LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.DataLayer.FaultMessageInspector: ReplyMessage: {0}", bodyContententsAsString));
            }
            LogManager.LogTrace(string.Format("SE.GOV.MM.Integration.DeliveryMailbox.DataLayer.FaultMessageInspector: leaving AfterReceiveReply"));
        }
Пример #8
0
        String MessageString(ref Message m)
        {
            MessageBuffer mb = m.CreateBufferedCopy(int.MaxValue);

            m = mb.CreateMessage();

            Stream    s  = new MemoryStream();
            XmlWriter xw = XmlWriter.Create(s);

            mb.CreateMessage().WriteMessage(xw);
            xw.Flush();
            s.Position = 0;

            byte[] bXML = new byte[s.Length];
            s.Read(bXML, 0, (int)s.Length);

            if (bXML[0] != (byte)'<')
            {
                return(Encoding.UTF8.GetString(bXML, 3, bXML.Length - 3));
            }
            else
            {
                return(Encoding.UTF8.GetString(bXML, 0, bXML.Length));
            }
        }
Пример #9
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (!reply.IsFault || !_enabled)
            {
                return;
            }

            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
            Message       copy   = buffer.CreateMessage();

            reply = buffer.CreateMessage();

            ErrorServicioRespuesta exception = RecuperarFaultException(copy);

            if (exception == null)
            {
                return;
            }

            switch (exception.Tipo)
            {
            case TipoErrorServicio.ErrorValidacion:
                throw new ExcepcionValidacion(exception.Mensaje);

            case TipoErrorServicio.ErrorNegocio:
                throw new ExcepcionReglaNegocio(exception.Codigo, exception.Mensaje);

            default:
                throw new ExcepcionServicio(
                          "La respuesta no pudo ser atendida por el servicio. Por favor intente más tarde.");
            }
        }
Пример #10
0
        public Message CompressMessage(Message sourceMessage)
        {
            byte[]        buffer;
            MessageBuffer messageBuffer = sourceMessage.CreateBufferedCopy(int.MaxValue);

            sourceMessage.Close();
            sourceMessage = messageBuffer.CreateMessage();
            using (XmlDictionaryReader reader1 = sourceMessage.GetReaderAtBodyContents())
            {
                buffer = Encoding.UTF8.GetBytes(reader1.ReadOuterXml());
            }
            if (buffer.Length < this.MinMessageSize)
            {
                sourceMessage.Close();
                return(messageBuffer.CreateMessage());
            }
            byte[]        compressedData    = DataCompressor.Compress(buffer);
            string        copressedBody     = CreateCompressedBody(compressedData);
            XmlTextReader reader            = new XmlTextReader(new StringReader(copressedBody), new NameTable());
            Message       compressedMessage = Message.CreateMessage(sourceMessage.Version, null, (XmlReader)reader);

            compressedMessage.Headers.CopyHeadersFrom(sourceMessage);
            compressedMessage.Properties.CopyProperties(sourceMessage.Properties);
            compressedMessage.AddCompressionHeader(this.DataCompressor.Algorithm);
            sourceMessage.Close();
            return(compressedMessage);
        }
Пример #11
0
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            var correlationModel = (CorrelationModel)correlationState;

            if (reply != null)
            {
                //Correlation Guid for track
                var correlationGuid = MessageHeader.CreateHeader("Correlation-GUID", "http://tempuri.org", correlationModel.CorrelationGuid.ToString());
                reply.Headers.Add(correlationGuid);
                XmlWriterSettings settings = new XmlWriterSettings {
                    Encoding = System.Text.Encoding.UTF8
                };
                StringWriter  sw     = new StringWriter();
                XmlWriter     writer = XmlWriter.Create(sw, settings);
                MessageBuffer buffer = reply.CreateBufferedCopy(int.MaxValue);
                //Create a copy of the message in order to continue the handling of te SOAP
                reply = buffer.CreateMessage();
                reply.WriteMessage(writer);
                //Recreate the message
                writer.Flush();
                //Flush the contents of the writer so that the stream gets updated
                //you can log the str to the database
                var str = sw.ToString();
                WriteToTxt.WriteToFile(str);
                reply = buffer.CreateMessage();
            }
            else
            {
                WriteToTxt.WriteToFile("No response xml for this request");
            }

            WriteToTxt.WriteToFile("Response time:" + new TimeSpan(DateTime.Now.Ticks - correlationModel.ResponseTicks));
        }
Пример #12
0
        public Message CopyMessage(Message message, MessageContainer container, MessageDirection direction)
        {
            MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);

            if (direction == MessageDirection.Incoming)
            {
                container.RequestMessageText = buffer.CreateMessage().ToString();
                container.RequestReceived    = DateTime.Now;
                if (message.Properties.ContainsKey(RemoteEndpointMessageProperty.Name))
                {
                    RemoteEndpointMessageProperty property = (RemoteEndpointMessageProperty)message.Properties[RemoteEndpointMessageProperty.Name];
                    container.RemoteAddress = property.Address;
                }
                if (message.Headers.To != null)
                {
                    container.ToAddress = message.Headers.To.ToString();
                }
                container.RequestAction = message.Headers.Action;
            }
            else if (direction == MessageDirection.Outgoing)
            {
                container.ResponseMessageText = buffer.CreateMessage().ToString();
                container.ResponseReceived    = DateTime.Now;
                container.ResponseAction      = message.Headers.Action;
            }
            return(buffer.CreateMessage());
        }
Пример #13
0
        public object AfterReceiveRequest(
            ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);

            try
            {
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.Schemas.Add(schemas);
                settings.ValidationType = ValidationType.Schema;

                Message   msgToValidate = buffer.CreateMessage();
                XmlReader reader        = XmlReader.Create(
                    msgToValidate.GetReaderAtBodyContents().ReadSubtree(), settings);

                while (reader.Read())
                {
                    ;                   // do nothing, just validate
                }
                request = buffer.CreateMessage();
            }
            catch (Exception e)
            {
                throw new FaultException(e.Message);
            }
            return(null);
        }
Пример #14
0
        private Message TraceMessage(MessageBuffer buffer)
        {
            //Must use a buffer rather than the origonal message, because the Message's body can be processed only once.
            Message msg = buffer.CreateMessage();

            //Setup StringWriter to use as input for our StreamWriter
            //This is needed in order to capture the body of the message, because the body is streamed.
            StringWriter  stringWriter  = new StringWriter();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

            //msg.WriteMessage(xmlTextWriter);
            xmlTextWriter.Flush();
            xmlTextWriter.Close();


            //Setup filename to write to
            if (!Directory.Exists(LogDir))
            {
                Directory.CreateDirectory(LogDir);
            }

            DateTime now      = DateTime.Now;
            string   datePart = now.Year.ToString() + '-' + now.Month.ToString() + '-' + now.Day.ToString() + '-' + now.Hour + '-' + now.Minute + '-' + now.Second;
            string   fileName = LogDir + "\\" + datePart + '-' + "SoapEnv.xml";

            //Write to file
            using (StreamWriter sw = new StreamWriter(fileName))
                sw.Write(stringWriter.ToString());

            //Return copy of origonal message with unalterd State
            return(buffer.CreateMessage());
        }
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            if (!_traceSoapMessages && !_traceSoapMessageHeaders)
            {
                return(null);
            }
            StringBuilder logMessage = new StringBuilder();
            MessageBuffer buffer     = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();
            Message originalMessage = buffer.CreateMessage();

            logMessage.AppendLine("Received:");
            logMessage.AppendLine();
            if (_traceSoapMessageHeaders)
            {
                foreach (MessageHeader header in originalMessage.Headers)
                {
                    string headerString = header.ToString();
                    logMessage.AppendLine(headerString);
                }
            }
            if (_traceSoapMessages)
            {
                logMessage.AppendLine();
                string soapMessage = originalMessage.ToString();
                logMessage.AppendLine(soapMessage);
            }
            string logMessageString = logMessage.ToString();

            GOCWindows.Instance.Logger.LogMessage(new LogMessage(logMessageString, LogMessageType.Information, LoggingLevel.Maximum));
            return(null);
        }
        /// <summary>Called after an inbound message has been received but before the message is dispatched to the intended operation.</summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>The object used to correlate state. This object is passed back in the BeforeSendReply(Message@,object) method.</returns>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (request == null)
            {
                return(null);
            }

            /* Create a buffer in order to make it possible to work with copies of the message */
            MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);

            this.OnPreValidation(buffer.CreateMessage(), channel, instanceContext);

            /* Create a copy of the message and send it to the validation */
            request = buffer.CreateMessage();
            try {
                this.ValidateMessage(request);
            }
            catch (XmlSchemaValidationException ex) {
                this.OnValidationError(buffer.CreateMessage(), channel, instanceContext, ex);

                FaultReasonText reasonText = new FaultReasonText(Resources.MessageDoesNotComplyWithSchema, CultureInfo.InvariantCulture);
                throw new FaultException <string>(ex.Message, new FaultReason(reasonText), FaultCode.CreateSenderFaultCode(new FaultCode("InvalidMessage")));
            }

            this.OnValidationSuccess(buffer.CreateMessage(), channel, instanceContext);

            /* Validation was succesfull. Create a new copy of the message and pass it to the WCF process. */
            request = buffer.CreateMessage();

            /* There is no need to correlate the AfterReceiveRequest en BeforeSendReply calls, so simply return null */
            return(null);
        }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (!_traceSoapMessages && !_traceSoapMessageHeaders)
            {
                return;
            }
            StringBuilder logMessage = new StringBuilder();
            MessageBuffer buffer     = reply.CreateBufferedCopy(Int32.MaxValue);

            reply = buffer.CreateMessage();
            Message originalMessage = buffer.CreateMessage();

            logMessage.AppendLine("Sending:");
            logMessage.AppendLine();
            if (_traceSoapMessageHeaders)
            {
                foreach (MessageHeader header in originalMessage.Headers)
                {
                    string headerString = header.ToString();
                    logMessage.AppendLine(headerString);
                }
            }
            if (_traceSoapMessages)
            {
                logMessage.AppendLine();
                string soapMessage = originalMessage.ToString();
                logMessage.AppendLine(soapMessage);
            }
            string logMessageString = logMessage.ToString();

            GOCWindows.Instance.Logger.LogMessage(new LogMessage(logMessageString, LogMessageType.Information, LoggingLevel.Maximum));
        }
Пример #18
0
    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);

        reply = buffer.CreateMessage();
        LogService.Log("Reply:" + Environment.NewLine + buffer.CreateMessage());
    }
Пример #19
0
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);

            reply = buffer.CreateMessage();
            Console.WriteLine("Received:\n{0}", buffer.CreateMessage().ToString());
        }
Пример #20
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);

            reply = buffer.CreateMessage();
            Console.WriteLine("Message Sending:\n{0}", buffer.CreateMessage().ToString());
        }
Пример #21
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();
            Message messageCopy = buffer.CreateMessage();

            //para obtener el metodo y la peticion del ws
            var           action        = OperationContext.Current.IncomingMessageHeaders.Action;
            var           operationName = action.Substring(action.LastIndexOf("/") + 1);
            StringWriter  stringWriter  = new StringWriter();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);

            xmlTextWriter.Formatting  = Formatting.Indented;
            xmlTextWriter.Indentation = 1;
            xmlTextWriter.IndentChar  = '\t';
            messageCopy.WriteMessage(xmlTextWriter);


            // Read the custom context data from the headers
            ModelInterceptor requestHeaders = Header.ReadHeader(request);

            // Add an extension to the current operation context so
            // that our custom context can be easily accessed anywhere.
            //ServerContext customContext = new ServerContext();
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                Utilerias.validaUsuario(requestHeaders.usuario, requestHeaders.contrasena);
                new Logg().Info("Mensaje de Entrada: (Request) \n\n" + stringWriter.ToString());
                log4netRequest.Info("Mensaje de Entrada: (Request) \n\n" + stringWriter.ToString());
            }
            OperationContext.Current.IncomingMessageProperties.Add(
                "CurrentContext", new ModelInterceptor());
            return(null);
        }
Пример #22
0
        private Message TraceMessage(MessageBuffer buffer)
        {
            Message msg = buffer.CreateMessage();

            Console.WriteLine("\n{0}\n", msg);
            return(buffer.CreateMessage());
        }
Пример #23
0
        private Message LogMessage(MessageBuffer buffer)
        {
            Message       msg = buffer.CreateMessage();
            StringBuilder sb  = new StringBuilder();

            using (XmlWriter xw = XmlWriter.Create(sb))
            {
                msg.WriteMessage(xw);
                xw.Close();
            }

            string logMsg = $"Message via: '{msg.Properties.Via}' with '{msg.Headers?.Count}' Headers -> content:\n {sb.ToString().CleanWhiteSpaces()}";

            Debug.WriteLine(logMsg);
            _log.Trace(logMsg);

            foreach (var header in msg.Headers)
            {
                string headerMsg = $"Header: {header}";
                Debug.WriteLine(headerMsg);
                _log.Trace(headerMsg);
            }

            return(buffer.CreateMessage());
        }
Пример #24
0
        internal static bool IsMessageVersionNoneFault(ref Message message, int maxFaultSize)
        {
            if (message.Version != MessageVersion.None || message.IsEmpty)
            {
                return(false);
            }
            HttpResponseMessageProperty prop = message.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;

            if (prop == null || prop.StatusCode != HttpStatusCode.InternalServerError)
            {
                return(false);
            }
            using (MessageBuffer buffer = message.CreateBufferedCopy(maxFaultSize))
            {
                message.Close();
                message = buffer.CreateMessage();
                using (Message copy = buffer.CreateMessage())
                {
                    using (XmlDictionaryReader reader = copy.GetReaderAtBodyContents())
                    {
                        return(reader.IsStartElement(XD.MessageDictionary.Fault, MessageVersion.None.Envelope.DictionaryNamespace));
                    }
                }
            }
        }
        public string SelectOperation(ref Message message)
        {
            // TODO: check message format (raw)

            // Ignore non-POST requests
            if (!EnsurePostRequest(message))
            {
                return(null);
            }

            if (message.Properties.ContainsKey(DispatcherUtils.OperationNameKey))
            {
                return((string)message.Properties[DispatcherUtils.OperationNameKey]);
            }

            Message messageCopy;

            using (MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue)) {
                message     = buffer.CreateMessage();
                messageCopy = buffer.CreateMessage();
            }

            string operation = SelectOperationInternal(messageCopy);

            if (operation == null)
            {
                throw new InvalidOperationException("Invalid message format.");
            }

            message.Properties[DispatcherUtils.OperationNameKey] = operation;

            return(operation);
        }
Пример #26
0
        /// <summary>
        /// Extracts the body of a WCF Message and returns it as an XmlDocment
        /// </summary>
        /// <param name="msg">The WCF message</param>
        /// <param name="discardOriginalMessage">If true, the body of the original message will not be
        /// readable after calling this method</param>
        /// <returns>The body of the Message as an XmlDocument</returns>
        public static XmlDocument GetMessageBodyAsXmlDocument(Message msg, bool discardOriginalMessage)
        {
            XmlDocument messageXml;

            if (msg.IsEmpty)
            {
                messageXml = null;
            }
            else
            {
                messageXml = new XmlDocument();

                if (!discardOriginalMessage)
                {
                    MessageBuffer       bufferCopy = msg.CreateBufferedCopy(int.MaxValue);
                    XmlDictionaryReader reader     = bufferCopy.CreateMessage().GetReaderAtBodyContents();
                    messageXml.Load(reader);
                    reader.Close();
                    msg = bufferCopy.CreateMessage();
                    bufferCopy.Close();
                }
                else
                {
                    XmlDictionaryReader reader = msg.GetReaderAtBodyContents();
                    messageXml.Load(reader);
                    reader.Close();
                }
            }
            return(messageXml);
        }
 /// <summary>
 /// <see cref="System.ServiceModel.Dispatcher.IDispatchMessageInspector"/>
 /// </summary>
 /// <param name="request"><see cref="System.ServiceModel.Dispatcher.IDispatchMessageInspector"/></param>
 /// <param name="channel"><see cref="System.ServiceModel.Dispatcher.IDispatchMessageInspector"/></param>
 /// <param name="instanceContext"><see cref="System.ServiceModel.Dispatcher.IDispatchMessageInspector"/></param>
 /// <returns><see cref="System.ServiceModel.Dispatcher.IDispatchMessageInspector"/></returns>
 public object AfterReceiveRequest(ref Message request, IClientChannel channel,
                                   InstanceContext instanceContext)
 {
     if (IsEnabled)
     {
         OperationContext context = OperationContext.Current;
         MessageBuffer    buffer  = request.CreateBufferedCopy(int.MaxValue);
         request = buffer.CreateMessage();
         if (context != null && buffer.BufferSize <= this.MaxMessageSize)
         {
             try
             {
                 Message                       tmpMesage         = buffer.CreateMessage();
                 Process                       CurrentProcess    = Process.GetCurrentProcess();
                 IIdentity                     SourceIdentity    = GenericPrincipal.Current.Identity;
                 MessageProperties             messageProperties = context.IncomingMessageProperties;
                 RemoteEndpointMessageProperty endpointProperty  = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
                 IIdentity                     ClientIdentity    = null;
                 if (context.ServiceSecurityContext != null)
                 {
                     ClientIdentity = context.ServiceSecurityContext.PrimaryIdentity;
                 }
                 WcfEvent wcfEvent = new WcfEvent()
                 {
                     MessageID                 = Guid.NewGuid(),
                     ProcessID                 = CurrentProcess.Id,
                     ThreadID                  = Thread.CurrentThread.ManagedThreadId,
                     TimeCreated               = DateTime.Now,
                     ServiceName               = context.Host.Description.Name,
                     ServiceMachineName        = Environment.MachineName,
                     ServiceUri                = context.Channel.LocalAddress.ToString(),
                     ServiceIP                 = context.Channel.LocalAddress.Uri.Host,
                     ServicePort               = context.Channel.LocalAddress.Uri.Port,
                     ServiceIdentity           = SourceIdentity.Name,
                     ServiceAuthenticationType = SourceIdentity.AuthenticationType,
                     ClientIP                  = endpointProperty.Address,
                     ClientPort                = endpointProperty.Port,
                     ClientIdentity            = ClientIdentity == null ? "Anonymous" : ClientIdentity.Name,
                     ClientAuthenticationType  = ClientIdentity == null ? "None" : ClientIdentity.AuthenticationType,
                     Action   = request.Headers.Action,
                     Request  = tmpMesage.GetReaderAtBodyContents().ReadOuterXml(),
                     Response = null,
                     Misc     = null,
                     IsFault  = request.IsFault
                 };
                 return(wcfEvent);
             }
             catch (Exception ex)
             {
                 if (!System.Diagnostics.EventLog.SourceExists(this.EventLogSource))
                 {
                     System.Diagnostics.EventLog.CreateEventSource(this.EventLogSource, this.EventLogName);
                 }
                 System.Diagnostics.EventLog.WriteEntry(this.EventLogSource, ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
             }
         }
     }
     return(null);
 }
Пример #28
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();
            Console.WriteLine("Received:\n{0}", buffer.CreateMessage());
            return(null);
        }
 /// <summary>
 /// Gets the message body as a string.
 /// </summary>
 /// <returns>The message body.</returns>
 /// <param name="message">Message.</param>
 private string GetMessageBody(ref Message message)
 {
     using (MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue)) {
         // Message can only be read once, so replace it with a copy.
         message = buffer.CreateMessage();
         return(buffer.CreateMessage().ToString());
     }
 }
Пример #30
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            request = buffer.CreateMessage();
            Console.WriteLine("Sending:\n{0}", buffer.CreateMessage().ToString());
            return(request);
        }