Example #1
0
        public static void SetHeader(IContextChannel channel, T header)
        {
            MessageHeader <T>     messageHeader         = new MessageHeader <T>(header);
            OperationContextScope operationContextScope = new OperationContextScope(channel);

            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader.GetUntypedHeader(typeof(T).ToString(), typeof(T).Namespace));
        }
        /// <summary>
        /// This implements a PerCall InstanceContextMode behavior. If a cached InstanceContext is not found
        /// then WCF will create a new one.
        /// </summary>     
        public InstanceContext GetExistingInstanceContext(System.ServiceModel.Channels.Message message, IContextChannel channel)
        {
            //Per Session behavior
            //To implement a PerSession behavior (If underlyin binding supports it) where in all
            //methods from one ChannelFactory will be serviced by the same InstanceContext

            //Check if the incoming request has the InstanceContext id it wants to connect with.
            if (message.Headers.FindHeader(CustomHeader.HeaderName, CustomHeader.HeaderNamespace) != -1)
            {
                String sharingId = message.Headers.GetHeader<string>(CustomHeader.HeaderName, CustomHeader.HeaderNamespace);
                if (sharingId != null && instanceContextCache.ContainsKey(sharingId))
                {
                    Utility.WriteMessageToConsole(String.Format(ResourceHelper.GetString("InstanceContextLookup"),sharingId));
                    //Retrieve the InstanceContext from the map
                    InstanceContext context = instanceContextCache[sharingId];
                    if (context != null)
                    {
                        //Before returning, stop the timer on this InstanceContext
                        CustomLeaseExtension extension = context.Extensions.Find<CustomLeaseExtension>();
                        Utility.WriteMessageToConsole(String.Format(ResourceHelper.GetString("StopInstanceContextIdleTimer"), sharingId));
                        extension.StopTimer();

                        Utility.WriteMessageToConsole(ResourceHelper.GetString("CachedInstanceContextFound"));
                        return instanceContextCache[sharingId];
                    }
                }
            }

            //No existing InstanceContext was found so return null and WCF will create a new one.
            return null;
        }
		public InstanceContext GetExistingInstanceContext (Message message, IContextChannel channel)
		{
			if (message.Headers.Action != "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get")
				return null;

			return ctx;
		}
Example #4
0
        public string ServerUrlForChannel(IContextChannel channel)
        {
            bool   needSanitizeItemName;
            string codePage;

            return(ServerUrlForChannel(channel, out needSanitizeItemName, out codePage));
        }
Example #5
0
        public IDXVCSService CreateService(string serviceUrl)
        {
            if (isServiceRegistered)
            {
                try {
                    int version = service.GetServiceVersion();
                    return(service);
                }
                catch {
                }
            }
            EndpointAddress myEndpointAddress      = new EndpointAddress(new Uri(serviceUrl), new SpnEndpointIdentity(String.Empty));
            ServiceEndpoint point                  = GZipMessageEncodingBindingElement.CreateEndpoint(myEndpointAddress);
            ChannelFactory <IDXVCSService> factory = new Factory(point);

            factory.Credentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Identification;
            IDXVCSService   newService = factory.CreateChannel();
            IContextChannel newChannel = (IContextChannel)newService;

            newChannel.OperationTimeout = TimeSpan.MaxValue;
            newChannel.Open();
            service             = newService;
            isServiceRegistered = true;
            service             = new ServiceWrapper(newService);
            return(service);
        }
        public void UnSubscribe(int clientId)
        {
            IPublishing     registeredUser = null;
            IContextChannel channel        = null;
            DateTime        value;

            bool result = false;

            if (!_callbackList.Contains(new KeyValuePair <int, IPublishing>(clientId, registeredUser)))
            {
                result = _callbackList.TryRemove(clientId, out registeredUser);
                if (result == true)
                {
                    result = _callbackListChannelByClientId.TryRemove(clientId, out channel);
                    if (result == true)
                    {
                        result = _callbackListClientIdByChannel.TryRemove(channel, out clientId);
                        result = _clientKeepAliveMessageByClientId.TryRemove(clientId, out value);
                        LogServer.LogStatus(STT.General.INFO_GENERAL, "client id:" + clientId + " was removed.");
                    }
                }
            }
            else
            {
                LogServer.LogStatus(STT.General.INFO_GENERAL, "unable to remove client id:" + clientId);
            }
        }
