Exemple #1
0
            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                MessageBuffer msgBuffer = reply.CreateBufferedCopy(int.MaxValue);

                MemoryStream ms = new MemoryStream();

                msgBuffer.WriteMessage(ms);

                ms.Position = 0;

                StreamReader sr     = new StreamReader(ms);
                string       output = sr.ReadToEnd();

                sr.Close();

                soapMessages.SoapResponse          = output;
                soapMessages.SoapResponseMessageId = GetMessageId(output);

                reply = msgBuffer.CreateMessage();

                msgBuffer.Close();

                //Below for debug, write Soap to static File
                //DirectoryInfo DirectoryInfo = new DirectoryInfo(@"C:\temp\HIServiceSOAP");
                //if (!DirectoryInfo.Exists)
                //{
                //  DirectoryInfo.Create();
                //}
                //FileInfo FileInfo = new FileInfo($"{DirectoryInfo.FullName}\\{DateTime.Now.ToString("yyyyMMddTHHmmss")}_ResponseSoap.xml");
                //File.WriteAllText(FileInfo.FullName, soapMessages.SoapRequest);

                // Comment this out as if error back from ESB - it doesn't get passed Validation
                // bool isValid = VerifyXML(soapMessages.SoapResponse);
                // soapMessages.IsSoapResponseSignatureValid = VerifyXML(soapMessages.SoapResponse);
            }
            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                MessageBuffer msgBuffer = reply.CreateBufferedCopy(int.MaxValue);

                MemoryStream ms = new MemoryStream();

                msgBuffer.WriteMessage(ms);

                ms.Position = 0;

                StreamReader sr     = new StreamReader(ms);
                string       output = sr.ReadToEnd();

                sr.Close();

                soapMessages.SoapResponse          = output;
                soapMessages.SoapResponseMessageId = GetMessageId(output);

                reply = msgBuffer.CreateMessage();

                msgBuffer.Close();

                // Comment this out as if error back from ESB - it doesn't get passed Validation
                // bool isValid = VerifyXML(soapMessages.SoapResponse);
                // soapMessages.IsSoapResponseSignatureValid = VerifyXML(soapMessages.SoapResponse);
            }
Exemple #3
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            lock (_syncObject)
            {
                if (MessageSink != null)
                {
                    // so bizarre...but if you don't, you'll ruin comms between the service and client
                    MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
                    reply = buffer.CreateMessage();
                    // so bizarre...but if you don't, you'll ruin comms between the service and client

                    Message       msg = buffer.CreateMessage();
                    StringBuilder sb  = new StringBuilder();
                    XmlWriter     xw  = XmlWriter.Create(sb);
                    msg.WriteBody(xw);
                    xw.Close();

                    MessageSink.WriteMessage(String.Format("Received ({0}):", DateTime.Now.ToUniversalTime().ToString()));
                    MessageSink.WriteMessage(msg.ToString());
                    MessageSink.WriteMessage("Body:");
                    MessageSink.WriteMessage(sb.ToString());
                    buffer.Close();
                }
            }
        }
Exemple #4
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);
        }
Exemple #5
0
        public void TestCreateMessageFromClosedBuffer()
        {
            Message       m = Message.CreateMessage(MessageVersion.Default, String.Empty);
            MessageBuffer b = m.CreateBufferedCopy(0);

            b.Close();
            b.CreateMessage();
        }
