public void Add(ILockable lockable)
            {
                if(locked)
                    lockable.Lock();

                lockables.Add(lockable);
            }
Example #2
0
        public LockHandle Lock(ILockable[] toWrite, ILockable[] toRead, LockingMode mode)
        {
            // Set up the local constants.

            int lockCount = toRead.Length + toWrite.Length;
            LockHandle handle = new LockHandle(lockCount);

            lock (this) {
                Lock @lock;
                LockingQueue queue;

                // Add Read and Write locks to cache and to the handle.
                for (int i = toWrite.Length - 1; i >= 0; --i) {
                    var toWriteLock = toWrite[i];
                    queue = GetQueueFor(toWriteLock);

                    // slightly confusing: this will add Lock to given table queue
                    @lock = new Lock(queue, mode, AccessType.Write);
                    @lock.Acquire();
                    handle.AddLock(@lock);
                }

                for (int i = toRead.Length - 1; i >= 0; --i) {
                    var toReadLock = toRead[i];
                    queue = GetQueueFor(toReadLock);

                    // slightly confusing: this will add Lock to given table queue
                    @lock = new Lock(queue, mode, AccessType.Read);
                    @lock.Acquire();
                    handle.AddLock(@lock);
                }
            }

            return handle;
        }
Example #3
0
        public void Dispose()
        {
            if(lockable == null)
                return;

            lockable.Unlock();
            lockable = null;
        }
Example #4
0
        public bool IsHandled(ILockable lockable)
        {
            for (int i = locks.Length - 1; i >= 0; i--) {
                if (locks[i].Lockable.RefId.Equals(lockable.RefId))
                    return true;
            }

            return false;
        }
Example #5
0
        public bool IsLocked(ILockable lockable)
        {
            lock (this) {
                LockingQueue queue;
                if (!queuesMap.TryGetValue(lockable.RefId, out queue))
                    return false;

                return !queue.IsEmpty;
            }
        }
Example #6
0
        public void CheckAccess(ILockable[] lockables, AccessType accessType, int timeout)
        {
            if (openHandles == null || lockables == null)
                return;

            foreach (var handle in openHandles) {
                foreach (var lockable in lockables) {
                    if (handle.IsHandled(lockable))
                        handle.CheckAccess(lockable, accessType, timeout);
                }
            }
        }
Example #7
0
        /// <summary>
        /// Do not return an item whose timestamp is later than the current
        /// transaction timestamp. (Otherwise we might compromise repeatable
        /// read unnecessarily.) Do not return an item which is soft-locked.
        /// Always go straight to the database instead.
        /// </summary>
        /// <remarks>
        /// Note that since reading an item from that cache does not actually
        /// go to the database, it is possible to see a kind of phantom read
        /// due to the underlying row being updated after we have read it
        /// from the cache. This would not be possible in a lock-based
        /// implementation of repeatable read isolation. It is also possible
        /// to overwrite changes made and committed by another transaction
        /// after the current transaction read the item from the cache. This
        /// problem would be caught by the update-time version-checking, if
        /// the data is versioned or timestamped.
        /// </remarks>
        public async Task <object> GetAsync(CacheKey key, long txTimestamp, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            using (await _lockObjectAsync.LockAsync())
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("Cache lookup: {0}", key);
                }

                // commented out in H3.1

                /*try
                 * {
                 *      cache.Lock( key );*/

                ILockable lockable = (ILockable)await(Cache.GetAsync(key, cancellationToken)).ConfigureAwait(false);

                bool gettable = lockable != null && lockable.IsGettable(txTimestamp);

                if (gettable)
                {
                    if (log.IsDebugEnabled())
                    {
                        log.Debug("Cache hit: {0}", key);
                    }

                    return(((CachedItem)lockable).Value);
                }
                else
                {
                    if (log.IsDebugEnabled())
                    {
                        if (lockable == null)
                        {
                            log.Debug("Cache miss: {0}", key);
                        }
                        else
                        {
                            log.Debug("Cached item was locked: {0}", key);
                        }
                    }
                    return(null);
                }

                /*}
                 * finally
                 * {
                 *      cache.Unlock( key );
                 * }*/
            }
        }
