public object AfterReceiveRequest(ref Message request,
		                                  IClientChannel channel,
		                                  InstanceContext instanceContext)
        {
            OperationContext.Current.Extensions.Add(new WorkerContext());
            return request.Headers.MessageId;
        }
 public object AfterReceiveRequest(ref Message request,
     IClientChannel channel,
     InstanceContext instanceContext)
 {
     request = TraceHttpRequestMessage(request.ToHttpRequestMessage());
     return null;
 }
 public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     /* Add request Logging code here
      *  Message contents in request.ToString()
      */
     return null;
 }
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     var reply = request.Headers.ReplyTo;
     OperationContext.Current.OutgoingMessageHeaders.To = reply.Uri;
     OperationContext.Current.OutgoingMessageHeaders.RelatesTo = request.Headers.MessageId;
     return null;
 }
        public object AfterReceiveRequest(ref Message request,
               IClientChannel channel,
               InstanceContext instanceContext)
        {
            // Extract Cookie (name=value) from messageproperty
            var messageProperty = (HttpRequestMessageProperty)
                OperationContext.Current.IncomingMessageProperties[HttpRequestMessageProperty.Name];
            string cookie = messageProperty.Headers.Get("Set-Cookie");
            if (string.IsNullOrWhiteSpace(cookie))
                return null;

            string[] nameValue = cookie.Split('=', ',');
            string userName = string.Empty;

            // Set User Name from cookie
            int pos = nameValue.ToList().IndexOf(".ASPXAUTH");
            if (pos == -1)
                return null;

            userName = nameValue[pos + 1];

            // Set Thread Principal to User Name
            EnterpriseIdentity enterpriseIdentity = new EnterpriseIdentity();
            GenericPrincipal threadCurrentPrincipal =
                   new GenericPrincipal(enterpriseIdentity, new string[] { });
            enterpriseIdentity.IsAuthenticated = true;
            enterpriseIdentity.Name = userName;
            System.Threading.Thread.CurrentPrincipal = threadCurrentPrincipal;

            return null;
        }
