Наследование: System.ServiceModel.Channels.MessageHeaderInfo
Пример #1
0
        static void Main(string[] args)
        {
            using (ChannelFactory<IMessage> channelFactory = new ChannelFactory<IMessage>("messageservice"))
            {
                IMessage proxy = channelFactory.CreateChannel();
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName, CultureInfoHeaderNamespace));
                    Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
                    Console.WriteLine(proxy.GetMessage());
                }

                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
                using (OperationContextScope contextScope = new OperationContextScope(proxy as IContextChannel))
                {
                    MessageHeader<CultureInfo> header = new MessageHeader<CultureInfo>(Thread.CurrentThread.CurrentUICulture);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader(CultureInfoHeadLocalName, CultureInfoHeaderNamespace));
                    Console.WriteLine("The UI culture of current thread is {0}", Thread.CurrentThread.CurrentUICulture);
                    Console.WriteLine(proxy.GetMessage());
                }
            }

            Console.Read();
        }
Пример #2
0
 /// <summary>
 /// 注入上下文:操作用户系统编号
 /// </summary>
 /// <param name="request"></param>
 /// <param name="channel"></param>
 /// <returns></returns>
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     System.ServiceModel.Channels.MessageHeader header = System.ServiceModel.Channels
                                                         .MessageHeader.CreateHeader("X-User-SysNo", string.Empty, ServiceContext.Current.UserSysNo);
     request.Headers.Add(header);
     return(null);
 }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            var requestHeader = correlationState as MiniProfilerRequestHeader;
            MiniProfiler.Stop();
            var miniProfiler = MiniProfiler.Current;

            if (miniProfiler != null && requestHeader != null)
            {
                if (requestHeader.ExcludeTrivialMethods)
                {
                    miniProfiler.Root.RemoveTrivialTimings();
                }

                var untypedHeader = new MessageHeader<MiniProfilerResultsHeader>(new MiniProfilerResultsHeader
                {
                    ProfilerResults = miniProfiler
                })
                .GetUntypedHeader(MiniProfilerResultsHeader.HeaderName, MiniProfilerResultsHeader.HeaderNamespace);

                reply.Headers.Add(untypedHeader);
            }

            //try
            //{
            //    var arrayOfIds = Settings.Storage.GetUnviewedIds(current.User).ToJson();
            //    // allow profiling of ajax requests
            //    response.AppendHeader("X-MiniProfiler-Ids", arrayOfIds);
            //}
            //catch { } // headers blew up
        }
Пример #4
0
        /// <summary>
        /// 请求发送前事件
        /// </summary>
        /// <param name="request">请求消息</param>
        /// <param name="channel">信道</param>
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            if (OperationContext.Current != null)
            {
                //WCF客户端获取公钥处理
                MessageHeaders incomingHeaders = OperationContext.Current.IncomingMessageHeaders;

                #region # 验证消息头

                if (!incomingHeaders.Any(x => x.Name == CommonConstants.WCFAuthenticationHeader && x.Namespace == GlobalSetting.ApplicationId))
                {
                    string message = "身份认证消息头不存在,请检查程序!";
                    NoPermissionException innerException = new NoPermissionException(message);
                    FaultReason           faultReason    = new FaultReason(message);
                    FaultCode             faultCode      = new FaultCode(HttpStatusCode.Unauthorized.ToString());
                    throw new FaultException <NoPermissionException>(innerException, faultReason, faultCode);
                }

                #endregion

                //读取消息头中的公钥
                Guid publicKey = incomingHeaders.GetHeader <Guid>(CommonConstants.WCFAuthenticationHeader, GlobalSetting.ApplicationId);

                //添加消息头
                System.ServiceModel.Channels.MessageHeader outgoingheader = System.ServiceModel.Channels.MessageHeader.CreateHeader(CommonConstants.WCFAuthenticationHeader, GlobalSetting.ApplicationId, publicKey);
                request.Headers.Add(outgoingheader);
            }

            return(null);
        }