Example #8
0
 public TableAndLockProvider GetStateProvider(String tableName, int agentInstanceId, bool writesToTables)
 {
     TableStateInstance instance = AssertGetState(tableName, agentInstanceId);
     ILockable @lock = writesToTables ? instance.TableLevelRWLock.WriteLock : instance.TableLevelRWLock.ReadLock;
     if (instance is TableStateInstanceGrouped)
     {
         return new TableAndLockProviderGroupedImpl(new TableAndLockGrouped(@lock, (TableStateInstanceGrouped)instance));
     }
     else
     {
         return new TableAndLockProviderUngroupedImpl(new TableAndLockUngrouped(@lock, (TableStateInstanceUngrouped)instance));
     }
 }
 public TimeWinRunnable(
     int threadNum,
     RegressionEnvironment env,
     ILockable sharedLock,
     string[] symbols,
     int numberOfEvents)
 {
     this.threadNum = threadNum;
     this.env = env;
     this.sharedLock = sharedLock;
     this.symbols = symbols;
     this.numberOfEvents = numberOfEvents;
 }
Example #10
0
 /// <summary>
 /// Close an object
 /// </summary>
 public static void Close(ILockable lockable, Character user)
 {
     if (lockable is GameObject)
     {
         var go = lockable as GameObject;
         go.State = GameObjectState.Disabled;
         if (go.Map is Battleground)
         {
             Battleground bg = go.Map as Battleground;
             bg.OnPlayerClickedOnflag(go, user);
         }
     }
 }
Example #11
0
 /// <summary>
 /// Open a GameObject
 /// </summary>
 public static void Open(ILockable lockable, Character chr)
 {
     if (lockable is GameObject)
     {
         var go = lockable as GameObject;
         go.Use(chr);
         if (go.Map is Battleground)
         {
             var bg = go.Map as Battleground;
             bg.OnPlayerClickedOnflag(go, chr);
         }
     }
 }
