Example #1
0
        public async Task <IEnumerable <LoadContext> > Execute(QueryContext context,
                                                               Next <QueryContext, IEnumerable <LoadContext> > next)
        {
            var items = (await next(context)).ToList();

            foreach (var item in items)
            {
                if (item.LoadedFromCache)
                {
                    continue;
                }
                if (item.Entity == null)
                {
                    continue;
                }

                var sessionEntry = new SessionEntry()
                {
                    Action   = ActionType.Update,
                    Instance = item.Entity,
                    Key      = item.Key
                };

                _sessionCache.Attach(sessionEntry);
            }

            return(items);
        }
Example #2
0
        public virtual void Add <T>(T instance) where T : class
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            var type  = typeof(T);
            var value = _idAccessor.GetId(instance);
            var key   = _idManager.GetFromId(typeof(T), value);

            if (key == null)
            {
                key = _idManager.GenerateId(type);
                _idAccessor.SetId(instance, key.Id);
            }

            var entry = new SessionEntry()
            {
                Action   = ActionType.Add,
                Instance = instance,
                Key      = key
            };

            _sessionCache.Attach(entry);
        }
            public ISessionStateItemCollection Get(string id, out int timeout)
            {
                var key   = GetKey(id);
                var entry = _client.Get <SessionEntry>(key);

                ISessionStateItemCollection sessionStateItemCollection = new SessionStateItemCollection();

                if (entry == null)
                {
                    entry = new SessionEntry();
                }
                else
                {
                    foreach (var item in entry.Dictionary)
                    {
                        sessionStateItemCollection[item.Key] = item.Value.Deserialize();
                    }
                }

                timeout = entry.Timeout;

                //更新过期时间。
                _client.Store(StoreMode.Set, key, entry, TimeSpan.FromMinutes(timeout));

                return(sessionStateItemCollection);
            }
Example #4
0
        public MptxInstance CreateInstance(
            Type stateType,
            string parentInstanceId,
            object state,
            IReadOnlyDictionary <string, object> items)
        {
            var instanceId = CreateInstanceId();

            object parentState     = null;
            Type   parentStateType = null;

            if (parentInstanceId != null)
            {
                var parentKey   = GetSessionKey(parentInstanceId);
                var parentEntry = GetEntry(parentKey);

                if (parentEntry == null)
                {
                    throw new InvalidParentException(parentInstanceId);
                }

                parentState     = parentEntry.State;
                parentStateType = parentEntry.StateType;

                parentEntry.ChildInstanceIds ??= new HashSet <string>();
                parentEntry.ChildInstanceIds.Add(instanceId);

                SetEntry(parentKey, parentEntry);
            }

            items ??= new Dictionary <string, object>();

            var entry = new SessionEntry()
            {
                StateType        = stateType,
                Items            = items,
                State            = state,
                ParentInstanceId = parentInstanceId,
                ChildInstanceIds = new HashSet <string>()
            };

            var key = GetSessionKey(instanceId);

            SetEntry(key, entry);

            return(new MptxInstance(
                       instanceId,
                       stateType,
                       state,
                       parentInstanceId,
                       parentStateType,
                       parentState,
                       items));
        }
 public static void Setup()
 {
     BsonMapper.Global.RegisterType(
         serialize: entity => ParticipantLapTimes.ToBson(entity),
         deserialize: bson => ParticipantLapTimes.FromBson(bson));
     BsonMapper.Global.RegisterType(
         serialize: entity => SessionEntry.ToBson(entity),
         deserialize: bson => SessionEntry.FromBson(bson));
     BsonMapper.Global.RegisterType(
         serialize: entity => SessionTrackInfo.ToBson(entity),
         deserialize: bson => SessionTrackInfo.FromBson(bson));
 }
Example #6
0
        /**
         * 创建session
         * @param sessionName
         * @return
         */
        private string CreateSession(string sessionId)
        {
            var entry = new SessionEntry();

            entry.ID = sessionId;

            var result = consulClient.Session.Create(entry).Sync();

            return(result.Response);

            //NewSession newSession = new NewSession();
            //newSession.setName(sessionName);
            //return consulClient.sessionCreate(newSession, null).getValue();
        }
Example #7
0
        private bool TryDeserialize(byte[] bytes, out SessionEntry entry)
        {
            try
            {
                entry = JsonConvert.DeserializeObject <SessionEntry>(_encoding.GetString(bytes), _serializerSettings);
                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Failed to deserialize MPTX state.");

                entry = default;
                return(false);
            }
        }