Пример #5
0
        static void Main(string[] args)
        {
            string action = "http://www.artech.com/crm/AddCustomer";
            using (Message message = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, action))
            {
                string ns = "http://www.artech.com/crm";
                EndpointAddress address = new EndpointAddress("http://www.artech.com/crm/client");
                message.Headers.To = new Uri("http://www.artech.com/crm/customerservice");
                message.Headers.From = address;
                message.Headers.ReplyTo = address;
                message.Headers.FaultTo = address;
                message.Headers.MessageId = new UniqueId(Guid.NewGuid());
                message.Headers.RelatesTo = new UniqueId(Guid.NewGuid());

                MessageHeader<string> foo = new MessageHeader<string>("ABC", false, "http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver",false);
                MessageHeader<string> bar = new MessageHeader<string>("abc", true, "http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver", false);
                MessageHeader<string> baz = new MessageHeader<string>("123", false, "http://www.w3.org/2003/05/soap-envelope/role/next", true);

                message.Headers.Add(foo.GetUntypedHeader("Foo", ns));
                message.Headers.Add(bar.GetUntypedHeader("Bar", ns));
                message.Headers.Add(baz.GetUntypedHeader("Baz", ns));

                WriteMessage(message, "message.xml");
            }
        }
Пример #6
0
        /// <summary>
        /// Add token message at header to using NHibernate cache
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // add trace log for debug and performance tuning
            if (null != (request.Headers).MessageId && (request.Headers).MessageId.IsGuid)
            {
                ServiceStopWatch = Stopwatch.StartNew();
                Guid messageId;
                (request.Headers).MessageId.TryGetGuid(out messageId);

                CurrentTraceInfo = new TraceInfo()
                {
                    SessionId = (HttpContext.Current != null && HttpContext.Current.Session != null) ? HttpContext.Current.Session.SessionID : "",
                    TraceType = TraceType.WcfActionClientCall,
                    TraceName = request.Headers.Action,
                    TraceUniqueId = messageId.ToString()
                };

                TraceLogger.Instance.TraceServiceStart(CurrentTraceInfo, true);

                // Add a message header with sessionid
                MessageHeader<string> messageHeader = new MessageHeader<string>(CurrentTraceInfo.SessionId);
                MessageHeader untyped = messageHeader.GetUntypedHeader("sessionid", "ns");
                request.Headers.Add(untyped);
            }
            return null;
        }
 internal bool IsHeaderIncluded(MessageHeader header)
 {
     if (header == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("header");
     }
     return this.IsHeaderIncluded(header.Name, header.Namespace);
 }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageHeader<ApplicationContext> contextHeader = new MessageHeader<ApplicationContext>(ApplicationContext.Current);

            request.Headers.Add(contextHeader.GetUntypedHeader(ApplicationContext.ContextHeaderLocalName, ApplicationContext.ContextHeaderNameSpace));

            return null;
        }
 protected DelegatingHeader(MessageHeader innerHeader)
 {
     if (innerHeader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("innerHeader");
     }
     this.innerHeader = innerHeader;
 }
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     //Instantiate new HeaderObject with values from ClientContext;
     if (eCollabroRequest.ActiveUser != null)
     {
         var typedHeader = new MessageHeader<UserContextDC>(eCollabroRequest.ActiveUser);
         var untypedHeader = typedHeader.GetUntypedHeader("ActiveUser", "s");
         request.Headers.Add(untypedHeader);
     }
     return null;
 }
 public static void AddHeadersTo(Message message, MessageHeader header)
 {
     if (message.Headers.FindHeader("PacketRoutable", "http://schemas.microsoft.com/ws/2005/05/routing") == -1)
     {
         if (header == null)
         {
             header = Create();
         }
         message.Headers.Add(header);
     }
 }
 public EncryptedHeader(MessageHeader plainTextHeader, EncryptedHeaderXml headerXml, string name, string namespaceUri, MessageVersion version)
     : base(plainTextHeader)
 {
     if (!headerXml.HasId || headerXml.Id == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.EncryptedHeaderXmlMustHaveId)));
     }
     this.headerXml = headerXml;
     this.name = name;
     this.namespaceUri = namespaceUri;
     this.version = version;
 }
 public void BeforeSendReply(
     ref Message reply, 
     object correlationState)
 {
     var correlationId = correlationState as Guid?;
     if (correlationId != null)
     {
         var messageHeader = new MessageHeader<Guid>(correlationId.Value);
         var untypedHeader = messageHeader.GetUntypedHeader(Constants.CorrelationIdHeader, Constants.ErniChNamespace);
         reply.Headers.Add(untypedHeader);
     }
     EtwSampleServerEventSource.Log.RequestStop();
 }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var dataToSend = new ExternalApiConnectionHeader
                                 {
                                     ClientCulture = Thread.CurrentThread.CurrentCulture.Name,
                                     ClientUiCulture = Thread.CurrentThread.CurrentUICulture.Name
                                 };

            var typedHeader = new MessageHeader<ExternalApiConnectionHeader>(dataToSend);
            var untypedHeader = typedHeader.GetUntypedHeader("ExternalApiConnectionHeader", NS.ExternalApiNamespaceV1);
            request.Headers.Add(untypedHeader);
            return null;
        }
        public void GenerateMpr(MprGenerationRequestV1 request)
        {
            var responseContext =
                OperationContext.Current.IncomingMessageHeaders.GetHeader<ResponseContext>(
                    "ResponseContext", "ServiceModelEx");
            System.Diagnostics.Trace.Assert(responseContext.MethodId.CompareTo(Guid.Empty.ToString()) != 0);

            LocalImageResourceManagerClient lirm =
                new LocalImageResourceManagerClient();
            lirm.Open();

            UniformImageVolumeDataContract ivdc = null;
            ivdc = lirm.GetImageVolume(request.ImageVolumeId);

            int[] size = CalculateSize(ivdc, request.Orientation);

            ImageDataContract idc = null;
            _cacheResultImages.TryGetValue(responseContext.MethodId, out idc);
            if (idc == null
                || idc.Width != size[0]
                || idc.Height != size[1])
            {
                idc = new ImageDataContract();
                idc.Width = size[0];
                idc.Height = size[1];
                idc = lirm.AddImage(idc);
                _cacheResultImages.TryAdd(responseContext.MethodId, idc);
            }

            lirm.Close();

            UpdatePixelsFromVolumeResampled(ivdc,
                request.Orientation, request.SlicePosition,
                request.WindowCenter, request.WindowWidth,
                idc);

            MessageHeader<ResponseContext> responseHeader = new MessageHeader<ResponseContext>(responseContext);
            NetMsmqBinding binding = new NetMsmqBinding("NoMsmqSecurity");
            MprGenerationResponseProxy proxy = new MprGenerationResponseProxy(binding,
                new EndpointAddress(responseContext.ResponseAddress));

            using (OperationContextScope scope = new OperationContextScope(proxy.InnerChannel))
            {
                OperationContext.Current.OutgoingMessageHeaders.Add(
                    responseHeader.GetUntypedHeader("ResponseContext", "ServiceModelEx"));

                proxy.OnMprDone(idc, request.RequestTime);
            }

            proxy.Close();
        }