Example #12
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="runtime">for processing events</param>
 /// <param name="beanEventType">the event type</param>
 /// <param name="eventAdapterService">factory for event beans and event types</param>
 /// <param name="threadingService">for inbound threading</param>
 public EventSenderBean(
     EPRuntimeEventSender runtime,
     BeanEventType beanEventType,
     EventAdapterService eventAdapterService,
     ThreadingService threadingService)
 {
     _iLock               = LockManager.CreateLock(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     _runtime             = runtime;
     _beanEventType       = beanEventType;
     _eventAdapterService = eventAdapterService;
     _compatibleClasses   = new HashSet <Type>();
     _threadingService    = threadingService;
 }
Example #13
0
        static void EndPopulate(IList target, ISupportInitialize supportInitialize)
        {
            ILockable lockable = target as ILockable;

            if (lockable != null)
            {
                lockable.EndUpdate();
            }
            if (supportInitialize != null)
            {
                supportInitialize.EndInit();
            }
        }
Example #14
0
        static void BeginPopulate(IList target, ISupportInitialize supportInitialize)
        {
            if (supportInitialize != null)
            {
                supportInitialize.BeginInit();
            }
            ILockable lockable = target as ILockable;

            if (lockable != null)
            {
                lockable.BeginUpdate();
            }
        }
Example #15
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="lockManager">The lock manager.</param>
 /// <param name="eventAdapterService">for dynamic event type creation</param>
 /// <param name="metadata">event type metadata</param>
 /// <param name="eventTypeId">The event type id.</param>
 /// <param name="underlyngType">is the underlying type returned by the event type</param>
 protected BaseConfigurableEventType(
     ILockManager lockManager,
     EventAdapterService eventAdapterService,
     EventTypeMetadata metadata,
     int eventTypeId,
     Type underlyngType)
 {
     _iLock               = lockManager.CreateLock(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     _eventTypeId         = eventTypeId;
     _eventAdapterService = eventAdapterService;
     _metadata            = metadata;
     _underlyngType       = underlyngType;
 }
        /// <summary>
        /// Adds the acquired lock.  If the lock does not already belong to the context, then it will be locked and
        /// the disposable lock will be returned.
        /// </summary>
        /// <param name="lock">The lock.</param>
        /// <returns></returns>
        public IDisposable AddAcquiredLock(ILockable @lock)
        {
            var table = _threadLocal.GetOrCreate();

            if (table.ContainsKey(@lock))
            {
                return(null);
            }

            var latch = @lock.Acquire();

            return(table[@lock] = latch);
        }
 public ExprTimePeriodEvalDeltaConstGivenDtxAdd(
     ExprTimePeriodImpl.TimePeriodAdder[] adders,
     int[] added,
     TimeZoneInfo timeZone,
     TimeAbacus timeAbacus)
 {
     _iLock             = LockManager.CreateLock(MethodBase.GetCurrentMethod().DeclaringType);
     _adders            = adders;
     _added             = added;
     _dateTime          = new DateTimeEx(DateTimeOffset.Now, timeZone);
     _timeAbacus        = timeAbacus;
     _indexMicroseconds = ExprTimePeriodUtil.FindIndexMicroseconds(adders);
 }
Example #18
0
 public TimeWinRunnable(
     int threadNum, 
     EPRuntime epRuntime, 
     ILockable sharedLock, 
     string[] symbols, 
     int numberOfEvents)
 {
     _threadNum = threadNum;
     _epRuntime = epRuntime;
     _sharedLock = sharedLock;
     _symbols = symbols;
     _numberOfEvents = numberOfEvents;
 }
        /// <summary>
        /// Do not return an item whose timestamp is later than the current
        /// transaction timestamp. (Otherwise we might compromise repeatable
        /// read unnecessarily.) Do not return an item which is soft-locked.
        /// Always go straight to the database instead.
        /// </summary>
        /// <remarks>
        /// Note that since reading an item from that cache does not actually
        /// go to the database, it is possible to see a kind of phantom read
        /// due to the underlying row being updated after we have read it
        /// from the cache. This would not be possible in a lock-based
        /// implementation of repeatable read isolation. It is also possible
        /// to overwrite changes made and committed by another transaction
        /// after the current transaction read the item from the cache. This
        /// problem would be caught by the update-time version-checking, if
        /// the data is versioned or timestamped.
        /// </remarks>
        public object Get(CacheKey key, long txTimestamp)
        {
            lock (_lockObject)
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("Cache lookup: {0}", key);
                }

                // commented out in H3.1

                /*try
                 * {
                 *      cache.Lock( key );*/

                ILockable lockable = (ILockable)cache.Get(key);

                bool gettable = lockable != null && lockable.IsGettable(txTimestamp);

                if (gettable)
                {
                    if (log.IsDebugEnabled())
                    {
                        log.Debug("Cache hit: {0}", key);
                    }

                    return(((CachedItem)lockable).Value);
                }
                else
                {
                    if (log.IsDebugEnabled())
                    {
                        if (lockable == null)
                        {
                            log.Debug("Cache miss: {0}", key);
                        }
                        else
                        {
                            log.Debug("Cached item was locked: {0}", key);
                        }
                    }
                    return(null);
                }

                /*}
                 * finally
                 * {
                 *      cache.Unlock( key );
                 * }*/
            }
        }
Example #20
0
        public void Lock_WhenCalledWithMultipleObjects_ShouldLockInHashOrder(ILockable lock1, ILockable lock2, ILockable lock3)
        {
            lock1.Lock.Returns(new object());
            lock2.Lock.Returns(new object());
            lock3.Lock.Returns(new object());

            lock1.Hash.Returns(100);
            lock2.Hash.Returns(200);
            lock3.Hash.Returns(300);

            locker.Lock(new[] { lock3, lock1, lock2 });

            enterObjects.Should().Equal(lock1.Lock, lock2.Lock, lock3.Lock);
        }