Exemple #6
0
 /// <summary>Enables inspection or modification of a message before a request message is sent to a service.</summary>
 /// <param name="request">The message to be sent to the service.</param>
 /// <param name="channel">The  client object channel.</param>
 /// <returns>
 /// The object that is returned as the <c>correlationState</c> argument of the <see cref="M:System.ServiceModel.Dispatcher.IClientMessageInspector.AfterReceiveReply(System.ServiceModel.Channels.Message@,System.Object)"/> method. This is null if no correlation state is used.The best practice is to make this a <see cref="T:System.Guid"/> to ensure that no two <c>correlationState</c> objects are the same.
 /// </returns>
 public object BeforeSendRequest( ref Message request, IClientChannel channel )
 {
     var correlationState = Guid.NewGuid();
     this._logger.Trace( @"Request {{{0}}}:
     {1}", correlationState.ToString(), request.ToString() );
     return correlationState;
 }
        /// <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)
        {
            var header = MessageHeader.CreateHeader(Constants.ProtocolVersion, Constants.Namespace, Constants.SupportedProtocolVersion);
            request.Headers.Add(header);

            return null;
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            bool shouldCompressResponse = false;

            object propObj;
            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out propObj))
            {
                var prop = (HttpRequestMessageProperty)propObj;
                var accept = prop.Headers[HttpRequestHeader.Accept];
                if (accept != null)
                {
                    if (jsonContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Json;
                    }
                    else if (xmlContentTypes.IsMatch(accept))
                    {
                        WebOperationContext.Current.OutgoingResponse.Format = WebMessageFormat.Xml;
                    }
                }

                var acceptEncoding = prop.Headers[HttpRequestHeader.AcceptEncoding];
                if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
                {
                    shouldCompressResponse = true;
                }
            }

            return shouldCompressResponse;
        }
        /// <summary>
        ///     Called when an inbound message been received
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>
        ///     The object used to correlate stateMsg.
        ///     This object is passed back in the method.
        /// </returns>
        public object AfterReceiveRequest(ref Message request,
            IClientChannel channel,
            InstanceContext instanceContext)
        {
            StateMessage stateMsg = null;
            HttpRequestMessageProperty requestProperty = null;
            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                requestProperty = request.Properties[HttpRequestMessageProperty.Name]
                    as HttpRequestMessageProperty;
            }

            if (requestProperty != null)
            {
                var origin = requestProperty.Headers["Origin"];
                if (!string.IsNullOrEmpty(origin))
                {
                    stateMsg = new StateMessage();
                    // if a cors options request (preflight) is detected, 
                    // we create our own reply message and don't invoke any 
                    // operation at all.
                    if (requestProperty.Method == "OPTIONS")
                    {
                        stateMsg.Message = Message.CreateMessage(request.Version, null);
                    }
                    request.Properties.Add("CrossOriginResourceSharingState", stateMsg);
                }
            }

            return stateMsg;
        }
		public object BeforeSendRequest(ref Message request, IClientChannel channel)
		{
			var tokenInjector = ServiceLocator.Current.GetInstance<ISecurityTokenInjector>();

			if (tokenInjector != null)
			{
				object httpRequestMessageObject;

				if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
				{
					var httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;

					if (httpRequestMessage != null)
						tokenInjector.InjectToken(httpRequestMessage.Headers);
				}
				else
				{
					var httpRequestMessage = new HttpRequestMessageProperty();
					tokenInjector.InjectToken(httpRequestMessage.Headers);
					request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
				}
			}

			return null;
		}
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            CorsState state = null;
            HttpRequestMessageProperty responseProperty = null;
            if (request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
            {
                responseProperty = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            }

            if (responseProperty != null)
            {

                //Handle cors requests
                var origin = responseProperty.Headers["Origin"];
                if (!string.IsNullOrEmpty(origin))
                {
                    state = new CorsState();
                    //if a cors options request (preflight) is detected, we create our own reply message and don't invoke any operation at all.
                    if (responseProperty.Method == "OPTIONS")
                    {
                        state.Message = Message.CreateMessage(request.Version, FindReplyAction(request.Headers.Action), new EmptyBodyWriter());
                    }
                    request.Properties.Add(CrossOriginResourceSharingPropertyName, state);
                }
            }
            return state;
        }
 public ConversationViewModel(IClientChannel clientChannel,
                              IForegroundUpdateService foregroundUpdateService,
                              IVoipChannel voipChannel)
 {
     _clientChannel = clientChannel;
     _voipChannel = voipChannel;
     _foregroundUpdateService = foregroundUpdateService;
     foregroundUpdateService.OnRelayMessagesUpdated += OnRelayMessagesUpdated;
     foregroundUpdateService.OnVoipStateUpdate += OnVoipStateUpdate;
     foregroundUpdateService.OnFrameFormatUpdate += OnFrameFormatUpdate;
     foregroundUpdateService.OnFrameRateUpdate += OnFrameRateUpdate;
     SendInstantMessageCommand = new DelegateCommand(OnSendInstantMessageCommandExecute,
         OnSendInstantMessageCommandCanExecute);
     AudioCallCommand = new DelegateCommand(OnCallCommandExecute, OnCallCommandCanExecute);
     VideoCallCommand = new DelegateCommand(OnVideoCallCommandExecute, OnVideoCallCommandCanExecute);
     HangupCommand = new DelegateCommand(OnHangupCommandExecute, OnHangupCommandCanExecute);
     AnswerCommand = new DelegateCommand(OnAnswerCommandExecute, OnAnswerCommandCanExecute);
     RejectCommand = new DelegateCommand(OnRejectCommandExecute, OnRejectCommandCanExecute);
     CloseConversationCommand = new DelegateCommand(OnCloseConversationCommandExecute, () => _canCloseConversation);
     MuteMicrophoneCommand = new DelegateCommand(MuteMicCommandExecute, MicCommandCanExecute);
     UnMuteMicrophoneCommand = new DelegateCommand(UnMuteCommandExecute, MicCommandCanExecute);
     SwitchVideoCommand = new DelegateCommand(SwitchVideoCommandExecute, SwitchVideoCommandCanExecute);
     LayoutService.Instance.LayoutChanged += LayoutChanged;
     LayoutChanged(LayoutService.Instance.LayoutType);
     SetVideoPresenters();
 }