Пример #16
0
        /// <summary>
        /// Add token message at header to using NHibernate cache
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //get the extension item that the client may have put in the channel
            var item = channel.Extensions.Find<NHibernate2ndLevelCacheBehaviorExtensionItem>();
            bool clientWantsToBypass = (item != null && item.BypassNHibernate2ndLevelCache);

            if (clientWantsToBypass || IsDefaultBypassNHibernateCache)
            {
                MessageHeader<bool> mhg = new MessageHeader<bool>(true);
                MessageHeader untyped = mhg.GetUntypedHeader("token", "ns");
                request.Headers.Add(untyped);
            }

            return null;
        }
 private void AddEncryptionReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, bool sign, out MemoryStream plainTextStream, out string encryptedDataId)
 {
     plainTextStream = new MemoryStream();
     XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(plainTextStream);
     if (sign)
     {
         this.AddSignatureReference(header, headerId, prefixGenerator, writer);
     }
     else
     {
         header.WriteHeader(writer, base.Version);
         writer.Flush();
     }
     encryptedDataId = base.GenerateId();
     this.referenceList.AddReferredId(encryptedDataId);
 }
        public void AfterInvoke(object correlationState)
        {
            if (!this.IsBidirectional) {
                return;
            }

            ApplicationContext context = correlationState as ApplicationContext;
            if (context == null) {
                return;
            }

            MessageHeader<ApplicationContext> contextHeader = new MessageHeader<ApplicationContext>(context);

            OperationContext.Current.OutgoingMessageHeaders.Add(contextHeader.GetUntypedHeader(ApplicationContext.ContextHeaderLocalName, ApplicationContext.ContextHeaderNameSpace));
            ApplicationContext.Current = null;
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //Instantiate new HeaderObject with values from ClientContext;
            var dataToSend = new CustomHeader
                {
                    WebNodeId = ClientCustomHeaderContext.HeaderInformation.WebNodeId,
                    WebSessionId = ClientCustomHeaderContext.HeaderInformation.WebSessionId,
                    WebUserId = ClientCustomHeaderContext.HeaderInformation.WebUserId
                };

            var typedHeader = new MessageHeader<CustomHeader>(dataToSend);
            var untypedHeader = typedHeader.GetUntypedHeader("custom-header", "s");

            request.Headers.Add(untypedHeader);
            return null;
        }
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            var requestHeader = correlationState as MiniProfilerRequestHeader;
            MiniProfiler.Stop();
            var miniProfiler = MiniProfiler.Current;

            if (miniProfiler != null && requestHeader != null)
            {
                if (requestHeader.ExcludeTrivialMethods)
                {
                    miniProfiler.Root.RemoveTrivialTimings();
                }

                var header = new MiniProfilerResultsHeader
                {
                    ProfilerResults = miniProfiler
                };

                if (reply.Headers.MessageVersion != MessageVersion.None)
                {
                    var untypedHeader = new MessageHeader<MiniProfilerResultsHeader>(header)
                    .GetUntypedHeader(MiniProfilerResultsHeader.HeaderName, MiniProfilerResultsHeader.HeaderNamespace);

                    reply.Headers.Add(untypedHeader);
                }
                else if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
                {
                    HttpResponseMessageProperty property = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];

                    property.Headers.Add(MiniProfilerResultsHeader.HeaderName, header.ToHeaderText());
                }
            }
            else
            {
                throw new InvalidOperationException("MVC Mini Profiler does not support EnvelopeNone unless HTTP is the transport mechanism");
            }

            //try
            //{
            //    var arrayOfIds = Settings.Storage.GetUnviewedIds(current.User).ToJson();
            //    // allow profiling of ajax requests
            //    response.AppendHeader("X-MiniProfiler-Ids", arrayOfIds);
            //}
            //catch { } // headers blew up
        }