Example #21
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="container">The container.</param>
 /// <param name="typesPerObject">shareable collection that this adapter writes tofor caching bean types per class</param>
 /// <param name="eventAdapterService">factory for event beans and event types</param>
 /// <param name="eventTypeIdGenerator">The event type id generator.</param>
 public BeanEventAdapter(
     IContainer container,
     IDictionary <Type, BeanEventType> typesPerObject,
     EventAdapterService eventAdapterService,
     EventTypeIdGenerator eventTypeIdGenerator)
 {
     _container                      = container;
     _typesPerObject                 = typesPerObject;
     _typesPerObjectLock             = _container.LockManager().CreateLock(GetType());
     _typeToLegacyConfigs            = new Dictionary <String, ConfigurationEventTypeLegacy>();
     _defaultPropertyResolutionStyle = PropertyResolutionStyle.DEFAULT;
     _eventAdapterService            = eventAdapterService;
     _eventTypeIdGenerator           = eventTypeIdGenerator;
 }
Example #22
0
        public static int CompareObject(ILockable x, ILockable y)
        {
            var hashDiff = x.Hash.CompareTo(y.Hash);

            if (hashDiff != 0)
            {
                return(hashDiff);
            }

            var xType = x.GetType();
            var yType = y.GetType();

            return(String.Compare(xType.AssemblyQualifiedName, yType.AssemblyQualifiedName, StringComparison.InvariantCulture));
        }
Example #23
0
        public ILockable FindLocakbleTarget()
        {
            Collider[] cols = Physics.OverlapSphere(transform.position, 20);
            for (int i = 0; i < cols.Length; i++)
            {
                ILockable lockable = cols[i].GetComponent <ILockable>();
                if (lockable != null)
                {
                    return(lockable);
                }
            }

            return(null);
        }
Example #24
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="runtime">for processing events</param>
 /// <param name="beanEventType">the event type</param>
 /// <param name="eventAdapterService">factory for event beans and event types</param>
 /// <param name="threadingService">for inbound threading</param>
 /// <param name="lockManager">The lock manager.</param>
 public EventSenderBean(
     EPRuntimeEventSender runtime,
     BeanEventType beanEventType,
     EventAdapterService eventAdapterService,
     ThreadingService threadingService,
     ILockManager lockManager)
 {
     _iLock               = lockManager.CreateLock(GetType());
     _runtime             = runtime;
     _beanEventType       = beanEventType;
     _eventAdapterService = eventAdapterService;
     _compatibleClasses   = new HashSet <Type>();
     _threadingService    = threadingService;
 }
Example #25
0
 protected T Invoke <T>(Authentication authentication, ILockable lockable, Func <T> func)
 {
     //using (UsingDataBase.Set(lockable as IServiceProvider, authentication, true))
     {
         if (lockable is IDispatcherObject dispatcherObject)
         {
             return(dispatcherObject.Dispatcher.Invoke(func));
         }
         else
         {
             return(func());
         }
     }
 }
Example #26
0
        public void CheckAccess(ILockable lockable, AccessType accessType)
        {
            for (int i = locks.Length - 1; i >= 0; --i)
            {
                var tableLock = locks[i];
                if (tableLock.Lockable == lockable)
                {
                    tableLock.CheckAccess(accessType);
                    return;
                }
            }

            throw new Exception("The given object was not found in the lock list for this handle");
        }