Exemple #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RosterViewModel"/> class.
        /// </summary>
        /// <param name="clientChannel">The client channel.</param>
        public RosterViewModel(IClientChannel clientChannel, LoginViewModel loginViewModel)
            : this()
        {
            if (clientChannel == null)
            {
                throw new ArgumentNullException("clientChannel");
            }

            if (clientChannel.State != SessionState.Established)
            {
                throw new ArgumentException("The session is in an invalid state");
            }

            _clientChannel = clientChannel;
            this.Identity = _clientChannel.LocalNode.ToIdentity();
            
            if (loginViewModel == null)
            {
                throw new ArgumentNullException("loginViewModel");
            }

            _loginViewModel = loginViewModel;

            _cancellationTokenSource = new CancellationTokenSource();
            _listenerTask = ListenAsync();

        }
        /// <summary>
        /// Gets a remote host service using the specified channel.
        /// </summary>
        /// <param name="channel">The channel.</param>
        /// <returns>The remote host service.</returns>
        public static IRemoteHostService GetRemoteHostService(IClientChannel channel)
        {
            if (channel == null)
                throw new ArgumentNullException("channel");

            return (IRemoteHostService)channel.GetService(typeof(IRemoteHostService), ServiceName);
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (request.Properties.ContainsKey("UriTemplateMatchResults"))
            {
                HttpRequestMessageProperty httpmsg = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
                UriTemplateMatch match = (UriTemplateMatch)request.Properties["UriTemplateMatchResults"];

                string format = match.QueryParameters["$format"];
                if ("json".Equals(format, StringComparison.InvariantCultureIgnoreCase))
                {
                    // strip out $format from the query options to avoid an error
                    // due to use of a reserved option (starts with "$")
                    match.QueryParameters.Remove("$format");

                    // replace the Accept header so that the Data Services runtime 
                    // assumes the client asked for a JSON representation
                    httpmsg.Headers["Accept"] = "application/json, text/plain;q=0.5";
                    httpmsg.Headers["Accept-Charset"] = "utf-8";

                    string callback = match.QueryParameters["$callback"];
                    if (!string.IsNullOrEmpty(callback))
                    {
                        match.QueryParameters.Remove("$callback");
                        return callback;
                    }
                }
            }

            return null;
        }
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
     request = buffer.CreateMessage();
     Console.WriteLine("Sending:\n{0}", buffer.CreateMessage().ToString());
     return request;
 }
        public static Log BuildLogRequest(ref Message request, IClientChannel channel)
        {
            string logName = request.Properties.ContainsKey("HttpOperationName")
                                 ? request.Properties["HttpOperationName"].ToString()
                                 : string.Empty;
            string serviceName = GetServiceName(request.Headers.To);
            var httpReq = (HttpRequestMessageProperty) request.Properties[HttpRequestMessageProperty.Name];
            string disableHeaderLog = httpReq.Headers["X-DisableHeaderLog"];
            serviceName = string.IsNullOrEmpty(serviceName) ? httpReq.Headers["X-ServiceName"] : serviceName;
            logName = string.IsNullOrEmpty(logName) ? httpReq.Headers["X-MethodName"] : logName;
            string errorElement = httpReq.Headers["X-SuccessElement"];
            var rq = new StringBuilder();
            if (string.IsNullOrEmpty(disableHeaderLog))
            {
                rq.AppendLine(string.Format("{0} {1}", httpReq.Method, request.Headers.To));
                foreach (string header in httpReq.Headers.AllKeys)
                {
                    rq.AppendLine(string.Format("{0}: {1}", header, httpReq.Headers[header]));
                }
                rq.AppendLine("------------------------------------------------------------");
            }

            if (!request.IsEmpty)
            {
                rq.AppendLine(MessageToString(ref request));
            }
            var log = new Log(logName, rq.ToString(), serviceName);
            log["SuccessElement"] = errorElement; // Used to set the status of the log after receiving response.
            return log;
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (!request.IsFault && !request.IsEmpty)
                LogRequest(ref request);

            return null;
        }