Example #7
0
        public OperationContext(IContextChannel channel)
        {
            if (channel == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("channel"));
            }

            ServiceChannel serviceChannel = channel as ServiceChannel;

            //Could be a TransparentProxy
            if (serviceChannel == null)
            {
                serviceChannel = ServiceChannelFactory.GetServiceChannel(channel);
            }

            if (serviceChannel != null)
            {
                this.outgoingMessageVersion = serviceChannel.MessageVersion;
                this.channel = serviceChannel;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxInvalidChannelToOperationContext)));
            }
        }
Example #8
0
        public void Connect(string name)
        {
            ICallBackIService1 Callbackchannel = OperationContext.Current.GetCallbackChannel <ICallBackIService1>();
            IContextChannel    channel         = OperationContext.Current.Channel;

            channel.Faulted += new EventHandler(Channel_Faulted);
            channel.Closed  += new EventHandler(Channel_Faulted);

            if (Channels.Where(a => a.Item1 == name).Count() == 0)
            {
                Channels.Add(new Tuple <string, IContextChannel, ICallBackIService1>(name, channel, Callbackchannel));
                //  Callbackchannel.Updatestatus("A user with name '" + name + "' Connected .\r\n");

                foreach (var ch in Channels)
                {
                    ch.Item3.GetMessage(name + " join" + "\r\n");
                }
                //  return true;
            }
            else
            {
                Callbackchannel.Updatestatus("A user with name '" + name + "' already exists.\r\n");
                // return false;
            }
        }
Example #9
0
 protected CremaServiceItemBase(ILogService logService)
 {
     this.logService = logService;
     this.host       = OperationContext.Current.Host;
     this.channel    = OperationContext.Current.Channel;
     this.sessionID  = OperationContext.Current.Channel.SessionId;
 }
Example #10
0
 public virtual void Dispose()
 {
     this.host    = null;
     this.channel = null;
     this.OnDisposed(EventArgs.Empty);
     this.logService.Debug($"[{this.OwnerID}] {this.GetType().Name} {nameof(IDisposable.Dispose)}");
 }
Example #11
0
        public EchoService()
        {
            IContextChannel channel = OperationContext.Current?.Channel;

            this.trackingId = channel?.GetProperty <TrackingContext>()?.TrackingId;
            RelayTraceSource.TraceVerbose($"{nameof(EchoService)} instance created. TrackingId:{this.trackingId}");
        }
Example #12
0
        /// <summary>
        /// 当有客户端连接时,会调用此方法注册
        /// </summary>
        /// <param name="userName"></param>
        public void Login(string userName)
        {
            IChatToClient   client = OperationContext.Current.GetCallbackChannel <IChatToClient>();
            string          key    = OperationContext.Current.SessionId;
            IContextChannel chanel = OperationContext.Current.Channel;

            chanel.Closed += (sender, e) => { if (ClientClosedEvent != null)
                                              {
                                                  ClientClosedEvent(sender, e);
                                              }
            };
            //检查是否有离线用户
            var users = LstUser.Where(x => x.Chanel.State != CommunicationState.Opened);

            if (users != null && users.Count() > 0)
            {
                mainDispatcher.Invoke(new Action(() => users.ToList().ForEach(x => LstUser.Remove(x))));
            }
            //将用户加入进去
            User user = new User()
            {
                Client = client, Key = key, Chanel = chanel, UserName = userName
            };
            var existUser = LstUser.Where(x => x.Key == user.Key);

            if (existUser != null && existUser.Count() > 0)
            {
                return;
            }
            mainDispatcher.Invoke(new Action(() => LstUser.Add(user)));
            if (this.LoginEvent != null)
            {
                this.LoginEvent(key, userName);
            }
        }