Example #8
0
        public virtual void Remove <T>(T instance) where T : class
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            var value = _idAccessor.GetId(instance);
            var key   = _idManager.GetFromId(typeof(T), value);
            var entry = new SessionEntry()
            {
                Action   = ActionType.Delete,
                Instance = instance,
                Key      = key
            };

            _sessionCache.Attach(entry);
        }
Example #9
0
        /// <summary>
        /// Get a CIM session for the target computer
        /// </summary>
        /// <param name="computerName"></param>
        /// <param name="credential"></param>
        /// <param name="certificateThumbprint"></param>
        /// <param name="authenticationMechanism"></param>
        /// <param name="sessionOptions"></param>
        /// <param name="useSsl"></param>
        /// <param name="port"></param>
        /// <param name="pssessionOption"></param>
        /// <returns></returns>
        internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption)
        {
            System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(computerName), "ComputerName is null in GetSession. GetSession should not be called in this case.");
            lock (SyncRoot)
            {
                SessionEntry newSessionEntry;

                if (availableSessions.ContainsKey(computerName))
                {
                    List <SessionEntry> sel = availableSessions[computerName];
                    if (sel.Count > 0)
                    {
                        for (int i = 0; i < sel.Count; i++)
                        {
                            SessionEntry se = sel[i];

                            // No session options specified or the object matches exactly...
                            if ((se.SessionOptions == null && sessionOptions == null) || CompareSessionOptions(se, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption))
                            {
                                // Up the number of references to this session object...
                                se.AddReference();
                                return(se.Session);
                            }
                        }
                    }
                }


                // Allocate a new session entry for this computer

                newSessionEntry = new SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption);
                newSessionEntry.IterationsRemaining = MaxIterations;
                newSessionEntry.AddReference();
                if (!availableSessions.ContainsKey(computerName))
                {
                    availableSessions.Add(computerName, new List <SessionEntry>());
                }

                availableSessions[computerName].Add(newSessionEntry);

                // Return the session object
                return(newSessionEntry.Session);
            }
        }
Example #10
0
        public async Task Execute(IEnumerable <T> context, Next <IEnumerable <T> > next)
        {
            var items = context
                        .Select(x =>
            {
                var entry = _sessionCache[x.Key];

                //not in cache
                if (entry == null)
                {
                    return(x);
                }

                //the item has been removed inside the session.
                if (entry.Action == ActionType.Delete)
                {
                    return(null);
                }

                //item was cached
                x.Entity          = entry.Instance;
                x.LoadedFromCache = true;
                return(x);
            })
                        .Where(x => x != null)          //removed deleted
                        .Where(x => !x.LoadedFromCache) //removed cached
                        .ToList();

            await next(items);

            foreach (var item in items.Where(x => x.Entity != null))
            {
                var sessionEntry = new SessionEntry()
                {
                    Action   = ActionType.Update,
                    Instance = item.Entity,
                    Key      = item.Key
                };

                _sessionCache.Attach(sessionEntry);
            }
        }
Example #11
0
        public virtual void Attach <T>(T instance) where T : class
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            //allows for attaching exiting objects to this session!
            //(issue could arise with the rev)
            var value = _idAccessor.GetId(instance);
            var key   = _idManager.GetFromId(typeof(T), value);
            var entry = new SessionEntry()
            {
                Action   = ActionType.Update,
                Instance = _tracking.TrackInstance(instance),
                Key      = key
            };


            _sessionCache.Attach(entry);
        }
Example #12
0
        public void Add(Session session)
        {
            var entry = new SessionEntry()
            {
                SessionListItem = new SessionListItem(session), // root
                ChildItems      = session.Children.Select(x => new SessionListItem(x)).ToList(),
            };

            _RootSessions.Add(session);
            _FlattenItems.Add(entry.SessionListItem);
            sessionMap.Add(session, entry);

            if (entry.SessionListItem.HasToggleButton)
            {
                Expand(_FlattenItems.Count - 1);
            }

            session.ChildSessionAdded += HandleNewChildSession;

            RaiseItemAdded(_FlattenItems.Count - 1);
        }
Example #13
0
 /// <summary>
 /// CreateSession is used to create a new managed session
 /// </summary>
 /// <returns>The session ID</returns>
 private async Task<string> CreateSession()
 {
     var se = new SessionEntry
     {
         Name = Opts.SessionName,
         TTL = Opts.SessionTTL
     };
     return (await _client.Session.Create(se).ConfigureAwait(false)).Response;
 }