Exemple #20
0
 public object BeforeInvoke(InstanceContext instanceContext,
     IClientChannel channel,
     Message message)
 {
     UnitOfWork = Rhino.Commons.UnitOfWork.Start();
     return null;
 }
 public object BeforeSendRequest(
     ref Message request, 
     IClientChannel channel)
 {
     reqPayload = request.ToString();
     return null;
 }
 public static void End(IAsyncResult asyncResult, out string userName, out string password, out IClientChannel channel)
 {
     ClientPasswordAsyncResult thisPtr = AsyncResult.End<ClientPasswordAsyncResult>(asyncResult);
     userName = thisPtr.passwordForm.UserName;
     password = thisPtr.passwordForm.Password;
     channel = thisPtr.clientChannel;
 }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (!request.IsEmpty)
            {
                XmlReader bodyReader = request.GetReaderAtBodyContents().ReadSubtree();

                MemoryStream stream = new MemoryStream();
                XmlWriter writer = XmlWriter.Create(stream);

                if (transform == null)
                {
                    transform = new XslCompiledTransform(true);
                    var reader = XmlReader.Create(new StringReader(Properties.Resources.XmlCleaner));
                    transform.Load(reader);
                }
                transform.Transform(bodyReader, writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                bodyReader = XmlReader.Create(stream);

                Message changedMessage = Message.CreateMessage(request.Version, null, bodyReader);
                changedMessage.Headers.CopyHeadersFrom(request.Headers);
                changedMessage.Properties.CopyProperties(request.Properties);
                request = changedMessage;
            }

            return null;
        }
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var httpRequest = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
            var authorizationHeader = httpRequest.Headers["Authorization"];

            if (string.IsNullOrEmpty(authorizationHeader))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            string user;
            string password;

            this.ParseUserPasswordFromHeader(authorizationHeader, out user, out password);

            if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(password))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            var authenticationService = ObjectFactory.GetInstance<IAuthenticationService>();

            if (!authenticationService.Authenticate(user, password))
            {
                throw new HttpResponseException(HttpStatusCode.Unauthorized);
            }

            return instanceContext;
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestProperty = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

            NameValueCollection rawParameters = HttpUtility.ParseQueryString(request.Headers.To.Query);
            UriBuilder uriBuilder = new UriBuilder(request.Headers.To);
            uriBuilder.Query = Rfc3986.EncodeAndJoin(rawParameters);

            request.Headers.To = uriBuilder.Uri;

            OAuthConsumer consumer = new OAuthConsumer(_credentials.OAuthKey, _credentials.OAuthSecret);

            int unixTime = UnixTime.ToUnixTime(DateTime.UtcNow);

            OAuthParameters parameters = new OAuthParameters();
            parameters.Version = Constants.Version1_0;
            parameters.SignatureMethod = "RSA-SHA1";
            parameters.ConsumerKey = _credentials.OAuthKey;
            parameters.Token = _credentials.OAuthToken;
            parameters.TokenSecret = _credentials.OAuthTokenSecret;
            parameters.Timestamp = unixTime.ToString();
            parameters.Nonce = _nonceProvider.GenerateNonce(unixTime);

            RsaSha1SigningProvider provider = new RsaSha1SigningProvider();
            provider.PfxFile = _credentials.OAuthPfxFile;
            provider.PfxPassword = _credentials.OAuthPfxPassword;

            parameters.Sign(request.Headers.To, httpRequestProperty.Method, consumer, null, provider);

            httpRequestProperty.Headers["Authorization"] = parameters.ToHeaderFormat();

            return null;
        }
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     var logger = ObjectFactory.GetInstance<ILogger>();
     logger.StartAction(request.Headers.To.ToString());
     logger.Write("Incoming Message", request.ToString());
     return null;
 }
 public PokerServer(ICommandBus cmdBus, ITableProjection tableProjection, IPlayerConnectionMap playerConnectionMap, IClientChannel clientChannel)
 {
     _cmdBus = cmdBus;
     _tables = tableProjection;
     _playerConnectionMap = playerConnectionMap;
     _clientChannel = clientChannel;
 }
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     object httpRequestMessageObject;
     if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
     {
         HttpRequestMessageProperty httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
         if (httpRequestMessage != null)
         {
             httpRequestMessage.Headers[SERVICE_KEY_HTTP_HEADER] = (ServiceKey ?? string.Empty);
         }
         else
         {
             httpRequestMessage = new HttpRequestMessageProperty();
             httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (ServiceKey ?? string.Empty));
             request.Properties[HttpRequestMessageProperty.Name] = httpRequestMessage;
         }
     }
     else
     {
         HttpRequestMessageProperty httpRequestMessage = new HttpRequestMessageProperty();
         httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (ServiceKey ?? string.Empty));
         request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
     }
     return null;
 }
		public IAsyncResult BeginDisplayInitializationUI (
			IClientChannel channel,
			AsyncCallback callback,
			object state)
		{
			throw new NotImplementedException ();
		}
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            //LocDHT: Retrieve Inbound Object from Request, populate AuthenticationType,UserName,Password
            var header = request.Headers.GetHeader<PersonnelHeader>("personnel-header", "s");
            if (header != null)
            {
                var token = OperationContext.Current.ServiceSecurityContext.PrimaryIdentity;
                if (token.AuthenticationType == "Windows" ||
                    token.AuthenticationType == "Negotiate" ||
                    token.AuthenticationType == "NTLM") // windows authentication
                {
                    header.IsWindowAuthentication = true;
                    header.Username = ServiceSecurityContext.Current.PrimaryIdentity.Name;
                }
                else // UserName authentication
                {
                    header.IsWindowAuthentication = false;
                    header.Username = ServiceSecurityContext.Current.PrimaryIdentity.Name;
                    if (ServiceSecurityContext.Current.PrimaryIdentity is PersonnelIdentity)
                    {
                        header.Password = ((PersonnelIdentity)ServiceSecurityContext.Current.PrimaryIdentity).Password;
                    }
                }

                //CustomHeaderServerContextExtension.Current.CustomHeader = header;
                OperationContext.Current.IncomingMessageProperties.Add("PersonnelHeader", header);
            }

            return null;
        }
Exemple #31
0
        /// <summary>
        /// Перед отправкой сообщения включаем в заголовок информацию о текущей трассировке
        /// </summary>
        /// <param name="request">запрос</param>
        /// <param name="channel">канал</param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var scope = TraceContextScope.Current;

            if (scope == null)
            {
                return(null);
            }

            var action = request.Headers.Action;

            action = action.Replace("http://tempuri.org/", "");

            var id     = scope.Id;
            var @event = TraceEvent.Create(id: id
                                           , name: "call> " + action);

            var callScope = new TraceContextScope(id, @event, TraceContextMode.Add);

            var index = request.Headers.FindHeader(TraceMeHeader.HeaderName, Namespace.Main);

            if (index > -1)
            {
                request.Headers.RemoveAt(index);
            }

            var header = MessageHeader.CreateHeader(
                TraceMeHeader.HeaderName, Namespace.Main
                , new TraceMeHeader()
            {
                Id = id,
            });

            request.Headers.Add(header);
            return(callScope);
        }