Example #13
0
        /// <summary>
        /// Determines if the context channel object is in an alive state
        /// </summary>
        /// <param name="channel">Channel to test</param>
        /// <returns>true if alive, false otherwise</returns>
        private static bool IsAlive(IContextChannel channel)
        {
            try
            {
                if (channel == null)
                {
                    return(false);
                }
                CommunicationState state = channel.State;
                switch (state)
                {
                case CommunicationState.Closed:
                case CommunicationState.Closing:
                case CommunicationState.Faulted:
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", MethodBase.GetCurrentMethod().DeclaringType.Namespace, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name));
                return(false);
            }
        }
Example #14
0
        /// <summary>
        /// A channel has transitioned to the faulted state
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void channel_Faulted(object sender, EventArgs e)
        {
            try
            {
                IContextChannel channel = sender as IContextChannel;
                if (channel != null)
                {
                    string typeName = channel.GetType().FullName;
                    if (Channels.ContainsKey(typeName))
                    {
                        Channels.Remove(typeName);
                    }

                    System.Diagnostics.Debug.WriteLine(string.Format("{0} is in the faulted state.", typeName), string.Format("{0}.{1}.{2}", MethodBase.GetCurrentMethod().DeclaringType.Namespace, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name));
                    try
                    {
                        channel.Abort();
                    }
                    catch
                    {
                        // No op...
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message, string.Format("{0}.{1}.{2}", MethodBase.GetCurrentMethod().DeclaringType.Namespace, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name));
            }
        }
Example #15
0
        /// <summary>
        /// Valida se canal de callback eh valido
        /// </summary>
        /// <param name="callback">instancia do callback, retornada em GetCallback[T}()</param>
        /// <returns>true, se o ChannelState = Opened </returns>
        public static bool IsValidChannel(object callback)
        {
            bool bRet = false;

            if (callback != null)
            {
                lock (_clientChannels)
                {
                    if (_clientChannels.ContainsKey(callback))
                    {
                        IContextChannel channel = (IContextChannel)_clientChannels[callback];
                        if (channel.State == CommunicationState.Opened)
                        {
                            bRet = true;
                        }
                        else
                        {
                            channel.Abort();
                            _clientChannels.Remove(callback);
                            return(false);
                        }
                    }
                }
            }

            return(bRet);
        }
Example #16
0
        public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            InstanceContext instanceContext = base.GetExistingInstanceContext(message, channel);

            if (instanceContext != null && this.InstanceLifeTimeManager != null)
            {
                WorkflowDurableInstance workflowDurableInstance = instanceContext.Extensions.Find <WorkflowDurableInstance>();

                if (workflowDurableInstance == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new InvalidOperationException(
                                  SR2.GetString(
                                      SR2.RequiredInstanceContextExtensionNotFound,
                                      typeof(WorkflowDurableInstance).Name)));
                }

                this.InstanceLifeTimeManager.NotifyWorkflowActivationComplete(
                    workflowDurableInstance.InstanceId,
                    this.workflowActivationCompleteCallback,
                    new WorkflowActivationCompletedCallbackState
                    (
                        workflowDurableInstance.InstanceId,
                        instanceContext),
                    false);
            }

            return(instanceContext);
        }
Example #17
0
 public OperationContextScope(IContextChannel channel)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope   = currentScope;
     this.thread          = Thread.CurrentThread;
     this.PushContext(new OperationContext(channel));
 }
        public virtual InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            if (channel == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel");
            }

            Guid instanceId = GetInstanceIdFromMessage(message);
            InstanceContext result = null;

            if (instanceId != Guid.Empty) //Not an activation request.
            {
                if (contextCache.TryGetInstanceContext(instanceId, out result))
                {
                    lock (result.ThisLock)
                    {
                        if (!string.IsNullOrEmpty(channel.SessionId) && !result.IncomingChannels.Contains(channel))
                        {
                            result.IncomingChannels.Add(channel);
                        }
                    }
                    return result;
                }
            }
            return result;
        }
        public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            Fx.Assert(message != null, "Null message");
            Fx.Assert(channel != null, "Null channel");

            return new InstanceContext(this.serviceHostBase);
        }
        public virtual InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            if (channel == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel");
            }

            Guid            instanceId = GetInstanceIdFromMessage(message);
            InstanceContext result     = null;

            if (instanceId != Guid.Empty) //Not an activation request.
            {
                if (contextCache.TryGetInstanceContext(instanceId, out result))
                {
                    lock (result.ThisLock)
                    {
                        if (!string.IsNullOrEmpty(channel.SessionId) && !result.IncomingChannels.Contains(channel))
                        {
                            result.IncomingChannels.Add(channel);
                        }
                    }
                    return(result);
                }
            }
            return(result);
        }
 public OperationContextScope(IContextChannel channel)
 {
     this.originalContext = OperationContext.Current;
     this.originalScope = currentScope;
     this.thread = Thread.CurrentThread;
     this.PushContext(new OperationContext(channel));
 }
        public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            InstanceContext ctx;
            var             key = message.Headers.RelatesTo;

            return(key != null && pool.TryGetValue(key, out ctx) ? ctx : null);
        }