Example #14
0
        private void SetEntry(string key, SessionEntry entry)
        {
            var serialized = Serialize(entry);

            _httpContextAccessor.HttpContext.Session.Set(key, serialized);
        }
Example #15
0
        private static bool CompareSessionOptions(SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption)
        {
            if (!sessionEntry.SessionOptions.Timeout.Equals(options2.Timeout))
            {
                return(false);
            }

            if (!string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (!string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (!string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (sessionEntry.AuthenticationMechanism != authenticationMechanism)
            {
                return(false);
            }

            if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2))
            {
                return(false);
            }

            if (sessionEntry.UseSsl != useSsl)
            {
                return(false);
            }

            if (sessionEntry.Port != port)
            {
                return(false);
            }


            // check PSSessionOption if present
            if (pssessionOption == null ^ sessionEntry.PSSessionOption == null)
            {
                return(false);
            }

            if (pssessionOption != null && sessionEntry.PSSessionOption != null)
            {
                if (sessionEntry.PSSessionOption.ProxyAccessType != pssessionOption.ProxyAccessType)
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.ProxyAuthentication != pssessionOption.ProxyAuthentication)
                {
                    return(false);
                }

                if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential))
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.SkipCACheck != pssessionOption.SkipCACheck)
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.SkipCNCheck != pssessionOption.SkipCNCheck)
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.SkipRevocationCheck != pssessionOption.SkipRevocationCheck)
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.NoEncryption != pssessionOption.NoEncryption)
                {
                    return(false);
                }

                if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16)
                {
                    return(false);
                }
            }

            return(true);
        }
Example #16
0
 private byte[] Serialize(SessionEntry entry) =>
 _encoding.GetBytes(JsonConvert.SerializeObject(entry, _serializerSettings));
 public ISessionStateItemCollection Get(string id, out int timeout)
 {
     var sessionDictionary = GetDictionary();
     SessionEntry sessionEntry;
     ISessionStateItemCollection sessionStateItemCollection = new SessionStateItemCollection();
     if (sessionDictionary.TryGetValue(id, out sessionEntry))
     {
         foreach (var entry in sessionEntry.Dictionary)
         {
             var item = DataItem.Create(entry.Value);
             sessionStateItemCollection[entry.Key] = item.Deserialize();
         }
     }
     else
     {
         sessionEntry = new SessionEntry();
     }
     timeout = sessionEntry.Timeout;
     return sessionStateItemCollection;
 }
 public void Set(string id, int timeout, ISessionStateItemCollection sessionStateItemCollection)
 {
     var dictionary = GetDictionary();
     var entry = dictionary[id] = new SessionEntry(timeout);
     foreach (string key in sessionStateItemCollection.Keys)
     {
         entry.Dictionary[key] = new DataItem(sessionStateItemCollection[key]).Serialize();
     }
     Save(dictionary);
 }
        protected async Task TryAccquireLockAsync(CancellationToken token)
        {
            if (!token.IsCancellationRequested)

            {
                try
                {
                    if (_distributedLock == null)
                    {
                        var client = new ConsulClient();
                        var se     = new SessionEntry()
                        {
                            Checks = new List <string>()
                            {
                                // Default health check for the consul agent. It is very recommended to keep this.
                                "serfHealth",
                                // "myServiceHealthCheck" // Any additional health check.
                            },
                            Name = "myServicSession",
                            // Optional TTL check, to achieve sliding expiration. It is very recommended to use it.
                            TTL = TimeSpan.FromSeconds(30)
                        };

                        var sessionId = (await client.Session.Create(se).ConfigureAwait(false)).Response;
                        if (se.TTL.HasValue)
                        {
                            _sessionRenewCts  = new CancellationTokenSource();
                            _sessionRenewTask = client.Session.RenewPeriodic(se.TTL.Value, sessionId,
                                                                             WriteOptions.Default, _sessionRenewCts.Token);
                        }

                        _distributedLock = await client
                                           .AcquireLock(
                            new LockOptions(_key)
                            { Session = sessionId, LockTryOnce = true, LockWaitTime = TimeSpan.FromSeconds(3) },
                            token).ConfigureAwait(false);
                    }
                    else
                    {
                        if (!_distributedLock.IsHeld)
                        {
                            if (_sessionRenewTask.IsCompleted)
                            {
                                Task.WaitAny(
                                    _sessionRenewTask); //Awaits the task without throwing, cleaner than try catch.
                                _distributedLock = null;
                            }
                            else
                            {
                                await _distributedLock.Acquire(token).ConfigureAwait(false);
                            }
                        }
                    }
                }
                catch (LockMaxAttemptsReachedException ex)
                {
                    _logger.Warning(ex, ex.Message);
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, ex.Message);
                }
                finally
                {
                    if (_distributedLock == null && _sessionRenewCts != null)
                    {
                        _sessionRenewCts.Cancel();
                        _sessionRenewCts.Dispose();
                    }

                    HandleLockStatusChange(_distributedLock?.IsHeld == true);

                    // Retrigger the timer after an 10 seconds delay (in this example)
                    _timer.Change(10000, Timeout.Infinite);
                }
            }
        }