Example #27
0
        /// <summary>
        /// Do not add an item to the cache unless the current transaction
        /// timestamp is later than the timestamp at which the item was
        /// invalidated. (Otherwise, a stale item might be re-added if the
        /// database is operating in repeatable read isolation mode.)
        /// </summary>
        /// <returns>Whether the item was actually put into the cache</returns>
        public async Task <bool> PutAsync(CacheKey key, object value, long txTimestamp, object version, IComparer versionComparator,
                                          bool minimalPut, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (txTimestamp == long.MinValue)
            {
                // MinValue means cache is disabled
                return(false);
            }
            cancellationToken.ThrowIfCancellationRequested();

            using (await(_asyncReaderWriterLock.WriteLockAsync()).ConfigureAwait(false))
            {
                if (log.IsDebugEnabled())
                {
                    log.Debug("Caching: {0}", key);
                }

                var lockValue = await(_cache.LockAsync(key, cancellationToken)).ConfigureAwait(false);
                try
                {
                    ILockable lockable = (ILockable)await(Cache.GetAsync(key, cancellationToken)).ConfigureAwait(false);

                    bool puttable = lockable == null ||
                                    lockable.IsPuttable(txTimestamp, version, versionComparator);

                    if (puttable)
                    {
                        await(Cache.PutAsync(key, CachedItem.Create(value, Cache.NextTimestamp(), version), cancellationToken)).ConfigureAwait(false);
                        if (log.IsDebugEnabled())
                        {
                            log.Debug("Cached: {0}", key);
                        }
                        return(true);
                    }
                    else
                    {
                        if (log.IsDebugEnabled())
                        {
                            log.Debug(lockable.IsLock ? "Item was locked: {0}" : "Item was already cached: {0}", key);
                        }
                        return(false);
                    }
                }
                finally
                {
                    await(_cache.UnlockAsync(key, lockValue, cancellationToken)).ConfigureAwait(false);
                }
            }
        }
Example #28
0
        public static void Handle(Character chr, ILockable lockable, LockInteractionType type)
        {
            var handler = InteractionHandlers.Get((uint)type);

            if (handler != null)
            {
                handler(lockable, chr);
            }
            else
            {
                log.Error("{0} trying to interact with lockable \"{1}\", but the used InteractionType \"{2}\" is not handled.",
                          chr, lockable, type);
            }
        }
Example #29
0
        public void Do_Generic_ExecutesProtectedBlock(
            ILockable lck)
        {
            bool          wasCalled = false;
            Func <string> block     = () =>
            {
                wasCalled = true;
                return("hello");
            };

            locker.Lock(new[] { lck }).Do(block);

            wasCalled.Should().BeTrue();
        }
Example #30
0
 protected void Invoke(Authentication authentication, ILockable lockable, Action action)
 {
     //using (UsingDataBase.Set(lockable as IServiceProvider, authentication, true))
     {
         if (lockable is IDispatcherObject dispatcherObject)
         {
             dispatcherObject.Dispatcher.Invoke(action);
         }
         else
         {
             action();
         }
     }
 }
Example #31
0
        /// <summary>Open a GameObject</summary>
        public static void Open(ILockable lockable, Character chr)
        {
            if (!(lockable is GameObject))
            {
                return;
            }
            GameObject go = lockable as GameObject;

            go.Use(chr);
            if (!(go.Map is Battleground))
            {
                return;
            }
            (go.Map as Battleground).OnPlayerClickedOnflag(go, chr);
        }
Example #32
0
 /// <summary>
 /// Loot a container's contents
 /// </summary>
 public static void Loot(ILockable lockable, Character user)
 {
     if (lockable is Item)
     {
         LootMgr.CreateAndSendObjectLoot(lockable, user, LootEntryType.Item, user.Map.IsHeroic);
     }
     else if (lockable is GameObject)
     {
         ((GameObject)lockable).Handler.Use(user);
     }
     else
     {
         log.Error("{0} tried to loot invalid object: " + lockable, user);
     }
 }
        private LockTimeoutException TimeoutException(ILockable lockable, AccessType accessType, int timeout)
        {
            ObjectName tableName;

            if (lockable is IDbObject)
            {
                tableName = ((IDbObject)lockable).ObjectInfo.FullName;
            }
            else
            {
                tableName = new ObjectName(lockable.RefId.ToString());
            }

            return(new LockTimeoutException(tableName, accessType, timeout));
        }
Example #34
0
 public static void Handle(Character chr, ILockable lockable, LockInteractionType type)
 {
     LockEntry.InteractionHandler interactionHandler =
         LockEntry.InteractionHandlers.Get <LockEntry.InteractionHandler>((uint)type);
     if (interactionHandler != null)
     {
         interactionHandler(lockable, chr);
     }
     else
     {
         LockEntry.log.Error(
             "{0} trying to interact with lockable \"{1}\", but the used InteractionType \"{2}\" is not handled.",
             (object)chr, (object)lockable, (object)type);
     }
 }