Exemple #6
0
 private void Release()
 {
     if (buffer == null)
     {
         return;
     }
     buffer.Close();
     buffer  = null;
     message = null;
 }
        /// <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"></param>
        /// <param name="correlationState"></param>
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);

            var requestCopy = buffer.CreateMessage();

            var messageLog = new MessageInspectorLogger();

            messageLog.Log(requestCopy);

            reply = buffer.CreateMessage();

            buffer.Close();
        }
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            MessageBuffer messageBuffer = reply.CreateBufferedCopy(1048576);
            MemoryStream  memoryStream  = new MemoryStream();

            messageBuffer.WriteMessage(memoryStream);
            memoryStream.Position = 0L;
            StreamReader streamReader = new StreamReader(memoryStream);

            this.RawResponse = streamReader.ReadToEnd();
            streamReader.Close();
            memoryStream.Close();
            reply = messageBuffer.CreateMessage();
            messageBuffer.Close();
        }
        /// <summary>
        /// Enables inspection or modification of a message before a request message is
        /// sent to a service
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

            var requestCopy = buffer.CreateMessage();

            var messageLog = new MessageInspectorLogger();

            messageLog.Log(requestCopy);

            request = buffer.CreateMessage();

            buffer.Close();

            return(null);
        }
Exemple #10
0
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            //create a copy of the message since a message can be read only once
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);

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

            //log the action
            Helper.Log(dupeRequest.Headers.Action);

            buffer.Close();

            Helper.Log("IDispatchMessageInspector.AfterReceiveRequest() called from " + Helper.GetClientIP());
            return(null);
        }
        /// <summary>
        /// Async method of ProcessMessage.
        /// </summary>
        /// <param name="request">request message</param>
        /// <param name="callback">callback method</param>
        /// <param name="asyncState">async state</param>
        /// <returns>async result</returns>
        public IAsyncResult BeginProcessMessage(Message request, AsyncCallback callback, object asyncState)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);

            byte[] messageData = AzureQueueItem.Serialize(buffer.CreateMessage());

            QueueAsyncResult asyncResult = new QueueAsyncResult(callback, asyncState);

            UniqueId messageId = request.Headers.MessageId;

            asyncResult.MessageId = messageId;

            asyncResult.StorageClient = this.requestStorageClient;

            try
            {
                BrokerTracing.TraceVerbose(
                    "[AzureServiceClient].BeginProcessMessage: Try to add message {0} to the request queue.",
                    messageId);

                var reliableState = new ReliableQueueClient.ReliableState(asyncResult, messageId);

                // Notice: It can happen that response message is back before
                // EndAddMessage is called on the request message. So
                // add/update the callback info to AzureQueueManager before
                // calling BeginAddMessage avoid the issue that response comes
                // back but can't find callback info.
                this.manager.AddQueueAsyncResult(asyncResult, this.requestStorageClient.QueueName, this.responseStorageName);

                this.requestStorageClient.BeginAddMessage(messageData, messageId, this.BeginAddMessageCallback, reliableState);
            }
            catch (Exception e)
            {
                BrokerTracing.TraceError(
                    "[AzureServiceClient].BeginProcessMessage: Failed to add message {0}, {1}",
                    messageId,
                    e);

                this.manager.CompleteCallback(asyncResult, null, e);
            }
            finally
            {
                buffer.Close();
            }

            return(asyncResult);
        }
Exemple #12
0
 internal MessageLogTraceRecord(ref System.ServiceModel.Channels.Message message, XmlReader reader, System.ServiceModel.Diagnostics.MessageLoggingSource source, bool logMessageBody) : this(source)
 {
     MessageBuffer buffer = null;
     try
     {
         this.logMessageBody = logMessageBody;
         this.message        = message;
         this.reader         = reader;
         this.type           = message.GetType();
     }
     finally
     {
         if (buffer != null)
         {
             buffer.Close();
         }
     }
 }
Exemple #13
0
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            lock (_syncObject)
            {
                if (MessageSink != null)
                {
                    // so bizarre...but if you don't, you'll ruin comms between the service and client
                    MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
                    request = buffer.CreateMessage();
                    // so bizarre...but if you don't, you'll ruin comms between the service and client

                    MessageSink.WriteMessage(String.Format("Sending ({0}):", DateTime.Now.ToUniversalTime().ToString()));
                    MessageSink.WriteMessage(buffer.CreateMessage().ToString());
                    buffer.Close();
                }
            }

            return(null);
        }