Example #20
0
        /// <param name="sessionID">The session this new ConnectionID will belong to</param>
        /// <returns>The new ConnectionID allocated</returns>
        public string AllocateNewConnectionID(string sessionID)
        {
            ASSERT( !string.IsNullOrEmpty(sessionID), "Missing parameter 'sessionID'" );
            LOG( "AllocateNewConnectionID(" + sessionID + ") - Start" );

            bool sessionAllocated = false;
            string connectionID;
            lock( LockObject )
            {
                LOG( "AllocateNewConnectionID(" + sessionID + ") - Lock aquired" );
                CheckValidity();

                SessionEntry sessionEntry;
                if(! AllSessions.TryGetValue(sessionID, out sessionEntry) )
                {
                    LOG( "AllocateNewConnectionID(" + sessionID + ") - This is the first connection in the sesion ; Allocating a new SessionEntry" );
                    sessionEntry = new SessionEntry();
                    AllSessions.Add( sessionID, sessionEntry );
                    sessionAllocated = true;
                }

                var otherConnectionIDsInSession = sessionEntry.ConnectionIDs.ToArray();

                connectionID = Guid.NewGuid().ToString();
                var connectionEntry = new ConnectionEntry( this, sessionID, connectionID );
                AllConnections.Add( connectionID, connectionEntry );
                sessionEntry.ConnectionIDs.Add( connectionID );

                LOG( "AllocateNewConnectionID(" + sessionID + ") - Starting DisconnectionTimeout" );
                connectionEntry.DisconnectionTimeout = TasksQueue.CreateTask( 0, 0, 0, DisconnectionSeconds, 0, (taskEntry)=>{ConnectionEntry_DisconnectionTimeout(taskEntry, connectionEntry);} );
                LOG( "AllocateNewConnectionID(" + sessionID + ") - Started DisconnectionTimeout " + connectionEntry.DisconnectionTimeout );

                // Reset all other connections that are in the same session than this connection
                // => So, if the user just changed its page, the connection of the old page is reset
                //		and if the user has more than 1 page, the other pages will simply reconnect.
                LOG( "RegisterConnection(" + connectionID + ") - Resetting " + otherConnectionIDsInSession.Length + " connections in the same SessionID" );
                foreach( var otherConnectionID in otherConnectionIDsInSession )
                {
                    bool connectionExists;
                    SendMessagesToConnectionIfAvailable( otherConnectionID, new Message[]{}, out connectionExists );
                }

                CheckValidity();
                LOG( "AllocateNewConnectionID(" + sessionID + ") - Exit: " + connectionID );
            }

            ConnectionAllocatedInvokeCallbacks( connectionID );
            if( sessionAllocated )
                SessionAllocatedInvokeCallbacks( sessionID );
            return connectionID;
        }
 private void OnSession(SessionEntry session)
 {
     lock (_stateLock) {
         _currentSession = session;
     }
 }
        private static bool CompareSessionOptions(SessionEntry sessionEntry, CimSessionOptions options2, PSCredential credential2, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, bool useSsl, uint port, PSSessionOption pssessionOption)
        {
            if (!sessionEntry.SessionOptions.Timeout.Equals(options2.Timeout))
                return false;

            if (!string.Equals(sessionEntry.SessionOptions.Culture.ToString(), options2.Culture.ToString(), StringComparison.OrdinalIgnoreCase))
                return false;

            if (!string.Equals(sessionEntry.SessionOptions.UICulture.ToString(), options2.UICulture.ToString(), StringComparison.OrdinalIgnoreCase))
                return false;

            if (!string.Equals(sessionEntry.CertificateThumbprint, certificateThumbprint, StringComparison.OrdinalIgnoreCase))
                return false;

            if (sessionEntry.AuthenticationMechanism != authenticationMechanism)
                return false;

            if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.Credential, credential2))
                return false;

            if (sessionEntry.UseSsl != useSsl)
                return false;

            if (sessionEntry.Port != port)
                return false;


            // check PSSessionOption if present
            if (pssessionOption == null ^ sessionEntry.PSSessionOption == null)
            {
                return false;
            }

            if (pssessionOption != null && sessionEntry.PSSessionOption != null)
            {
                if (sessionEntry.PSSessionOption.ProxyAccessType != pssessionOption.ProxyAccessType)
                    return false;

                if (sessionEntry.PSSessionOption.ProxyAuthentication != pssessionOption.ProxyAuthentication)
                    return false;

                if (!Workflow.WorkflowUtils.CompareCredential(sessionEntry.PSSessionOption.ProxyCredential, pssessionOption.ProxyCredential))
                    return false;

                if (sessionEntry.PSSessionOption.SkipCACheck != pssessionOption.SkipCACheck)
                    return false;

                if (sessionEntry.PSSessionOption.SkipCNCheck != pssessionOption.SkipCNCheck)
                    return false;

                if (sessionEntry.PSSessionOption.SkipRevocationCheck != pssessionOption.SkipRevocationCheck)
                    return false;

                if (sessionEntry.PSSessionOption.NoEncryption != pssessionOption.NoEncryption)
                    return false;

                if (sessionEntry.PSSessionOption.UseUTF16 != pssessionOption.UseUTF16)
                    return false;
            }

            return true;
        }