Exemple #32
0
        void IDisposable.Dispose()
        {
            IClientChannel channel = null;

            if (this.simplexSessionChannel != null)
            {
                channel = (IClientChannel)this.simplexSessionChannel;
            }
            else if (this.duplexSessionChannel != null)
            {
                channel = (IClientChannel)this.duplexSessionChannel;
            }

            if (channel != null && channel.State != CommunicationState.Closed)
            {
                try
                {
                    // Close will abort the channel should an exception be thrown.
                    channel.Close();
                }
                catch (CommunicationException)
                { }
            }
        }
Exemple #33
0
        protected override void DisposeCore()
        {
            IClientChannel channel = (IClientChannel)_channel;

            UnhookChannel((ITaxiOnlineService)channel);
            try
            {
                if (channel.State != CommunicationState.Faulted)
                {
                    channel.Close();
                }
                else
                {
                    channel.Abort();
                }
            }
            catch (CommunicationException)
            {
                channel.Abort();
            }
            catch (TimeoutException)
            {
                channel.Abort();
            }
            catch (Exception)
            {
                channel.Abort();
                throw;
            }
            finally
            {
                channel  = null;
                _channel = null;
            }
            // _callbackInstance.Close();
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // prepare the data to sign
            string   operation = Regex.Match(request.Headers.Action, "[^/]+$").ToString();
            DateTime now       = DateTime.UtcNow;
            string   timestamp = now.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string   signMe    = operation + timestamp;

            byte[] bytesToSign = Encoding.UTF8.GetBytes(signMe);

            // sign the data
            byte[] secretKeyBytes = Encoding.UTF8.GetBytes(secretKey);
            HMAC   hmacSha256     = new HMACSHA256(secretKeyBytes);

            byte[] hashBytes = hmacSha256.ComputeHash(bytesToSign);
            string signature = Convert.ToBase64String(hashBytes);

            // add the signature information to the request headers
            request.Headers.Add(new AmazonHeader("AWSAccessKeyId", accessKeyId));
            request.Headers.Add(new AmazonHeader("Timestamp", timestamp));
            request.Headers.Add(new AmazonHeader("Signature", signature));

            return(null);
        }
Exemple #35
0
        public async Task <bool> ConnectWithPasswordAsync(Identity identity, string password, CancellationToken cancellationToken)
        {
            var tcpClient = new TcpClient();

#if DEBUG
            ITraceWriter traceWriter = new DebugTraceWriter("Client");
#else
            ITraceWriter traceWriter = new FileTraceWriter("client.log");
#endif

            var transport = new TcpTransport(
                new TcpClientAdapter(tcpClient),
                new EnvelopeSerializer(),
                hostName: _clientUri.Host,
                traceWriter: traceWriter
                );

            Channel = new ClientChannel(transport, TimeSpan.FromSeconds(60), autoReplyPings: true, autoNotifyReceipt: true);

            await Channel.Transport.OpenAsync(_clientUri, cancellationToken);

            var resultSession = await Channel.EstablishSessionAsync(
                c => c.First(),
                e => SessionEncryption.TLS,
                identity,
                (s, r) => { var auth = new PlainAuthentication(); auth.SetToBase64Password(password); return(auth); },
                Environment.MachineName,
                cancellationToken);

            if (resultSession.State != SessionState.Established)
            {
                return(false);
            }

            return(true);
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            object existingMessageProperty;

            HttpRequestMessageProperty requestMessageProperty;

            if (!request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out existingMessageProperty))
            {
                requestMessageProperty = new HttpRequestMessageProperty();

                request.Properties.Add(HttpRequestMessageProperty.Name, requestMessageProperty);
            }
            else
            {
                requestMessageProperty = existingMessageProperty as HttpRequestMessageProperty;
            }

            if (requestMessageProperty != null)
            {
                requestMessageProperty.Headers[_headerName] = _headerValue;
            }

            return(null);
        }
Exemple #37
0
        public object BeforeSendRequest(ref Message request,
                                        IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage = null;
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;
            }

            if (httpRequestMessage == null)
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }

            foreach (var header in _headers)
            {
                httpRequestMessage.Headers[header.Key] = header.Value;
            }

            return(null);
        }
