Example #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();
        }
Example #2
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");
            }
        }
Example #3
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;
        }
        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;
        }
 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 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();
        }
        /// <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;
        }
        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;
        }
Example #11
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());
            }
        }
Example #12
0
            public ConnectionWithContext(C1Connection connection)
            {
                _client = new LogServiceClient(connection.Binding, connection.EndpointAddress);
                _operationContextScope = new OperationContextScope(_client.InnerChannel);

                var mhg = new MessageHeader<string>(connection._authenticationInfo.AuthToken);
                MessageHeader authToken = mhg.GetUntypedHeader("AuthToken", "Composite.Logger");

                OperationContext.Current.OutgoingMessageHeaders.Add(authToken);
            }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            DateTime now = DateTime.UtcNow;
            string timestamp = now.ToString("yyyy-MM-ddTHH:mm:ssZ", System.Globalization.CultureInfo.InvariantCulture);

            AuthenticationData authData = new AuthenticationData
            {
                Username = ClientAuthenticationHeaderContext.HeaderInformation.Username,
                Password = ClientAuthenticationHeaderContext.HeaderInformation.Password,
                Timespan = timestamp // This is the seed..
            };

            string serializedAuthData = Serializer.JsonSerializer<AuthenticationData>(authData);

            string signature = string.Empty;

            signature = Encryption.Encrypt(serializedAuthData, true);

            var encryptedHeader = new AuthenticationHeader
            {
                EncryptedSignature = signature
            };

            var typedHeader = new MessageHeader<AuthenticationHeader>(encryptedHeader);
            var untypedHeader = typedHeader.GetUntypedHeader("authentication-header", "chsakell.com");

            request.Headers.Add(untypedHeader);
            return null;
        }
        public void ProvideFault(Exception error, System.ServiceModel.Channels.MessageVersion version, ref System.ServiceModel.Channels.Message fault)
        {
            ServiceEndpoint endpoint = OperationContext.Current.Host.Description.Endpoints.Find(OperationContext.Current.EndpointDispatcher.EndpointAddress.Uri);
            DispatchOperation dispatchOperation = OperationContext.Current.EndpointDispatcher.DispatchRuntime.Operations.Where(op => op.Action == OperationContext.Current.IncomingMessageHeaders.Action).First();

            errorInfo = new ErrorInfo()
            {
                Address = endpoint.ListenUri.AbsoluteUri,
                Guid = guid.ToString(),
                Operation = dispatchOperation.Name,
                EndpointName = endpoint.Name
            };

            if (error != null && System.Web.HttpContext.Current != null)
                Elmah.ErrorSignal.FromContext(System.Web.HttpContext.Current).Raise(error);
            else
                log.Fatal(string.Format("Either 'error' parameter or 'System.Web.HttpContext.Current' is null. I cannot log error to elmah.", error, System.Web.HttpContext.Current)); 

            
            string errorMessage = error.Message;
            FaultCode faultCode = new FaultCode("Server"); 
            
            if (error.Message.StartsWith("The caller was not authenticated by the service") || error.Message.StartsWith("Access is denied"))
            {
                errorMessage = "Request is not authorized. Please try logging off and logging on again";
                faultCode = new FaultCode(FaultCodes.AuthorizationException.ToString()); 
                
            }
            else if (error is BusinessException)
            {
                faultCode = new FaultCode(FaultCodes.BusinessException.ToString()); 
            }
            else if (error is AuthorizationException)
            {
                errorMessage = "Request is not authorized. Please try logging off and logging on again";
                faultCode = new FaultCode(FaultCodes.AuthorizationException.ToString());
            }
            else if (error.Message.StartsWith("The creator of this fault did not specify a Reason"))
            {
                var key = OperationContext.Current.IncomingMessageHeaders.MessageId;
                string exception = ObjectService.ObjectServiceExceptionStore.GetException(key);
                errorMessage = exception ?? "An error occured please try again.";
                faultCode = new FaultCode(FaultCodes.BusinessException.ToString()); 
            }
            else
            {
                errorMessage = "An error occured. Please try again";
                faultCode = new FaultCode(FaultCodes.TechnicalException.ToString()); 
            }

            // MessageFault msgFault = newEx.CreateMessageFault();
            MessageFault msgFault = MessageFault.CreateFault(faultCode, new FaultReason(errorMessage), error.StackTrace); 
            
            fault = Message.CreateMessage(version, msgFault, null);
            
            MessageHeader<ErrorInfo> header = new MessageHeader<ErrorInfo>(errorInfo);
            MessageHeader untypedHeader = header.GetUntypedHeader("ErrorInfo", "http://services.enka.com/error");
            fault.Headers.Add(untypedHeader); 

            return;

        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //Instantiate new HeaderObject with values from ClientContext;
            var dataToSend = new ClaimsHeader
            {
                Token = ClaimsHeaderContext.HeaderInformation.Token,
                AccountId = ClaimsHeaderContext.HeaderInformation.AccountId,
                RequestId = ClaimsHeaderContext.HeaderInformation.RequestId
            };

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

            request.Headers.Add(untypedHeader);
            return null;
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //Instantiate new HeaderObject with values from ClientContext;
            var dataToSend = new PersonnelHeader
            {
                Database = ClientPersonnelHeaderContext.HeaderInformation.Database,
                LanguageId = ClientPersonnelHeaderContext.HeaderInformation.LanguageId
            };

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

            request.Headers.Add(untypedHeader);
            return 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;
        }
        private MessageHeader GetSecurityTokenHeader()
        {
            var securityTokeCookie = Request.Cookies.Get(COOKIE_SECURITY_TOKEN);
            //return MessageHeader.CreateHeader(MESSAGE_HEADER_SECURITY_TOKEN, MESSAGE_HEADER_NAMESPACE,securityTokeCookie != null ? securityTokeCookie.Value : string.Empty);

            var sessionTokenHeader = new MessageHeader<string>(securityTokeCookie != null ? securityTokeCookie.Value : string.Empty);
            return sessionTokenHeader.GetUntypedHeader(MESSAGE_HEADER_SECURITY_TOKEN, MESSAGE_HEADER_NAMESPACE);
        }
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     MessageHeader<CultureName> header = new MessageHeader<CultureName>(new CultureName(Thread.CurrentThread.CurrentUICulture.Name));
     request.Headers.Add(header.GetUntypedHeader(CultureName.LocalName, CultureName.Ns));
     return null;
 }