Example #23
0
        RoutingService()
        {
            this.SessionMessages = new List <MessageRpc>(1);

            //We only need to call this here if we trace in this method.  BeginXXX methods call it again.
            //FxTrace.Trace.SetAndTraceTransfer(this.ActivityID, true);

            this.operationContext = OperationContext.Current;
            if (Fx.Trace.IsEtwProviderEnabled)
            {
                this.eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(this.operationContext.IncomingMessage);
            }

            IContextChannel channel = this.operationContext.Channel;

            ServiceHostBase host = this.operationContext.Host;

            this.ChannelExtension = channel.Extensions.Find <RoutingChannelExtension>();
            if (this.ChannelExtension == null)
            {
                throw FxTrace.Exception.AsError(new ConfigurationErrorsException(SR2.RoutingExtensionNotFound));
            }

            this.RoutingConfig = host.Extensions.Find <RoutingExtension>().RoutingConfiguration;
            this.RoutingConfig.VerifyConfigured();
            this.ChannelExtension.AttachService(this);
        }
Example #24
0
        public ServerService()
            : base()
        {
            try
            {
                sessionId = Guid.Parse(OperationContext.Current.IncomingMessageHeaders
                    .GetHeader<string>("SessionId", string.Empty));

                using (var session = SessionProvider.OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    currentUser = session.CreateCriteria<User>()
                        .Add(Restrictions.Eq("SessionId", sessionId))
                        .SetMaxResults(1)
                        .UniqueResult<User>();
                }
            }
            catch { }

            logger.Debug("Создан новый экземпляр службы [{0}]", sessionId);

            channel = OperationContext.Current.Channel;
            channel.Faulted += channel_Faulted;
            channel.Closing += channel_Closing;
        }
Example #25
0
        protected void ExecuteClientActionInOCS(object input, string operationDescription, Action <string> action, Func <string, Operation> waitOperation)
        {
            IContextChannel contextChannel = Channel as IContextChannel;

            if (contextChannel != null)
            {
                using (new OperationContextScope(contextChannel))
                {
                    try
                    {
                        RetryCall(action);
                        Operation operation = waitOperation(operationDescription);
                        var       context   = new ManagementOperationContext
                        {
                            OperationDescription = operationDescription,
                            OperationId          = operation.OperationTrackingId,
                            OperationStatus      = operation.Status
                        };

                        WriteObject(context, true);
                    }
                    catch (CommunicationException ex)
                    {
                        WriteErrorDetails(ex);
                    }
                }
            }
            else
            {
                RetryCall(action);
            }
        }
        public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            InstanceContext ctx;
            var             key = channel.SessionId ?? String.Empty;

            return(pool.TryGetValue(key, out ctx) ? ctx : null);
        }
Example #27
0
        protected void ExecuteClientActionInOCS <TResult>(object input, string operationDescription, Func <string, TResult> action, Func <string, Operation> waitOperation, Func <Operation, TResult, object> contextFactory) where TResult : class
        {
            IContextChannel contextChannel = Channel as IContextChannel;

            if (contextChannel != null)
            {
                using (new OperationContextScope(contextChannel))
                {
                    try
                    {
                        TResult   result    = RetryCall(action);
                        Operation operation = waitOperation(operationDescription);
                        if (result != null)
                        {
                            object context = contextFactory(operation, result);
                            WriteObject(context, true);
                        }
                    }
                    catch (CommunicationException ex)
                    {
                        WriteErrorDetails(ex);
                    }
                }
            }
            else
            {
                TResult result = RetryCall(action);
                if (result != null)
                {
                    WriteObject(result, true);
                }
            }
        }
Example #28
0
        /// <summary>
        /// Closes this WCF Service instance.
        /// </summary>
        /// <param name="isFaulted">if set to <c>true</c> [is faulted].</param>
        protected virtual void CleanUp(bool isFaulted)
        {
            // Similar to IDisposable we will only execute unsubscribe once, whatever comes first
            lock (this)
            {
                if (Closed)
                {
                    return;
                }

                // Clean up internal connections
                Closed = true;
                ServiceManager.Unregister(this);

                // Close wcf channel
                _channel.Closed  -= OnChannelClosed;
                _channel.Faulted -= OnChannelFaulted;

                try
                {
                    // abort in every case so the client gets a message in every case that the connection is not available anymore
                    _channel.Abort();
                }
                finally
                {
                    _channel = null;
                }
            }
        }
        public void Subscribe(int clientId)
        {
            m_registeredUser = OperationContext.Current.GetCallbackChannel <IPublishing>();

            IContextChannel      channel = OperationContext.Current.Channel;
            ICommunicationObject obj     = (ICommunicationObject)m_registeredUser;

            obj.Faulted += new EventHandler(Channel_Faulted);
            obj.Closed  += new EventHandler(Channel_Faulted);

            var result = false;

            if (!_callbackList.Contains(new KeyValuePair <int, IPublishing>(clientId, m_registeredUser)))
            {
                result = _callbackList.TryAdd(clientId, m_registeredUser);
                if (result)
                {
                    LogServer.LogStatus(STT.General.INFO_GENERAL, $"ClientNotifier client ID= {clientId} had been subscribe ");
                }
                else
                {
                    LogServer.LogStatus(STT.General.ERROR_GENERAL, $"ClientNotifier client ID= {clientId} subscribtion Failure ");
                }

                result = _callbackListClientIdByChannel.TryAdd(channel, clientId);
                result = _callbackListChannelByClientId.TryAdd(clientId, channel);

                DateTime today = DateTime.Now;
                result = _clientKeepAliveMessageByClientId.TryAdd(clientId, today);
            }

            m_timer          = new Timer(1000);
            m_timer.Elapsed += Channel_Opened;
            m_timer.Start();
        }