Exemple #38
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            var action = request.Headers.Action;

            currentAction.Value = action;

            var policy          = OperationPolicy.GetPolicyForAction(action);
            var transformer     = new MessageTransformer(request);
            var requestDocument = transformer.GetXmlDocument();

            if (debug)
            {
                Console.WriteLine("### Request not wrapped: " + XmlUtil.PrettyXml(requestDocument));
            }
            securityService.WrapRequest(requestDocument, policy);

            if (debug)
            {
                Console.WriteLine("### Request wrapped: " + XmlUtil.AsText(requestDocument));
            }

            request = transformer.ToMessage(requestDocument);
            return(null);
        }
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     if (channel is IServiceChannel serviceChannel)
     {
         if (serviceChannel.ListenUri.Scheme == "net.tcp")
         {
             string   methodName  = request.Headers.Action.Split('/').Last();
             TypeInfo serviceType = instanceContext.Host.Description.ServiceType as TypeInfo;
             foreach (var @interface in serviceType.ImplementedInterfaces)
             {
                 var method = @interface.GetMethod(methodName);
                 if (method != null)
                 {
                     var attributes = method.GetCustomAttributes().Where(x => x.GetType() == typeof(WcfAllowedAttribute)).FirstOrDefault();
                     if (attributes == null)
                     {
                         throw new OnyWebApiException($"Method which was invoked: {methodName}");
                     }
                 }
             }
         }
     }
     return(request);
 }
        object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // Add Query Options if any are set
            var messageProperties = OperationContext.Current?.OutgoingMessageProperties;

            if (messageProperties != null)
            {
                messageProperties.TryGetValue(QueryPropertyName, out object queryProperty);
                messageProperties.TryGetValue(IncludeTotalCountPropertyName, out object includeTotalCountProperty);

                // Add Query Options header if any options were specified
                if (queryProperty != null || includeTotalCountProperty != null)
                {
                    var queryParts = queryProperty != null?QuerySerializer.Serialize((IQueryable)queryProperty) : null;

                    var includeTotalCount = (bool?)includeTotalCountProperty;

                    var header = new QueryOptionsHeader(queryParts, includeTotalCount == true);
                    request.Headers.Add(header);
                }
            }

            return(null);
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage;
            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {
                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;

                if (httpRequestMessage != null && string.IsNullOrEmpty(httpRequestMessage.Headers["user-agent"]))
                {
                    httpRequestMessage.Headers["user-agent"] = _userAgent;
                }
            }
            else
            {
                httpRequestMessage = new HttpRequestMessageProperty();
                httpRequestMessage.Headers.Add("user-agent", _userAgent);
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }


            return(null);
        }
        public object AfterReceiveRequest(ref Message message, IClientChannel channel, InstanceContext instanceContext)
        {
            Console.WriteLine("AfterReceiveRequest");

            MessageBuffer buffer = message.CreateBufferedCopy(int.MaxValue);

            message = buffer.CreateMessage();

            Message messageCopy = buffer.CreateMessage();
            string  contents;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                XmlWriter writer = XmlWriter.Create(memoryStream);
                messageCopy.WriteMessage(writer);
                writer.Flush();

                memoryStream.Position = 0;
                contents = new StreamReader(memoryStream).ReadToEnd();
            }

            LogFile(contents, "Request");
            return(null);
        }
Exemple #43
0
        /// <summary>
        /// После принятия запроса если присутствует флаг TraceMe, создаем окружение трассировки
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <param name="instanceContext"></param>
        /// <returns></returns>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            var index = request.Headers.FindHeader(TraceMeHeader.HeaderName, Namespace.Main);

            if (index < 0)
            {
                return(null);
            }

            var header = request.Headers.GetHeader <TraceMeHeader>(index);

            if (header == null)
            {
                return(null);
            }

            var @event = TraceEvent.Create(
                id: header.Id
                , name: "disp> " + instanceContext.Host.Description.Name);

            @event["host"] = HostName;

            return(new TraceContextScope(header.Id, @event, TraceContextMode.Add));
        }
Exemple #44
0
        public async Task AddBuiltHandler_SingleHandler_ShouldExecuteHandler()
        {
            // Arrange
            _transport.Setup(t => t.IsConnected).Returns(true);
            IClientChannel handlerClientChannel     = null;
            var            handlerCancellationToken = default(CancellationToken);
            Func <IClientChannel, CancellationToken, Task> builtHandler = (clientChannel, cancellationToken) =>
            {
                handlerClientChannel     = clientChannel;
                handlerCancellationToken = cancellationToken;
                return(TaskUtil.CompletedTask);
            };

            var target = GetTarget();

            // Act
            target.AddBuiltHandler(builtHandler);
            var channel = await target.BuildAsync(_cancellationToken);

            // Assert
            handlerClientChannel.ShouldNotBeNull();
            handlerClientChannel.ShouldBe(channel);
            handlerCancellationToken.ShouldBe(_cancellationToken);
        }