Exemple #14
0
            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                MessageBuffer msgBuffer = reply.CreateBufferedCopy(int.MaxValue);

                Message msg = msgBuffer.CreateMessage();

                soapMessages.SoapResponse = ConvertMessageToString(msg);

                reply = msgBuffer.CreateMessage();

                msgBuffer.Close();

                // Verify signature on soap response
                try
                {
                    soapMessages.SoapResponseSignatureStatus = SoapSignatureUtility.VerifyXML(soapMessages.SoapResponse);
                }
                catch (Exception ex)
                {
                }
            }
Exemple #15
0
        public void PoxBufferedMessage_BufferedCopy_Negative()
        {
            // write message throws argument null
            // All props throw after close, create message, write message throw after close

            using (Message message = this.GetMessage())
            {
                MessageBuffer buffer = message.CreateBufferedCopy(0);
                // WriteMessage throws ArgumentNullException.
                ExceptionHelper.ExpectArgumentNullException(() =>
                {
                    buffer.WriteMessage(null);
                }, "stream");

                // All members throw ObjectDisposedException after Close.
                buffer.Close();
                ExceptionHelper.ExpectException <ObjectDisposedException>(() =>
                {
                    int bufferSize = buffer.BufferSize;
                }, ObjectDisposedText);

                ExceptionHelper.ExpectException <ObjectDisposedException>(() =>
                {
                    string contentType = buffer.MessageContentType;
                }, ObjectDisposedText);

                ExceptionHelper.ExpectException <ObjectDisposedException>(() =>
                {
                    buffer.CreateMessage();
                }, ObjectDisposedText);

                ExceptionHelper.ExpectException <ObjectDisposedException>(() =>
                {
                    using (MemoryStream stream = new MemoryStream())
                    {
                        buffer.WriteMessage(stream);
                    }
                }, ObjectDisposedText);
            }
        }
        internal MessageLogTraceRecord(ref Message message, XmlReader reader, MessageLoggingSource source, bool logMessageBody)
            : this(source)
        {
            Fx.Assert(message != null, "");

            MessageBuffer buffer = null;

            try
            {
                this.logMessageBody = logMessageBody;
                this.message        = message;
                this.reader         = reader;
                this.type           = message.GetType();
            }
            finally
            {
                if (buffer != null)
                {
                    buffer.Close();
                }
            }
        }