Example #30
0
        public bool Connect(string clientname)
        {
            IMDSClient      _CallBackChannel    = OperationContext.Current.GetCallbackChannel <IMDSClient>();
            IContextChannel _UserContextChannel = OperationContext.Current.Channel;
            int             key = _UserContextChannel.GetHashCode();

            if (!Clients.Keys.Contains(key))
            {
                MDSClient _Client = new MDSClient(clientname, key, _CallBackChannel);
                Clients.Add(key, _Client);

                _Client.Fault += new EventHandler(client_Fault);
                _UserContextChannel.Faulted += new EventHandler(_UserContextChannel_Faulted);
                _UserContextChannel.Closing += new EventHandler(_UserContextChannel_Faulted);
                _UserContextChannel.Closed  += new EventHandler(_UserContextChannel_Faulted);


                createNewMessage("Подключился клиент " + clientname + " (" + key.ToString() + ")");

                foreach (MDSClient c in Clients.Values.ToArray())
                {
                    c.SendUpdateClients();
                }
                return(true);
            }

            return(false);
        }
        public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            Fx.Assert(message != null, "Null message");
            Fx.Assert(channel != null, "Null channel");

            return(new InstanceContext(this.serviceHostBase));
        }
Example #32
0
        bool SendResolveResponse(EndpointDiscoveryMetadata matchingEndpoint)
        {
            if (matchingEndpoint == null)
            {
                return(true);
            }

            IContextChannel contextChannel = (IContextChannel)this.ResponseChannel;
            IAsyncResult    result         = null;

            using (new OperationContextScope(contextChannel))
            {
                this.context.AddressDuplexResponseMessage(OperationContext.Current);

                contextChannel.OperationTimeout = this.timeoutHelper.RemainingTime();

                result = this.BeginSendResolveResponse(
                    this.ResponseChannel,
                    this.discoveryServiceImpl.GetNextMessageSequence(),
                    matchingEndpoint,
                    this.PrepareAsyncCompletion(onSendResolveResponseCompletedCallback),
                    this);
            }

            return(result.CompletedSynchronously && OnSendResolveResponseCompleted(result));
        }
Example #33
0
        private void AddMessageHeader(IContextChannel channel, string cmd, bool iscompressjson, bool isencryptionjson, SerializeType serializetype, SysLoginRight loginright, Action callback)
        {
            using (var scope = new OperationContextScope(channel as IContextChannel))
            {
                if (string.IsNullOrEmpty(cmd))
                {
                    cmd = "";
                }

                HeaderParameter para = new HeaderParameter();
                para.cmd        = cmd;
                para.routerid   = clientObj.RouterID;
                para.pluginname = clientObj.PluginName;
                //ReplyIdentify如果客户端创建连接为空,如果中间件连接上级中间件那就是本地中间件标识
                para.replyidentify    = null;
                para.beginidentify    = BeginIdentify;
                para.endidentify      = EndIdentify;
                para.token            = loginright != null ? loginright.token : null; //clientObj.Token;
                para.iscompressjson   = iscompressjson;
                para.isencryptionjson = isencryptionjson;
                para.serializetype    = serializetype;
                para.LoginRight       = loginright;
                para.NodePath         = null;
                HeaderOperater.AddMessageHeader(OperationContext.Current.OutgoingMessageHeaders, para);
                callback();
            }
        }
        public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            InstanceContext instanceContext = base.GetExistingInstanceContext(message, channel);

            if (instanceContext != null && this.InstanceLifeTimeManager != null)
            {
                WorkflowDurableInstance workflowDurableInstance = instanceContext.Extensions.Find<WorkflowDurableInstance>();

                if (workflowDurableInstance == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                        new InvalidOperationException(
                        SR2.GetString(
                        SR2.RequiredInstanceContextExtensionNotFound,
                        typeof(WorkflowDurableInstance).Name)));
                }

                this.InstanceLifeTimeManager.NotifyWorkflowActivationComplete(
                    workflowDurableInstance.InstanceId,
                    this.workflowActivationCompleteCallback,
                    new WorkflowActivationCompletedCallbackState
                    (
                    workflowDurableInstance.InstanceId,
                    instanceContext),
                    false);
            }

            return instanceContext;
        }