Exemple #45
0
        /// <summary>
        /// Called after an inbound message has been received but before the message is dispatched
        /// to the intended operation.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>
        /// The object used to correlate state.
        /// This object is passed back in the <see cref="IDispatchMessageInspector.BeforeSendReply"/> method.
        /// </returns>
        public object AfterReceiveRequest(
            ref Message request,
            IClientChannel channel,
            InstanceContext instanceContext)
        {
            var httpRequest = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
            var origin      = httpRequest?.Headers[Constants.Origin];

            if (origin == null)
            {
                return(null);
            }

            var operationName = (string)request.Properties[WebHttpDispatchOperationSelector.HttpOperationNamePropertyName];

            if (operationName == null)
            {
                return(null);
            }

            if (!_corsEnabledOperationsNames.Contains(operationName, StringComparer.OrdinalIgnoreCase))
            {
                Facility.LogWriter.LogError($"Failing CORS because the request operation {operationName} is not allowed.");
                VmAspectsEventSource.Log.CorsOperationNotAllowed(operationName);
                return(null);
            }

            if (_allowedOrigins != null && _allowedOrigins.Any() && !_allowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase))
            {
                Facility.LogWriter.LogError($"Failing CORS because the request origin {origin} is not explicitly allowed.");
                VmAspectsEventSource.Log.CorsOriginNotAllowed(origin);
                return(null);
            }

            return(origin);
        }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            //remove extra tags VsDebuggerCausalityData
            int limit = request.Headers.Count;

            for (int i = 0; i < limit; ++i)
            {
                if (request.Headers[i].Name.Equals("VsDebuggerCausalityData"))
                {
                    request.Headers.RemoveAt(i);
                    break;
                }
            }

            string st = GetSignElement(MessageString(ref request));

            //place for log request

            //File.AppendAllText(@"LogRequest.txt", st + Environment.NewLine, Encoding.Default);

            request = CreateMessageFromString(st, request.Version);

            return(null);
        }
Exemple #47
0
        public void Intercept(IInvocation invocation)
        {
            var backendWsHttpBinding = new BasicHttpBinding();
            var address = new EndpointAddress("http://localhost:64013/Service1.svc");

            var channelFactory = new ChannelFactory <TService>(backendWsHttpBinding, address);

            IClientChannel channel = channelFactory.CreateChannel() as IClientChannel;

            if (channel != null)
            {
                try
                {
                    var response = invocation.Method.Invoke(channel, invocation.Arguments);
                    invocation.ReturnValue = response;
                    channel.Close();
                }
                catch (Exception e)
                {
                    channel.Abort();
                    Console.WriteLine("Error...");
                }
            }
        }
Exemple #48
0
 public IAsyncResult BeginWhisper(string from, long fromCID, string to, string message, AsyncCallback callback, object asyncState)
 {
     if (this.proxy != null)
     {
         try
         {
             return(this.proxy.BeginAsyncWhisper(from, fromCID, to, message, callback, asyncState));
         }
         catch (Exception ex)
         {
             if (this.Logger != null)
             {
                 this.Logger.Fatal("Fail to BeginWhisper", ex);
             }
             IClientChannel clientChannel = this.proxy as IClientChannel;
             if (clientChannel.State == CommunicationState.Faulted)
             {
                 clientChannel.Abort();
             }
             return(null);
         }
     }
     throw new Exception("No Service is connected");
 }
Exemple #49
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            string messageFileName = string.Format("{0}Log{1:000}_Incoming.txt", MessageLogFolder, Interlocked.Increment(ref messageLogFileIndex));
            Uri    requestUri      = request.Headers.To;

            using (StreamWriter sw = File.CreateText(messageFileName))
            {
                HttpRequestMessageProperty httpReq = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

                sw.WriteLine("{0} {1}", httpReq.Method, requestUri);
                foreach (var header in httpReq.Headers.AllKeys)
                {
                    sw.WriteLine("{0}: {1}", header, httpReq.Headers[header]);
                }

                if (!request.IsEmpty)
                {
                    sw.WriteLine();
                    sw.WriteLine(this.MessageToString(ref request));
                }
            }

            return(requestUri);
        }
Exemple #50
0
        public object AfterReceiveRequest(ref Message request, IClientChannel channel,
                                          InstanceContext instanceContext)
        {
            try
            {
                ProfilingObject pObject = new ProfilingObject
                {
                    action = OperationContext.Current.IncomingMessageHeaders.Action.Split('/').ToList().Last(),
                    timer  = new AbcTimer()
                };

                logger.write("RPC call '{0}' started", pObject.action);
                pObject.timer.Start();

                return(pObject);
            } catch (Exception) {
                ProfilingObject pObject = new ProfilingObject {
                    timer = new AbcTimer(), action = "Unknown"
                };
                logger.write("RPC call '{0}' started", pObject.action);
                pObject.timer.Start();
                return(pObject);
            }
        }
Exemple #51
0
        /// <summary>
        /// After receiving a request, do any message stuff here
        /// </summary>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            try
            {
                this.m_traceSource.TraceEvent(TraceEventType.Verbose, 0, "Received request from {0} : {1} {2} ({3})", (OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty)?.Address.ToString(),
                                              WebOperationContext.Current.IncomingRequest.Method,
                                              WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri,
                                              WebOperationContext.Current.IncomingRequest.UserAgent);

                // Handle compressed requests
                var compressionScheme = CompressionUtil.GetCompressionScheme(WebOperationContext.Current.IncomingRequest.Headers[System.Net.HttpRequestHeader.ContentEncoding]);
                if (compressionScheme != null)
                {
                    CompressionUtil.DeCompressMessage(ref request, compressionScheme, this.GetContentFormat(request));
                }

                return(null);
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(TraceEventType.Error, e.HResult, e.ToString());
                return(null);
            }
        }