Example #23
0
 private void OnSession(SessionEntry session)
 {
     _currentSession = session;
 }
            public ISessionStateItemCollection Get(string id, out int timeout)
            {
                var key = GetKey(id);
                var entry = _client.Get<SessionEntry>(key);

                ISessionStateItemCollection sessionStateItemCollection = new SessionStateItemCollection();

                if (entry == null)
                {
                    entry = new SessionEntry();
                }
                else
                {
                    foreach (var item in entry.Dictionary)
                    {
                        sessionStateItemCollection[item.Key] = item.Value.Deserialize();
                    }
                }

                timeout = entry.Timeout;

                //更新过期时间。
                _client.Store(StoreMode.Set, key, entry, TimeSpan.FromMinutes(timeout));

                return sessionStateItemCollection;
            }
Example #25
0
 /// <summary>
 /// CreateSession is used to create a new managed session
 /// </summary>
 /// <returns>The session ID</returns>
 private string CreateSession()
 {
     var se = new SessionEntry
     {
         Name = Opts.SessionName,
         TTL = Opts.SessionTTL
     };
     return _client.Session.Create(se).Response;
 }
        /// <summary>
        /// Get a CIM session for the target computer
        /// </summary>
        /// <param name="computerName"></param>
        /// <param name="credential"></param>
        /// <param name="certificateThumbprint"></param>
        /// <param name="authenticationMechanism"></param>
        /// <param name="sessionOptions"></param>
        /// <param name="useSsl"></param>
        /// <param name="port"></param>
        /// <param name="pssessionOption"></param>
        /// <returns></returns>
        internal CimSession GetSession(string computerName, PSCredential credential, string certificateThumbprint, AuthenticationMechanism authenticationMechanism, CimSessionOptions sessionOptions, bool useSsl, uint port, PSSessionOption pssessionOption)
        {
            System.Diagnostics.Debug.Assert(!string.IsNullOrEmpty(computerName), "ComputerName is null in GetSession. GetSession should not be called in this case.");
            lock (SyncRoot)
            {
                SessionEntry newSessionEntry;

                if (availableSessions.ContainsKey(computerName))
                {

                    List<SessionEntry> sel = availableSessions[computerName];
                    if (sel.Count > 0)
                    {
                        for (int i = 0; i < sel.Count; i++)
                        {
                            SessionEntry se = sel[i];

                            // No session options specified or the object matches exactly...
                            if ((se.SessionOptions == null && sessionOptions == null) || CompareSessionOptions(se, sessionOptions, credential, certificateThumbprint, authenticationMechanism, useSsl, port, pssessionOption))
                            {
                                // Up the number of references to this session object...
                                se.AddReference();
                                return se.Session;
                            }
                        }
                    }
                }

                
                // Allocate a new session entry for this computer

                newSessionEntry = new SessionEntry(computerName, credential, certificateThumbprint, authenticationMechanism, sessionOptions, useSsl, port, pssessionOption);
                newSessionEntry.IterationsRemaining = MaxIterations;
                newSessionEntry.AddReference();
                if (! availableSessions.ContainsKey(computerName))
                {
                    availableSessions.Add(computerName, new List<SessionEntry>());
                }

                availableSessions[computerName].Add(newSessionEntry);

                // Return the session object
                return newSessionEntry.Session;
            }
        }