Example #35
0
        /// <summary>Close an object</summary>
        public static void Close(ILockable lockable, Character user)
        {
            if (!(lockable is GameObject))
            {
                return;
            }
            GameObject go = lockable as GameObject;

            go.State = GameObjectState.Disabled;
            if (!(go.Map is Battleground))
            {
                return;
            }
            (go.Map as Battleground).OnPlayerClickedOnflag(go, user);
        }
Example #36
0
        public bool CanInsert(object parent, object child)
        {
            var hierarchical = parent.AsAll <IHierarchical>();

            if (hierarchical == null)
            {
                return(false);
            }

            ILockable lockable = parent.As <ILockable>();

            if (lockable != null && lockable.IsLocked)
            {
                return(false);
            }

            DomNode parentNode = parent.As <DomNode>();

            IEnumerable <object> items = Util.ConvertData(child, false);
            bool canInsert             = false;

            foreach (object item in items)
            {
                DomNode childNode = item as DomNode;
                if (parentNode != null && childNode != null)
                {
                    if ((parentNode.IsDescendantOf(childNode) ||
                         parentNode == childNode ||
                         parentNode == childNode.Parent))
                    {
                        return(false);
                    }
                }
                IResource res = item as IResource;
                var       gob = m_resourceConverterService.Convert(res);

                foreach (var h in hierarchical)
                {
                    if (h.CanAddChild(item) || h.CanAddChild(gob))
                    {
                        canInsert = true;
                        break;
                    }
                }
            }

            return(canInsert);
        }
		/// <summary> 
		/// Construct a locking strategy based on SQL UPDATE statements.
		/// </summary>
		/// <param name="lockable">The metadata for the entity to be locked. </param>
		/// <param name="lockMode">Indictates the type of lock to be acquired. </param>
		/// <remarks>
		/// read-locks are not valid for this strategy.
		/// </remarks>
		public UpdateLockingStrategy(ILockable lockable, LockMode lockMode)
		{
			this.lockable = lockable;
			this.lockMode = lockMode;
			if (lockMode.LessThan(LockMode.Upgrade))
			{
				throw new HibernateException("[" + lockMode + "] not valid for update statement");
			}
			if (!lockable.IsVersioned)
			{
				log.Warn("write locks via update not supported for non-versioned entities [" + lockable.EntityName + "]");
				sql = null;
			}
			else
			{
				sql = GenerateLockString();
			}
		}
Example #38
0
        internal void CheckAccess(ILockable lockable, AccessType accessType, int timeout)
        {
            if (accessType == AccessType.ReadWrite) {
                CheckAccess(lockable, AccessType.Read, timeout);
                CheckAccess(lockable, AccessType.Write, timeout);
                return;
            }

            for (int i = locks.Length - 1; i >= 0; --i) {
                var @lock = locks[i];
                if (@lock.Lockable.RefId.Equals(lockable.RefId) &&
                    @lock.AccessType == accessType) {
                    @lock.CheckAccess(accessType, timeout);
                    return;
                }
            }

            throw new Exception("The given object was not found in the lock list for this handle");
        }
Example #39
0
        public LockHandle Lock(ILockable[] lockables, AccessType accessType, LockingMode mode)
        {
            lock (this) {
                int count = 0;
                if ((accessType & AccessType.Read) != 0)
                    count += lockables.Length;
                if ((accessType & AccessType.Write) != 0)
                    count += lockables.Length;

                var handle = new LockHandle(count);

                if ((accessType & AccessType.Read) != 0)
                    AddToHandle(handle, lockables, AccessType.Read, mode);

                if ((accessType & AccessType.Write) != 0)
                    AddToHandle(handle, lockables, AccessType.Write, mode);

                return handle;
            }
        }
 public RelockTimer(Mobile from, ILockable o, TimeSpan delay)
     : base(delay)
 {
     Priority = TimerPriority.TwoFiftyMS;
     m_from = from;
     o_obj = o;
 }