Example #35
0
        IAsyncResult BeginSendProxyAnnouncement(
            EndpointDiscoveryMetadata proxyEndpoint,
            TimeSpan timeout,
            AsyncCallback callback,
            object state)
        {
            IAsyncResult    result;
            IContextChannel contextChannel = (IContextChannel)this.ResponseChannel;

            using (new OperationContextScope(contextChannel))
            {
                this.context.AddressDuplexResponseMessage(OperationContext.Current);

                contextChannel.OperationTimeout = timeout;

                result = this.BeginSendProxyAnnouncement(
                    this.ResponseChannel,
                    this.discoveryServiceImpl.GetNextMessageSequence(),
                    proxyEndpoint,
                    callback,
                    state);
            }

            return(result);
        }
Example #36
0
        //------------------------------------------------------------------------------------Event Handler--------------------------------------------------------------------------------

        private void InterfaceChannel_Closed(object sender, EventArgs e)
        {
            IContextChannel ThisContext = (IContextChannel)sender;

            CallBackHandler.RemoveInterfaceConnection(ThisContext.SessionId);

            AstroData.UnsubscribeBySessionID(ThisContext.SessionId);
        }
 public override void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
 {
     ServiceChannel serviceChannel = GetServiceChannelFromProxy(channel);
     if (serviceChannel != null && serviceChannel.HasSession)
     {
         instanceContext.BindIncomingChannel(serviceChannel);
     }
 }
Example #38
0
 public ProcessorInfo(string serviceID, string aSessionId, OperationContext aCtx)
 {
     ServiceID     = serviceID;
     ID            = aSessionId;
     _callBack     = aCtx.GetCallbackChannel <IWCFCallback>();
     Chanel        = aCtx.Channel;
     SessionObject = aCtx.Channel;
 }
Example #39
0
        public DisplayService()
            : base()
        {
            logger.Debug("Создан новый экземпляр службы");

            channel = OperationContext.Current.Channel;
            channel.Faulted += channel_Faulted;
            channel.Closing += channel_Closing;
        }
 public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     ServiceChannel serviceChannel = this.GetServiceChannelFromProxy(channel);
     if (serviceChannel != null && serviceChannel.HasSession)
     {
         this.SingletonInstance.BindIncomingChannel(serviceChannel);
     }
     return this.SingletonInstance;
 }
 internal ServiceChannel GetServiceChannelFromProxy(IContextChannel channel)
 {
     ServiceChannel serviceChannel = channel as ServiceChannel;
     if (serviceChannel == null)
     {
         serviceChannel = ServiceChannelFactory.GetServiceChannel(channel);
     }
     return serviceChannel;
 }
		public void InitializeInstanceContext (InstanceContext instanceContext, Message message, IContextChannel channel)
		{
			var key = channel.SessionId ?? String.Empty;
			pool [key] = instanceContext;
			channel.Closed += delegate {
				pool.Remove (key);
				instanceContext.Close (); // FIXME: timeout?
			};
		}
 public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     ServiceChannel serviceChannelFromProxy = base.GetServiceChannelFromProxy(channel);
     if (serviceChannelFromProxy == null)
     {
         return null;
     }
     return serviceChannelFromProxy.InstanceContext;
 }