Exemple #17
0
            public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
            {
                MessageBuffer msgBuffer = reply.CreateBufferedCopy(int.MaxValue);

                MemoryStream ms = new MemoryStream();

                msgBuffer.WriteMessage(ms);

                ms.Position = 0;

                StreamReader sr     = new StreamReader(ms);
                string       output = sr.ReadToEnd();

                sr.Close();
                //File.WriteAllText("C:\\Temp\\SOAP_Response.xml", output);

                soapMessages.SoapResponse = output;

                reply = msgBuffer.CreateMessage();

                msgBuffer.Close();
            }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Try to get Request ID from inbound request.
            Guid OrganizationRequestId = Guid.Empty;

            try
            {
                // Get a copy to work with.
                using (MessageBuffer mbuff = request.CreateBufferedCopy(Int32.MaxValue))
                {
                    request = mbuff.CreateMessage();  // Copy it back to the request buffer.
                    using (XmlDictionaryReader msgReader = mbuff.CreateMessage().GetReaderAtBodyContents())
                    {
                        msgReader.MoveToContent();
                        while (msgReader.Read())
                        {
                            if (msgReader.NodeType == XmlNodeType.Element && msgReader.LocalName.Equals("RequestId", StringComparison.OrdinalIgnoreCase))
                            {
                                string readValue = msgReader.ReadElementContentAsString();
                                if (!string.IsNullOrEmpty(readValue))
                                {
                                    Guid.TryParse(readValue, out OrganizationRequestId); // Find the request ID from the message and assign it to the new tracking id.
                                }
                                break;
                            }
                        }
                    }
                    mbuff.Close();
                }
            }
            catch
            {
            }

            // Adding HTTP Headers
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                HttpRequestMessageProperty httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
                if (string.IsNullOrEmpty(httpRequestMessage.Headers[Utilities.CDSRequestHeaders.USER_AGENT_HTTP_HEADER]))
                {
                    httpRequestMessage.Headers[Utilities.CDSRequestHeaders.USER_AGENT_HTTP_HEADER] = _userAgent;
                }
                if (string.IsNullOrEmpty(httpRequestMessage.Headers[HttpRequestHeader.Connection]))
                {
                    httpRequestMessage.Headers.Add(HttpRequestHeader.Connection, Utilities.CDSRequestHeaders.CONNECTION_KEEP_ALIVE);
                }
                if (OrganizationRequestId != Guid.Empty && string.IsNullOrEmpty(httpRequestMessage.Headers[Utilities.CDSRequestHeaders.X_MS_CLIENT_REQUEST_ID]))
                {
                    httpRequestMessage.Headers[Utilities.CDSRequestHeaders.X_MS_CLIENT_REQUEST_ID] = OrganizationRequestId.ToString();
                }
                if ((_callerCdsConnectionServiceHandler != null && (_callerCdsConnectionServiceHandler.SessionTrackingId.HasValue && _callerCdsConnectionServiceHandler.SessionTrackingId.Value != Guid.Empty)) && string.IsNullOrEmpty(httpRequestMessage.Headers[Utilities.CDSRequestHeaders.X_MS_CLIENT_SESSION_ID]))
                {
                    httpRequestMessage.Headers[Utilities.CDSRequestHeaders.X_MS_CLIENT_SESSION_ID] = _callerCdsConnectionServiceHandler.SessionTrackingId.Value.ToString();
                }
                if ((_callerCdsConnectionServiceHandler != null && _callerCdsConnectionServiceHandler.ForceServerCacheConsistency && string.IsNullOrEmpty(httpRequestMessage.Headers[Utilities.CDSRequestHeaders.FORCE_CONSISTENCY])))
                {
                    httpRequestMessage.Headers[Utilities.CDSRequestHeaders.FORCE_CONSISTENCY] = "Strong";
                }
            }
            else
            {
                HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty();
                httpRequestMessage.Headers.Add(Utilities.CDSRequestHeaders.USER_AGENT_HTTP_HEADER, _userAgent);
                httpRequestMessage.Headers.Add(HttpRequestHeader.Connection, Utilities.CDSRequestHeaders.CONNECTION_KEEP_ALIVE);

                if (OrganizationRequestId != Guid.Empty)
                {
                    httpRequestMessage.Headers.Add(Utilities.CDSRequestHeaders.X_MS_CLIENT_REQUEST_ID, OrganizationRequestId.ToString());
                }
                if (_callerCdsConnectionServiceHandler != null && (_callerCdsConnectionServiceHandler.SessionTrackingId.HasValue && _callerCdsConnectionServiceHandler.SessionTrackingId.Value != Guid.Empty))
                {
                    httpRequestMessage.Headers.Add(Utilities.CDSRequestHeaders.X_MS_CLIENT_SESSION_ID, _callerCdsConnectionServiceHandler.SessionTrackingId.Value.ToString());
                }
                if ((_callerCdsConnectionServiceHandler != null && _callerCdsConnectionServiceHandler.ForceServerCacheConsistency && string.IsNullOrEmpty(httpRequestMessage.Headers[Utilities.CDSRequestHeaders.FORCE_CONSISTENCY])))
                {
                    httpRequestMessage.Headers.Add(Utilities.CDSRequestHeaders.FORCE_CONSISTENCY, "Strong");
                }

                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }

            // Adding SOAP headers
            Guid callerId = Guid.Empty;

            if (_callerCdsConnectionServiceHandler != null)
            {
                if (_callerCdsConnectionServiceHandler.CdsWebClient != null)
                {
                    callerId = _callerCdsConnectionServiceHandler.CdsWebClient.CallerId;
                }
            }

            if (callerId == Guid.Empty) // Prefer the CRM Caller ID over hte AADObjectID.
            {
                if (_callerCdsConnectionServiceHandler != null && (_callerCdsConnectionServiceHandler.CallerAADObjectId.HasValue && _callerCdsConnectionServiceHandler.CallerAADObjectId.Value != Guid.Empty))
                {
                    // Add Caller ID to the SOAP Envolope.
                    // Set a header request with the AAD Caller Object ID.
                    using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
                    {
                        var AADCallerIdHeader = new MessageHeader <Guid>(_callerCdsConnectionServiceHandler.CallerAADObjectId.Value).GetUntypedHeader(Utilities.CDSRequestHeaders.AAD_CALLER_OBJECT_ID_HTTP_HEADER, "http://schemas.microsoft.com/xrm/2011/Contracts");
                        request.Headers.Add(AADCallerIdHeader);
                    }
                }
            }

            if (OrganizationRequestId != Guid.Empty)
            {
                using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
                {
                    var ClientRequestHeader = new MessageHeader <Guid>(OrganizationRequestId).GetUntypedHeader(Utilities.CDSRequestHeaders.X_MS_CLIENT_REQUEST_ID, "http://schemas.microsoft.com/xrm/2011/Contracts");
                    request.Headers.Add(ClientRequestHeader);
                }
            }

            if (_callerCdsConnectionServiceHandler != null && (_callerCdsConnectionServiceHandler.SessionTrackingId.HasValue && _callerCdsConnectionServiceHandler.SessionTrackingId.Value != Guid.Empty))
            {
                using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
                {
                    var ClientSessionRequestHeader = new MessageHeader <Guid>(_callerCdsConnectionServiceHandler.SessionTrackingId.Value).GetUntypedHeader(Utilities.CDSRequestHeaders.X_MS_CLIENT_SESSION_ID, "http://schemas.microsoft.com/xrm/2011/Contracts");
                    request.Headers.Add(ClientSessionRequestHeader);
                }
            }

            if ((_callerCdsConnectionServiceHandler != null && _callerCdsConnectionServiceHandler.ForceServerCacheConsistency))
            {
                using (OperationContextScope scope = new OperationContextScope((IContextChannel)channel))
                {
                    var ForceConsistencytHeader = new MessageHeader <string>("Strong").GetUntypedHeader(Utilities.CDSRequestHeaders.FORCE_CONSISTENCY, "http://schemas.microsoft.com/xrm/2011/Contracts");
                    request.Headers.Add(ForceConsistencytHeader);
                }
            }
            return(null);
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            /*
             * if (!request.IsFault)
             * {
             *  var quotas = new XmlDictionaryReaderQuotas();
             *  var bodyReader = request.GetReaderAtBodyContents().ReadSubtree();
             *
             *  var wrapperSettings = new XmlReaderSettings();
             *  wrapperSettings.CloseInput = true;
             *  wrapperSettings.ValidationFlags = XmlSchemaValidationFlags.None;
             *  wrapperSettings.ValidationType = ValidationType.None;
             *
             *  var wrappedReader = XmlReader.Create(bodyReader, wrapperSettings);
             *
             *  File.WriteAllText(Path.Combine("Z:\\Logs\\", Guid.NewGuid().ToString("N") + ".xml"),
             *      wrappedReader.ReadOuterXml());
             *
             *  var memStream = new MemoryStream();
             *  var xdw = XmlDictionaryWriter.CreateBinaryWriter(memStream);
             *  xdw.WriteNode(wrappedReader, false);
             *  xdw.Flush();
             *  memStream.Position = 0L;
             *
             *  var xdr = XmlDictionaryReader.CreateBinaryReader(memStream, quotas);
             *
             *  Message replacedMessage = Message.CreateMessage(request.Version, null, xdr);
             *  replacedMessage.Headers.CopyHeadersFrom(request.Headers);
             *  replacedMessage.Properties.CopyProperties(request.Properties);
             *  request = replacedMessage;
             * }
             */

            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            // WARNING: DOES NOT WORK WITH SECURED BINDINGS!!!
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
            MessageBuffer buffer = request.CreateBufferedCopy(int.MaxValue);  // cannot create even buffered copy when binding is secured

            try
            {
                Message toBeLogged = buffer.CreateMessage();

                string filePath = GetLogFilePath();
                using (var fileStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 0x2000, FileOptions.SequentialScan))
                    using (var xdw = XmlDictionaryWriter.CreateTextWriter(fileStream, Encoding.UTF8, false))
                    {
                        toBeLogged.WriteMessage(xdw);
                        xdw.Flush();
                    }

                request = buffer.CreateMessage();
            }
            finally
            {
                if (buffer != null)
                {
                    buffer.Close();
                }
            }

            return(null);
        }