Example #41
0
        private void CheckAccess(ILockable[] lockables, AccessType accessType)
        {
            if (lockHandles == null || lockables == null)
                return;

            foreach (var handle in lockHandles) {
                foreach (var lockable in lockables) {
                    if (handle.IsHandled(lockable))
                        handle.CheckAccess(lockable, accessType);
                }
            }
        }
Example #42
0
 internal LockingQueue(IDatabase database, ILockable lockable)
 {
     Database = database;
     Lockable = lockable;
     locks = new List<Lock>();
 }
Example #43
0
		public override void Initialize(ref SpellFailedReason failReason)
		{
			if (m_cast.Selected != null)
			{
				lockable = m_cast.Selected as GameObject;
			}
			else
			{
				lockable = m_cast.TargetItem;
			}

			if (lockable == null)
			{
				failReason = SpellFailedReason.BadTargets;
			}
			else
			{
				var lck = lockable.Lock;
				var chr = m_cast.CasterChar;

				if (lck == null)
				{
					log.Warn("Using OpenLock on object without Lock: " + lockable);
					failReason = SpellFailedReason.Error;
					return;
				}
				if (chr == null)
				{
					log.Warn("Using OpenLock without Character: " + chr);
					failReason = SpellFailedReason.Error;
					return;
				}

				if (!lck.IsUnlocked)
				{
					var type = (LockInteractionType)Effect.MiscValue;
					if (lck.Keys.Length > 0 && m_cast.CasterItem != null)
					{
						if (!lck.Keys.Contains(key => key.KeyId == m_cast.CasterItem.Template.ItemId))
						{
							failReason = SpellFailedReason.ItemNotFound;
							return;
						}
					}
					else if (!lck.Supports(type))
					{
						failReason = SpellFailedReason.BadTargets;
						return;
					}

					if (type != LockInteractionType.None)
					{
						foreach (var openingMethod in lck.OpeningMethods)
						{
							if (openingMethod.InteractionType == type)
							{
								if (openingMethod.RequiredSkill != SkillId.None)
								{
									skill = chr.Skills[openingMethod.RequiredSkill];
									if (skill == null || skill.ActualValue < openingMethod.RequiredSkillValue)
									{
										failReason = SpellFailedReason.MinSkill;
									}
								}
								method = openingMethod;
								break;
							}
						}

						if (method == null)
						{
							// we are using the wrong kind of spell on the target
							failReason = SpellFailedReason.BadTargets;
						}
					}
				}

				if (failReason != SpellFailedReason.Ok)
				{
					// spell failed
					if (lockable is GameObject && ((GameObject)lockable).Entry.IsConsumable)
					{
						// re-enable GO
						((GameObject)lockable).State = GameObjectState.Enabled;
					}
				}
			}
		}
Example #44
0
 public GlobalMutexScope(string key)
 {
     _concurrentLock = AquireConcurrentLock(key);
 }
Example #45
0
        public void Lock(ILockable[] toWrite, ILockable[] toRead, LockingMode mode)
        {
            lock (Database) {
                if (lockHandles == null)
                    lockHandles = new List<LockHandle>();

                var handle = Database.DatabaseContext.Locker.Lock(toWrite, toRead, mode);
                if (handle != null)
                    lockHandles.Add(handle);
            }
        }
Example #46
0
        private void AddToHandle(LockHandle handle, ILockable[] lockables, AccessType accessType, LockingMode mode)
        {
            if (lockables == null)
                return;

            for (int i = lockables.Length - 1; i >= 0; --i) {
                var lockable = lockables[i];
                var queue = GetQueueFor(lockable);

                handle.AddLock(queue.NewLock(mode, accessType));
            }
        }
 public void Remove(ILockable lockable)
 {
     composite.Remove(lockable);
 }