Example #44
0
    	private RealmEntry GetRealmByChannel(IContextChannel chan)
    	{
    		foreach (var realm in AuthenticationServer.Realms)
    		{
    			if (realm.Channel == chan)
    			{
					return realm;
    			}
    		}
			return null;
    	}
 public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     // Here is the flow for a Sessionful channel
     //  1. First request comes in on new channel.
     //  2. ServiceChannel.InstanceContext is returned which is null.
     //  3. InstanceBehavior.EnsureInstanceContext will create a new InstanceContext.
     //  4. this.InitializeInstanceContext is called with the newly created InstanceContext and the channel.
     //  5. If the channel is sessionful then its bound to the InstanceContext.
     //  6. Bind channel to the InstanceContext.
     //  7. For all further requests on the same channel, we will return ServiceChannel.InstanceContext which will be non null.
     ServiceChannel serviceChannel = this.GetServiceChannelFromProxy(channel);
     Contract.Assert((serviceChannel != null), "System.ServiceModel.Dispatcher.PerSessionInstanceContextProvider.GetExistingInstanceContext(), serviceChannel != null");
     return (serviceChannel != null) ? serviceChannel.InstanceContext : null;
 }
		private static ILifetimeScope GetScope(IContextChannel scopeHolder)
		{
			if (scopeHolder == null)
			{
				return null;
			}
			var extension = scopeHolder.Extensions.Find<WcfSessionScopeHolder>();
			if (extension == null)
			{
				extension = new WcfSessionScopeHolder(new DefaultLifetimeScope());
				scopeHolder.Extensions.Add(extension);
			}
			return extension.Scope;
		}
        public virtual void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
        {
            if (instanceContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instanceContext");
            }
            if (message == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
            }
            if (channel == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel");
            }

            Guid instanceId = GetInstanceIdFromMessage(message);
            DurableInstance durableInstance;
            if (instanceId == Guid.Empty) //Activation Request.
            {
                instanceId = Guid.NewGuid();
                durableInstance = this.OnCreateNewInstance(instanceId);
                message.Properties[DurableMessageDispatchInspector.NewDurableInstanceIdPropertyName] = instanceId;
            }
            else
            {
                durableInstance = this.OnGetExistingInstance(instanceId);
            }

            Fx.Assert(durableInstance != null, "Durable instance should never be null at this point.");
            durableInstance.Open();

            instanceContext.Extensions.Add(durableInstance);

            if (!string.IsNullOrEmpty(channel.SessionId))
            {
                instanceContext.IncomingChannels.Add(channel);
            }

            contextCache.AddInstanceContext(instanceId, instanceContext);

            if (DiagnosticUtility.ShouldTraceInformation)
            {
                string traceText = SR.GetString(SR.TraceCodeDICPInstanceContextCached, instanceId);
                TraceUtility.TraceEvent(TraceEventType.Information,
                    TraceCode.DICPInstanceContextCached, SR.GetString(SR.TraceCodeDICPInstanceContextCached), 
                    new StringTraceRecord("InstanceDetail", traceText),
                    this, null);
            }
        }
Example #48
0
        public TemplateService()
            : base()
        {
            logger.Debug("Создан новый экземпляр службы");

            channel = OperationContext.Current.Channel;
            channel.Faulted += channel_Faulted;
            channel.Closing += channel_Closing;

            var currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            templatesFolder = !string.IsNullOrWhiteSpace(Settings.Folder)
                ? Settings.Folder
                : Path.Combine(currentDirectory, "templates");
        }
        InstanceContext IInstanceContextProvider.GetExistingInstanceContext(Message message, IContextChannel channel)
        {
            SessionState state = null;

            bool hasSession = (channel.SessionId != null);
            if (hasSession)
            {
                state = channel.Extensions.Find<SessionState>();
                if (state != null)
                    return state.WaitForInstanceContext();
            }

            int headerIndex = message.Headers.FindHeader(ClientHeader.HeaderName, ClientHeader.HeaderNamespace);
            string clientId = null;
            if (headerIndex != -1)
                clientId = message.Headers.GetHeader<string>(headerIndex);

            if (clientId == null)
                return null;

            bool isNew = false;
            lock (this.ThisLock)
            {
                LighterSessionStateManager manager = LighterSessionContext.GetInstance().SessionManager;
                if (!manager.TryGetValue(clientId, out state))
                {
                    state = new SessionState(clientId, null);
                    manager.Add(clientId, state);
                    isNew = true;
                }
            }

            if (hasSession)
                channel.Extensions.Add(state);

            if (isNew)
                return null;

            InstanceContext instanceContext = state.WaitForInstanceContext();
            if (hasSession)
                instanceContext.IncomingChannels.Add(channel);

            return instanceContext;
        }
        void IInstanceContextProvider.InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
        {
            SessionState state = null;

            bool hasSession = (channel.SessionId != null);
            if (hasSession)
            {
                instanceContext.IncomingChannels.Add(channel);
                state = channel.Extensions.Find<SessionState>();
            }
            else
            {
                // Otherwise, if we don't have a session, look the info up again in the table.
                int headerIndex = message.Headers.FindHeader(ClientHeader.HeaderName, ClientHeader.HeaderNamespace);
                if (headerIndex != -1)
                {
                    string clientId = message.Headers.GetHeader<string>(headerIndex);
                    if (clientId != null)
                    {
                        lock (this.ThisLock)
                        {
                            LighterSessionStateManager manager = LighterSessionContext.GetInstance().SessionManager;
                            manager.TryGetValue(clientId, out state);
                        }
                    }
                }
            }

            if (state != null)
            {
                instanceContext.Extensions.Add(state);
                state.SetInstanceContext(instanceContext);
            }

            instanceContext.Closing += delegate(object sender, EventArgs e)
            {
                lock (this.ThisLock)
                {
                    LighterSessionStateManager manager = LighterSessionContext.GetInstance().SessionManager;
                    manager.Remove(state.Account);
                }
            };
        }