Exemple #52
0
        /// <summary>
        /// Inspects inbound message headers and adds an
        /// <see cref="TenantIdentificationContextExtension"/>
        /// to the current operation context with the tenant ID.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>
        /// Always returns <see langword="null" />. There is no correlation state
        /// value to be managed in this inspector.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown if <paramref name="request" /> is <see langword="null" />.
        /// </exception>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var context = OperationContext.Current;

            try
            {
                var tenantId = request.Headers.GetHeader <TTenantId>(TenantHeaderName, TenantHeaderNamespace);
                context.Extensions.Add(new TenantIdentificationContextExtension {
                    TenantId = tenantId
                });
            }
            catch (MessageHeaderException)
            {
                // The additional header won't be there when we update service
                // references; only when the behavior is on the client end.
            }

            return(null);
        }
 object IClientMessageInspector.BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     return(null);
 }
Exemple #54
0
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     return(null);
 }
Exemple #55
0
 public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
 {
     return(null);
 }
 /// <summary>
 /// Sets up timeouts.
 /// </summary>
 /// <param name="channel"></param>
 void SetupTimeout(IClientChannel channel)
 {
     channel.OperationTimeout = new TimeSpan(0, 0, 0, 0, _messageTimeout);
 }
 /// <summary>
 /// 对调用请求进行拦截
 /// </summary>
 /// <remarks>这里是是在消息头增加一些额外信息</remarks>
 /// <param name="request"></param>
 /// <param name="channel"></param>
 /// <returns></returns>
 public object BeforeSendRequest(ref Message request, IClientChannel channel)
 {
     request.Headers.Add(MessageHeader.CreateHeader(Key, string.Empty, Signature));
     return(null);
 }
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            string      messageRef = MessageString(ref request);
            XmlDocument docRequest = new XmlDocument();

            docRequest.LoadXml(messageRef);

            WsdlServiceHandle.RequestType type;
            DateTime?dateTime = null;
            string   lnNum    = string.Empty;
            string   lnSnils  = string.Empty;

            if (messageRef.Contains("getLNListByDate"))
            {
                type = WsdlServiceHandle.RequestType.GetLnListByDate;

                XmlNodeList nodeDate = docRequest.GetElementsByTagName("date");
                if (nodeDate != null && nodeDate.Count == 1)
                {
                    dateTime = DateTime.Parse(nodeDate[0].InnerText);
                }
            }
            else if (messageRef.Contains("getLNData"))
            {
                type = WsdlServiceHandle.RequestType.GetLnData;

                XmlNodeList nodeLnCode = docRequest.GetElementsByTagName("lnCode");
                if (nodeLnCode != null && nodeLnCode.Count == 1)
                {
                    lnNum = nodeLnCode[0].InnerText;
                }

                XmlNodeList nodeLnSnils = docRequest.GetElementsByTagName("snils");
                if (nodeLnSnils != null && nodeLnCode.Count == 1)
                {
                    lnSnils = nodeLnSnils[0].InnerText;
                }
            }
            else
            {
                throw new Exception("Неподдерживаемый тип запроса");
            }

            XmlDocument docCustomSigned    = WsdlServiceHandle.GetSignedRequestXml(type, dateTime, lnNum, lnSnils);
            XmlDocument docCustomEncrypted =
                CryptoTools.EncryptionXML(docCustomSigned, WsdlServiceHandle.fssCert, WsdlServiceHandle.userCert);

            request = CreateMessageFromString(docCustomEncrypted.OuterXml, request.Version);



            //var _url = "https://docs.fss.ru/WSLnCryptoV11/FileOperationsLnPort?WSDL";
            //var _action = "http://ru/ibs/fss/ln/ws/FileOperationsLn.wsdl/getLNListByDate";

            ////XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
            //HttpWebRequest webRequest = CreateWebRequest(_url, _action);
            //InsertSoapEnvelopeIntoWebRequest(docCustomEncrypted, webRequest);

            //// begin async call to web request.
            //IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);

            //// suspend this thread until call is complete. You might want to
            //// do something usefull here like update your UI.
            //asyncResult.AsyncWaitHandle.WaitOne();

            //// get the response from the completed web request.
            //string soapResult;
            //using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult)) {
            //	using (StreamReader rd = new StreamReader(webResponse.GetResponseStream())) {
            //		soapResult = rd.ReadToEnd();
            //	}
            //	Console.Write(soapResult);
            //}



            return(request);
        }
Exemple #59
0
 public static void SetInstanceId(IClientChannel innerChannel, Guid instanceId)
 {
     SetContext(innerChannel, InstanceIdKey, instanceId.ToString());
 }
Exemple #60
0
 //Called by the client to write context over context bindings
 public static void SetContext(IClientChannel innerChannel, string key, string value)
 {
     SetContext(innerChannel, UpdateContext(innerChannel, key, value));
 }