Example #48
0
		public bool UseOn( Mobile from, ILockable o )
		{
			if ( o.KeyValue == this.KeyValue )
			{
				if ( o is BaseDoor && !((BaseDoor)o).UseLocks() )
				{
					return false;
				}
				else
				{
					o.Locked = !o.Locked;

					if ( o is LockableContainer )
					{
						LockableContainer cont = (LockableContainer)o;

						if ( cont.LockLevel == -255 )
							cont.LockLevel = cont.RequiredSkill - 10;
					}

					if ( o is Item )
					{
						Item item = (Item) o;

						if ( o.Locked )
							item.SendLocalizedMessageTo( from, 1048000 ); // You lock it.
						else
							item.SendLocalizedMessageTo( from, 1048001 ); // You unlock it.

						if ( item is LockableContainer )
						{
							LockableContainer cont = (LockableContainer) item;

							if ( cont.TrapType != TrapType.None && cont.TrapOnLockpick )
							{
								if ( o.Locked )
									item.SendLocalizedMessageTo( from, 501673 ); // You re-enable the trap.
								else
									item.SendLocalizedMessageTo( from, 501672 ); // You disable the trap temporarily.  Lock it again to re-enable it.
							}
						}
					}

					return true;
				}
			}
			else
			{
				return false;
			}
		}
Example #49
0
        private LockingQueue GetQueueFor(ILockable lockable)
        {
            LockingQueue queue;

            if (!queuesMap.TryGetValue(lockable.RefId, out queue)) {
                queue = new LockingQueue(Database, lockable);
                queuesMap[lockable.RefId] = queue;
            }

            return queue;
        }
Example #50
0
		public SelectLockingStrategy(ILockable lockable, LockMode lockMode)
		{
			this.lockable = lockable;
			this.lockMode = lockMode;
			sql = GenerateLockString();
		}
Example #51
0
 public GlobalMutexScope(string key, LockStyle style, TimeSpan cacheTimeout, TimeSpan retryTimeout)
 {
     _concurrentLock = AquireConcurrentLock(key, style, cacheTimeout, retryTimeout);
 }
Example #52
0
 public GlobalMutexScope(string key, LockStyle style)
 {
     _concurrentLock = AquireConcurrentLock(key, style);
 }
            public void Remove(ILockable lockable)
            {
                if(locked)
                    lockable.Unlock();

                lockables.Remove(lockable);
            }
Example #54
0
 public void Lock(ILockable[] toWrite, ILockable[] toRead, LockingMode mode)
 {
 }
 public void Add(ILockable lockable)
 {
     composite.Add(lockable);
 }
Example #56
0
        private LockTimeoutException TimeoutException(ILockable lockable, AccessType accessType, int timeout)
        {
            ObjectName tableName;
            if (lockable is IDbObject) {
                tableName = ((IDbObject) lockable).ObjectInfo.FullName;
            } else {
                tableName = new ObjectName(lockable.RefId.ToString());
            }

            return new LockTimeoutException(tableName, accessType, timeout);
        }
Example #57
0
 /// <summary> 
 /// Get a strategy instance which knows how to acquire a database-level lock
 /// of the specified mode for this dialect. 
 /// </summary>
 /// <param name="lockable">The persister for the entity to be locked. </param>
 /// <param name="lockMode">The type of lock to be acquired. </param>
 /// <returns> The appropriate locking strategy. </returns>
 public virtual ILockingStrategy GetLockingStrategy(ILockable lockable, LockMode lockMode)
 {
     return new SelectLockingStrategy(lockable, lockMode);
 }
Example #58
0
 /*
     Constructor
 */
 public Key(ILockable o)
 {
     m_Object = o;
 }
 public static void Lock(this IUserSession session, LockingMode mode)
 {
     var lockable = new ILockable[] { session.Transaction };
     session.Lock(lockable, lockable, LockingMode.Exclusive);
 }
		/// <summary>
		/// Is the client's lock commensurate with the item in the cache?
		/// If it is not, we know that the cache expired the original
		/// lock.
		/// </summary>
		private bool IsUnlockable( ISoftLock clientLock, ILockable myLock )
		{
			//null clientLock is remotely possible but will never happen in practice
			return myLock != null &&
				myLock.IsLock &&
				clientLock != null &&
				( ( CacheLock ) clientLock ).Id == ( ( CacheLock ) myLock ).Id;
		}