Пример #21
0
        object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            string headerText = "<wsse:UsernameToken xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\">" +
                                "<wsse:Username>{0}</wsse:Username>" +
                                "<wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\">{1}</wsse:Password>" +
                                "</wsse:UsernameToken>";    // +

            headerText = string.Format(headerText, _username, _password);

            XmlDocument MyDoc = new XmlDocument();

            MyDoc.LoadXml(headerText);
            XmlElement myElement = MyDoc.DocumentElement;

            System.ServiceModel.Channels.MessageHeader myHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", myElement, false);
            request.Headers.Add(myHeader);
            return(Convert.DBNull);
        }
        public static void SetSessionData(string userName, string password, ref Message request)
        {
            var userHeader = new MessageHeader <string> {
                Actor = HnForUserName, Content = userName
            };

            //Creating an untyped header to add to the WCF context
            System.ServiceModel.Channels.MessageHeader unTypedHeaderForUser = userHeader.GetUntypedHeader(HnForUserName, HNamespaceForUserName);
            //Add the header to the current request
            request.Headers.Add(unTypedHeaderForUser);

            var passwordHeader = new MessageHeader <string> {
                Actor = HnForPassword, Content = password
            };

            //Creating an untyped header to add to the WCF context
            System.ServiceModel.Channels.MessageHeader unTypedHeaderForPassword = passwordHeader.GetUntypedHeader(HnForPassword, HNamespaceForPassword);
            //Add the header to the current request
            request.Headers.Add(unTypedHeaderForPassword);
        }