Exemple #20
0
 public void Dispose()
 {
     _owner.Close();
 }
Exemple #21
0
 public void Close()
 {
     localBuffer.Close();
     Console.WriteLine("reader closed");
 }
Exemple #22
0
            public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
            {
                string startInfo = "application/soap+xml";
                string boundary  = string.Format("uuid:{0}+id=1", Guid.NewGuid());
                string startUri  = "http://tempuri.org/0";

                // Set message ID
                UniqueId messageId = new UniqueId();

                soapMessages.SoapRequestMessageId = messageId.ToString();

                // Modify MessageId and From headers
                request.Headers.MessageId = messageId;
                request.Headers.From      = new EndpointAddress("http://www.w3.org/2005/08/addressing/anonymous");
                request.Headers.To        = new Uri("http://www.w3.org/2005/08/addressing/anonymous");

                // Create message buffer (Message needs to be recreated multiple times)
                MessageBuffer msgBuffer = request.CreateBufferedCopy(int.MaxValue);

                // Get assembled soap request and sign
                var messageToSign = msgBuffer.CreateMessage();
                var bigXml        = ConvertMessageToString(messageToSign);
                var signedBigXml  = Encoding.UTF8.GetString(SoapSignatureUtility.SignBodyAndAddressingHeaders(Encoding.UTF8.GetBytes(bigXml), signingCertificate));

                soapMessages.SoapRequest = signedBigXml;

                // Encoding message into MTOM format using MTOM writer
                request = msgBuffer.CreateMessage();
                var initialMs     = new MemoryStream();
                var initialWriter = XmlDictionaryWriter.CreateMtomWriter(initialMs, Encoding.UTF8, int.MaxValue, startInfo, boundary, startUri, true, true);

                request.WriteMessage(initialWriter);
                initialWriter.Flush();

                var originalMessageSize = (int)initialMs.Length;

                // Copy MTOM message into buffer
                byte[] bufferUnsigned = new byte[originalMessageSize];
                Array.Copy(initialMs.GetBuffer(), 0, bufferUnsigned, 0, (int)initialMs.Position);
                string mtomString = Encoding.UTF8.GetString(bufferUnsigned);

                // Get SOAP XML from MTOM message, with start and end index
                int startSoapIndex;
                var unsignedXml  = GetSoapFromString(mtomString, out startSoapIndex);
                int endSoapIndex = startSoapIndex + unsignedXml.Length;

                // If binary MIME parts are found in MTOM message, then replace out base64 content with MTOM include statement
                string signedFinalXml    = signedBigXml;
                var    partHeaderMatches = Regex.Matches(mtomString, @"((Content-ID: <.*>\s+)|(Content-Transfer-Encoding: binary\s+)|(Content-Type: application/octet-stream\s+)){3}", RegexOptions.IgnoreCase);

                if (partHeaderMatches.Count > 0)
                {
                    for (int x = 0; x < partHeaderMatches.Count; x++)
                    {
                        var contentId          = Regex.Match(partHeaderMatches[x].Value, "Content-ID: <(.*?)>");
                        var encodedContentId   = HttpUtility.UrlEncode(contentId.Groups[1].Value).Replace(".", @"\.");
                        var unencodedContentId = contentId.Groups[1].Value.Replace(".", @"\.");

                        // var xopIncludeMatch = Regex.Match(unsignedXml, "(<[^>]+?>)(<([^>]+?:)?Include href=\"cid:(" + encodedContentId + ")\"[^>]*?/>)(</[^>]+?>)", RegexOptions.IgnoreCase);

                        var xopIncludeMatch = Regex.Match(unsignedXml, "(<[^>]+?>)(<([^>]+?:)?Include href=\"cid:(" + encodedContentId + "|" + unencodedContentId + ")\"[^>]*?/>)(</[^>]+?>)", RegexOptions.IgnoreCase);

                        signedFinalXml = Regex.Replace(signedFinalXml,
                                                       xopIncludeMatch.Groups[1] + "[^<]*?" + xopIncludeMatch.Groups[5],
                                                       xopIncludeMatch.Groups[0].Value);
                    }
                }
                else
                {
                    signedFinalXml = signedBigXml;
                }

                // Get difference in message length between unsigned and signed SOAP messages
                int diff = Encoding.UTF8.GetBytes(signedFinalXml).Length - Encoding.UTF8.GetBytes(unsignedXml).Length;

                // Create buffer large enough to contain MTOM message with signed SOAP XML
                byte[] bufferSigned = new byte[bufferUnsigned.Length + diff];

                // Copy MIME start content (everything before SOAP XML) from unsigned buffer to signed buffer
                Array.Copy(bufferUnsigned, bufferSigned, startSoapIndex);

                // Copy signed SOAP XML into signed buffer after MIME start content
                var signedXmlArray = Encoding.UTF8.GetBytes(signedFinalXml);

                Array.Copy(signedXmlArray, 0, bufferSigned, startSoapIndex, signedXmlArray.Length);

                // Copy MIME end content to after signed SOAP XML
                Array.Copy(bufferUnsigned, endSoapIndex, bufferSigned, startSoapIndex + signedXmlArray.Length, bufferUnsigned.Length - (endSoapIndex + 1));

                var mimeContent = new ArraySegment <byte>(bufferSigned, 0, originalMessageSize + diff).Array;

                soapMessages.MtomRequest = mimeContent;

                // Recreate request (Message) using MTOM reader
                var outputReader = XmlDictionaryReader.CreateMtomReader(mimeContent, 0, mimeContent.Length, Encoding.UTF8, new XmlDictionaryReaderQuotas());

                request = Message.CreateMessage(outputReader, int.MaxValue, request.Version);

                // Dispose things
                msgBuffer.Close();

                return(null);
            }