Example #51
0
        public StandardServerService()
            : base()
        {
            try
            {
                var operationContext = OperationContext.Current;
                if (operationContext != null)
                {
                    sessionId = Guid.Parse(operationContext.IncomingMessageHeaders
                        .GetHeader<string>("SessionId", string.Empty));
                }
            }
            catch { }

            try
            {
                var webOperationContext = WebOperationContext.Current;
                if (webOperationContext != null && sessionId == Guid.Empty)
                {
                    sessionId = Guid.Parse(webOperationContext.IncomingRequest
                        .Headers[ExtendHttpHeaders.Session]);
                }
            }
            catch { }

            if (sessionId != Guid.Empty)
            {
                using (var session = SessionProvider.OpenSession())
                using (var transaction = session.BeginTransaction())
                {
                    currentUser = session.CreateCriteria<User>()
                        .Add(Restrictions.Eq("SessionId", sessionId))
                        .SetMaxResults(1)
                        .UniqueResult<User>();
                }
            }

            logger.Debug("Создан новый экземпляр службы [{0}]", sessionId);

            channel = OperationContext.Current.Channel;
            channel.Faulted += channel_Faulted;
            channel.Closing += channel_Closing;
        }
		OperationContext CreateOperationContext (Message incoming)
		{
			IContextChannel contextChannel;
			if (dispatch_runtime.CallbackClientRuntime.CallbackClientType != null) {
#if DISABLE_REAL_PROXY
				var type = ServiceProxyGenerator.CreateCallbackProxyType (dispatch_runtime, dispatch_runtime.CallbackClientRuntime.CallbackClientType);
				contextChannel = (ServiceRuntimeChannel) Activator.CreateInstance (type, new object [] {reply_or_input, dispatch_runtime});
#else
				contextChannel = (IContextChannel) new ClientRealProxy (dispatch_runtime.CallbackClientRuntime.CallbackClientType, new DuplexServiceRuntimeChannel (reply_or_input, dispatch_runtime), true).GetTransparentProxy ();
#endif
			}
			else
				contextChannel = new ServiceRuntimeChannel (reply_or_input, dispatch_runtime);
			contextChannel.Open (); // FIXME: timeout?
			OperationContext opCtx = new OperationContext (contextChannel);
			opCtx.IncomingMessage = incoming;
			opCtx.EndpointDispatcher = dispatch_runtime.EndpointDispatcher;
			context_channel = contextChannel;
			return opCtx;
		}
        public EnsureCredentialsUseContext(
            string username, string password, string accessKey, IContextChannel channel)
        {
            EsbCredentials credentials = new EsbCredentials
            {
                Username = username,
                Password = password,
            };

            _scope = new OperationContextScope(channel);
            MessageHeader<EsbCredentials> credentialsMessageHeader =
                new MessageHeader<EsbCredentials>(credentials);
            MessageHeader<string> accessKeyMessageHeader =
                new MessageHeader<string>(accessKey);

            OperationContext.Current.OutgoingMessageHeaders
                .Add(credentialsMessageHeader
                .GetUntypedHeader(Esbcredentials, HttpServicesSapoPtDefinitions));

            OperationContext.Current.OutgoingMessageHeaders
                .Add(accessKeyMessageHeader
                .GetUntypedHeader(Esbaccesskey, HttpServicesSapoPtMetadataMarket));
        }
 public virtual void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
 }
 public virtual InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException());
 }
 public override void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
 {
 }
 public override InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     return null;
 }
Example #58
0
 public OperationContextScope(IContextChannel channel)
 {
     this.PushContext(new OperationContext(channel));
 }
Example #59
0
 public InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
 {
     ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
     return this.inner.GetExistingInstanceContext(message, channel);
 }
Example #60
0
 public void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
 {
     ColorConsole.WriteLine(ConsoleColor.Cyan, "{0}.{1}", this.GetType().Name, ReflectionUtil.GetMethodSignature(MethodBase.GetCurrentMethod()));
     this.inner.InitializeInstanceContext(instanceContext, message, channel);
 }