Пример #23
0
        private void SetStartMessageHeaders(Message message, Message chunk)
        {
            this.messageId = Guid.NewGuid();
            //create messageId header
            this.messageIdHeader = MessageHeader.CreateHeader(
                ChunkingUtils.MessageIdHeader,
                ChunkingUtils.ChunkNs,
                this.messageId.ToString(),
                true);
            chunk.Headers.Add(this.messageIdHeader);

            //create chunkStart header
            MessageHeader chunkStartHeader = MessageHeader.CreateHeader(
                ChunkingUtils.ChunkingStartHeader,
                ChunkingUtils.ChunkNs,
                null,
                true);
            chunk.Headers.Add(chunkStartHeader);

            //write out original headers as new message's headers
            MessageHeaders headers = message.Headers;
            string addressingNs = ChunkingUtils.GetAddressingNamespace(message.Version);
            for (int i = 0; i < headers.Count; i++)
            {
                //look for Action header and write it out as OriginalAction

                if (headers[i].Name == "Action" && headers[i].Namespace == addressingNs)
                {
                    //write out original action
                    string originalAction = message.Headers.Action; //headers.GetHeader<string>(i);
                    MessageHeader originalActionHeader = MessageHeader.CreateHeader(ChunkingUtils.OriginalAction, ChunkingUtils.ChunkNs, originalAction);
                    chunk.Headers.Add(originalActionHeader);
                }
                else
                {
                    //copying a header
                    chunk.Headers.CopyHeaderFrom(headers, i);
                }
            }

        }
        protected override EncryptedHeader EncryptHeader(MessageHeader plainTextHeader, SymmetricAlgorithm algorithm, 
            SecurityKeyIdentifier keyIdentifier, MessageVersion version, string id, MemoryStream stream)
        {
            // We are not reading EncryptedData from the wire here, hence pass false.
            EncryptedHeaderXml encryptedHeaderXml = new EncryptedHeaderXml(version, false);
            encryptedHeaderXml.SecurityTokenSerializer = this.StandardsManager.SecurityTokenSerializer;
            encryptedHeaderXml.EncryptionMethod = this.EncryptionAlgorithm;
            encryptedHeaderXml.EncryptionMethodDictionaryString = this.EncryptionAlgorithmDictionaryString;
            encryptedHeaderXml.KeyIdentifier = keyIdentifier;
            encryptedHeaderXml.Id = id;
            // The Encrypted Headers MustUnderstand, Relay and Actor attributes will always match the
            // Security Headers value. The values for these on the Encrypted Header and its decrypted 
            // form can be different.
            encryptedHeaderXml.MustUnderstand = this.MustUnderstand;
            encryptedHeaderXml.Relay = this.Relay;
            encryptedHeaderXml.Actor = this.Actor;

            encryptedHeaderXml.SetUpEncryption(algorithm, stream);

            return new EncryptedHeader(plainTextHeader, encryptedHeaderXml, EncryptedHeaderXml.ElementName.Value, EncryptedHeaderXml.NamespaceUri.Value, version);
        }
        /// <summary>
        /// before the send request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="channel">The channel.</param>
        /// <returns>the mini profiler start</returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // If we currently are running inside a MiniProfiler context, then add a request onto this request
            var miniProfiler = GetCurrentProfiler();
            if (miniProfiler != null)
            {
                var header = new MiniProfilerRequestHeader
                {
                    User = miniProfiler.User,
                    ParentProfilerId = miniProfiler.Id
                };

                // ReSharper disable PossibleUnintendedReferenceComparison
                if (request.Headers.MessageVersion != MessageVersion.None)
                // ReSharper restore PossibleUnintendedReferenceComparison
                {
                    var untypedHeader = new MessageHeader<MiniProfilerRequestHeader>(header)
                    .GetUntypedHeader(MiniProfilerRequestHeader.HeaderName, MiniProfilerRequestHeader.HeaderNamespace);
                    request.Headers.Add(untypedHeader);
                }
                else if (_http || WebOperationContext.Current != null || channel.Via.Scheme == "http" | channel.Via.Scheme == "https")
                {
                    _http = true;

                    if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
                    {
                        request.Properties.Add(HttpRequestMessageProperty.Name, new HttpRequestMessageProperty());
                    }
                    HttpRequestMessageProperty property = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

                    property.Headers.Add(MiniProfilerRequestHeader.HeaderName, header.ToHeaderText());
                }
                else
                    throw new InvalidOperationException("MVC Mini Profiler does not support EnvelopeNone unless HTTP is the transport mechanism");

                return new MiniProfilerStart { StartTime = miniProfiler.DurationMilliseconds };
            }

            return null;
        }