Exemple #23
0
 public override void Close()
 {
     buffer.Close();
 }
Exemple #24
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            // Service Runtime'a gececek olan kullanici, ip vs. gibi degerler bir header olarak request'e eklenecek.
            MessageBuffer      buffer      = request.CreateBufferedCopy(request.ToString().Length);
            Message            tRequest    = buffer.CreateMessage();
            ServiceContextInfo contextInfo = null;

            var containsMessageHeader = false;

            if (OperationContext.Current != null && OperationContext.Current.IncomingMessageHeaders != null)
            {
                int contextHeaderIndex = OperationContext.Current.IncomingMessageHeaders.FindHeader(ServiceBase.ContextDataKey, ServiceBase.ContextDataNamespaceKey);
                if (contextHeaderIndex >= 0)
                {
                    //contextInfo = OperationContext.Current.IncomingMessageHeaders.GetHeader<DefaultServiceContextInfo>(contextHeaderIndex);
                    var typeFinder         = EngineContext.Current.Resolve <ITypeFinder>();
                    var contextInfos       = typeFinder.FindClassesOfType <ServiceContextInfo>().ToList();
                    var currentContextInfo = contextInfos.Count() == 1
                                                          ? contextInfos[0]
                                                          : contextInfos.FirstOrDefault(
                        t => !(t == typeof(DefaultServiceContextInfo)));
                    using (XmlDictionaryReader reader = OperationContext.Current.IncomingMessageHeaders.GetReaderAtHeader(contextHeaderIndex))
                    {
                        MessageHeaderInfo headerInfo = OperationContext.Current.IncomingMessageHeaders[contextHeaderIndex];
                        var serializer = new DataContractSerializer(currentContextInfo.UnderlyingSystemType, headerInfo.Name, headerInfo.Namespace, null, int.MaxValue, false, false, null);
                        contextInfo = serializer.ReadObject(reader) as ServiceContextInfo;
                    }

                    containsMessageHeader = true;
                }
            }
            if (!containsMessageHeader)
            {
                if (_currentContextInfoProviderType == null)
                {
                    var typeFinder           = EngineContext.Current.Resolve <ITypeFinder>();
                    var contextInfoProviders = typeFinder.FindClassesOfType <ServiceContextInfoProvider>().ToList();
                    _currentContextInfoProviderType = contextInfoProviders.Count() == 1
                                                          ? contextInfoProviders[0]
                                                          : contextInfoProviders.FirstOrDefault(
                        t => !(t == typeof(DefaultServiceContextInfoProvider)));
                }

                if (_currentContextInfoProviderType == null)
                {
                    _currentContextInfoProviderType = typeof(DefaultServiceContextInfoProvider);
                }
                var contextInfoProvider =
                    Activator.CreateInstance(_currentContextInfoProviderType) as ServiceContextInfoProvider;
                if (contextInfoProvider != null)
                {
                    contextInfo = contextInfoProvider.GetServiceContextInfo();
                }

                if (contextInfo == null) //default
                {
                    contextInfo = new DefaultServiceContextInfo();
                }
                contextInfo.ClientIp = "127.0.0.1";
            }

            MessageHeader header = null;

            // ---------------------------------------------------------------------------------------------------------------------------------
            header = MessageHeader.CreateHeader(ServiceBase.ContextDataKey, ServiceBase.ContextDataNamespaceKey, contextInfo);
            tRequest.Headers.Add(header);

            ClientComputerInfo clientcomputerInfo = null;

            containsMessageHeader = false;
            if (OperationContext.Current != null && OperationContext.Current.IncomingMessageHeaders != null)
            {
                int contextHeaderIndex = OperationContext.Current.IncomingMessageHeaders.FindHeader(ServiceBase.ClientComputerInfoKey, ServiceBase.ClientComputerInfoNamespaceKey);
                if (contextHeaderIndex >= 0)
                {
                    clientcomputerInfo    = OperationContext.Current.IncomingMessageHeaders.GetHeader <ClientComputerInfo>(contextHeaderIndex);
                    containsMessageHeader = true;
                }
            }
            if (!containsMessageHeader)
            {
                //istek yapilan yerde bu kullanilacak
                clientcomputerInfo = new ClientComputerInfo()
                {
                    ClientComputerName      = System.Net.Dns.GetHostName(),
                    ClientComputerIpAddress = ServiceBase.GetLocalIPAddress()
                };
            }

            header = MessageHeader.CreateHeader(ServiceBase.ClientComputerInfoKey, ServiceBase.ClientComputerInfoNamespaceKey, clientcomputerInfo);
            tRequest.Headers.Add(header);

            request = tRequest;
            buffer.Close();
            return(null);
        }