Пример #26
0
        static void Main(string[] args)
        {
            try
            {
                TestProxy.Service1Client client = new TestProxy.Service1Client();

                using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
                {
                    MessageHeader<string> cultureHeader = new MessageHeader<string>("en-US");

                    // Add the culture header into request
                    OperationContext.Current.OutgoingMessageHeaders.Add(
                        cultureHeader.GetUntypedHeader("culture", "urn:wcf:extension")
                        );

                    client.GetData(11);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Пример #27
0
 internal static void AddHeader(MessageHeaders headers, MessageHeader hContext)
 {
     headers.Add(hContext);
 }
 MessagePartProtectionMode GetProtectionMode(MessageHeader header)
 {
     if (!this.RequireMessageProtection)
     {
         return MessagePartProtectionMode.None;
     }
     bool sign = this.signedInfo != null && this.effectiveSignatureParts.IsHeaderIncluded(header);
     bool encrypt = this.referenceList != null && this.EncryptionParts.IsHeaderIncluded(header);
     return MessagePartProtectionModeHelper.GetProtectionMode(sign, encrypt, this.SignThenEncrypt);
 }
 protected virtual EncryptedHeader EncryptHeader(MessageHeader plainTextHeader, SymmetricAlgorithm algorithm,
         SecurityKeyIdentifier keyIdentifier, MessageVersion version, string id, MemoryStream stream)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
         SR.GetString(SR.HeaderEncryptionNotSupportedInWsSecurityJan2004, plainTextHeader.Name, plainTextHeader.Namespace)));
 }
 void EncryptAndWriteHeader(MessageHeader plainTextHeader, string id, MemoryStream stream, XmlDictionaryWriter writer)
 {
     EncryptedHeader encryptedHeader = EncryptHeader(
         plainTextHeader,
         this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version,
         id, stream);
     encryptedHeader.WriteHeader(writer, this.Version);
 }
        void ApplySecurityAndWriteHeader(MessageHeader header, string headerId, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator)
        {
            if (!this.RequireMessageProtection && this.ShouldSignToHeader)
            {
                if ((header.Name == XD.AddressingDictionary.To.Value) &&
                    (header.Namespace == this.Message.Version.Addressing.Namespace))
                {
                    if (this.toHeaderHash == null)
                    {
                        byte[] headerHash;
                        headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out headerHash);
                        this.toHeaderHash = headerHash;
                        this.toHeaderId = headerId;
                    }
                    else
                        // More than one 'To' header is specified in the message.
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.GetString(SR.TransportSecuredMessageHasMoreThanOneToHeader)));

                    return;
                }
            }

            MessagePartProtectionMode protectionMode = GetProtectionMode(header);
            MemoryStream plainTextStream;
            string encryptedDataId;
            switch (protectionMode)
            {
                case MessagePartProtectionMode.None:
                    header.WriteHeader(writer, this.Version);
                    return;
                case MessagePartProtectionMode.Sign:
                    AddSignatureReference(header, headerId, prefixGenerator, writer);
                    return;
                case MessagePartProtectionMode.SignThenEncrypt:
                    AddEncryptionReference(header, headerId, prefixGenerator, true, out plainTextStream, out encryptedDataId);
                    EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
                    this.hasSignedEncryptedMessagePart = true;
                    return;
                case MessagePartProtectionMode.Encrypt:
                    AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
                    EncryptAndWriteHeader(header, encryptedDataId, plainTextStream, writer);
                    return;
                case MessagePartProtectionMode.EncryptThenSign:
                    AddEncryptionReference(header, headerId, prefixGenerator, false, out plainTextStream, out encryptedDataId);
                    EncryptedHeader encryptedHeader = EncryptHeader(
                        header, this.encryptingSymmetricAlgorithm, this.encryptionKeyIdentifier, this.Version, encryptedDataId, plainTextStream);
                    AddSignatureReference(encryptedHeader, encryptedDataId, prefixGenerator, writer);
                    return;
                default:
                    Fx.Assert("Invalid MessagePartProtectionMode");
                    return;
            }
        }
 void AddSignatureReference(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer)
 {
     byte[] hashValue;
     headerId = GetSignatureHash(header, headerId, prefixGenerator, writer, out hashValue);
     this.signedInfo.AddReference(headerId, hashValue);
 }
        string GetSignatureHash(MessageHeader header, string headerId, IPrefixGenerator prefixGenerator, XmlDictionaryWriter writer, out byte[] hash)
        {
            HashStream hashStream = TakeHashStream();
            XmlDictionaryWriter effectiveWriter;
            XmlBuffer canonicalBuffer = null;

            if (writer.CanCanonicalize)
            {
                effectiveWriter = writer;
            }
            else
            {
                canonicalBuffer = new XmlBuffer(int.MaxValue);
                effectiveWriter = canonicalBuffer.OpenSection(XmlDictionaryReaderQuotas.Max);
            }

            effectiveWriter.StartCanonicalization(hashStream, false, null);

            header.WriteStartHeader(effectiveWriter, this.Version);
            if (headerId == null)
            {
                headerId = GenerateId();
                this.StandardsManager.IdManager.WriteIdAttribute(effectiveWriter, headerId);
            }
            header.WriteHeaderContents(effectiveWriter, this.Version);
            effectiveWriter.WriteEndElement();
            effectiveWriter.EndCanonicalization();
            effectiveWriter.Flush();

            if (!ReferenceEquals(effectiveWriter, writer))
            {
                Fx.Assert(canonicalBuffer != null, "Canonical buffer cannot be null.");
                canonicalBuffer.CloseSection();
                canonicalBuffer.Close();
                XmlDictionaryReader dicReader = canonicalBuffer.GetReader(0);
                writer.WriteNode(dicReader, false);
                dicReader.Close();
            }

            hash = hashStream.FlushHashAndGetValue();

            return headerId;
        }
        void IPeerNodeMessageHandling.HandleIncomingMessage(MessageBuffer messageBuffer, PeerMessagePropagation propagateFlags,
            int index, MessageHeader hopHeader, Uri via, Uri to)
        {
            if (DiagnosticUtility.ShouldTraceVerbose)
            {
                TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerFloodedMessageReceived, SR.GetString(SR.TraceCodePeerFloodedMessageReceived), this.traceRecord, this, null);
            }

            if (via == null)
            {
                Fx.Assert("No VIA in the forwarded message!");
                using (Message message = messageBuffer.CreateMessage())
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.PeerMessageMustHaveVia, message.Headers.Action)));
                }
            }
            if ((propagateFlags & PeerMessagePropagation.Local) != 0)
            {
                DeliverMessageToClientChannels(null, messageBuffer, via, to, messageBuffer.MessageContentType, (int)maxReceivedMessageSize, index, hopHeader);
                messageBuffer = null;
            }
            else
            {
                if (DiagnosticUtility.ShouldTraceVerbose)
                {
                    using (Message traceMessage = messageBuffer.CreateMessage())
                    {
                        TraceUtility.TraceEvent(TraceEventType.Verbose, TraceCode.PeerFloodedMessageNotPropagated, SR.GetString(SR.TraceCodePeerFloodedMessageNotPropagated), this.traceRecord, this, null, traceMessage);
                    }
                }
            }
        }
 public void Add(MessageHeader header)
 {
 }
Пример #36
0
 public void Insert(int headerIndex, MessageHeader header)
 {
     l.Insert(headerIndex, header);
 }
Пример #37
0
 public void Add(MessageHeader header)
 {
     l.Add(header);
 }