Example #1
0
		/// <summary>
		/// Sends CharacterUnlock to creature's client.
		/// </summary>
		public static void CharacterUnlock(Creature creature, Locks type)
		{
			var packet = new Packet(Op.CharacterUnlock, creature.EntityId);
			packet.PutUInt((uint)type);

			creature.Client.Send(packet);
		}
Example #2
0
        private IProjectFile GetOrCreateSameDestinationFile(
            [NotNull] IProjectModelTransactionCookie cookie,
            [NotNull] IT4File file,
            [NotNull] string destinationName
            )
        {
            Locks.AssertWriteAccessAllowed();
            var existingFile = GetSameDestinationFile(file, destinationName);

            if (existingFile != null)
            {
                return(existingFile);
            }
            return(CreateSameDestinationFile(cookie, file, destinationName));
        }
Example #3
0
        /// <summary>
        /// Gets the active locks.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <Lock.Lock> GetActiveLocks()
        {
            if (Locks == null)
            {
                return(Enumerable.Empty <Lock.Lock>());
            }

            var now = DateTime.Now;

            var activeLocks = Locks
                              .Where(l => l.UnlockedAt > now || l.UnlockedAt == default(DateTime))
                              .ToList();

            return(activeLocks);
        }
Example #4
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are ignored unless the option to convert to C# 7.2 'in' parameters is selected:
//ORIGINAL LINE: private void assertLocksHeld(final Long... expectedResourceIds)
        private void AssertLocksHeld(params Long[] expectedResourceIds)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<long> expectedLockedIds = java.util.Arrays.asList(expectedResourceIds);
            IList <long> expectedLockedIds = Arrays.asList(expectedResourceIds);
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<long> seenLockedIds = new java.util.ArrayList<>();
            IList <long> seenLockedIds = new List <long>();

            Locks.accept((resourceType, resourceId, description, estimatedWaitTime, lockIdentityHashCode) => seenLockedIds.Add(resourceId));

            expectedLockedIds.Sort();
            seenLockedIds.Sort();
            assertEquals("unexpected locked resource ids", expectedLockedIds, seenLockedIds);
        }
Example #5
0
        public void CreateLockTest()
        {
            long currentMaxId = GetMaxLocksId();
            Lock l            = new Lock();

            l.IpAddress         = "10.20.1.1";
            l.LockDate          = DateTime.Now;
            l.UnlockDate        = DateTime.Now.AddDays(1);
            l.Port              = 0;
            l.Status            = Lock.LOCK_STATUS_HARDLOCK;
            l.NumberOfSoftLocks = 2;
            l.TriggerIncident   = 100;
            l.Id = Locks.CreateLock(l);
            Assert.AreEqual(currentMaxId + 1, l.Id);
        }
Example #6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustReleaseUnpreparedLocksOnStop()
        public virtual void MustReleaseUnpreparedLocksOnStop()
        {
            // Given
            ClientA.acquireShared(_tracer, NODE, 1L);
            ClientA.acquireExclusive(_tracer, NODE, 2L);

            // When
            ClientA.stop();

            // The client was stopped before it could enter the prepare phase, so all of its locks are released
            LockCountVisitor lockCountVisitor = new LockCountVisitor();

            Locks.accept(lockCountVisitor);
            assertEquals(0, lockCountVisitor.LockCount);
        }
Example #7
0
        public bool TryGetOrCreateResourceStore(string tenantId, out Task <RavenFileSystem> fileSystem)
        {
            if (ResourcesStoresCache.TryGetValue(tenantId, out fileSystem))
            {
                if (fileSystem.IsFaulted || fileSystem.IsCanceled)
                {
                    ResourcesStoresCache.TryRemove(tenantId, out fileSystem);
                    DateTime time;
                    LastRecentlyUsed.TryRemove(tenantId, out time);
                    // and now we will try creating it again
                }
                else
                {
                    return(true);
                }
            }

            if (Locks.Contains(tenantId))
            {
                throw new InvalidOperationException("FileSystem '" + tenantId + "' is currently locked and cannot be accessed");
            }

            var config = CreateTenantConfiguration(tenantId);

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

            fileSystem = ResourcesStoresCache.GetOrAdd(tenantId, __ => Task.Factory.StartNew(() =>
            {
                var transportState = ResourseTransportStates.GetOrAdd(tenantId, s => new TransportState());
                var fs             = new RavenFileSystem(config, tenantId, transportState);
                AssertLicenseParameters();

                // if we have a very long init process, make sure that we reset the last idle time for this db.
                LastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (_, time) => SystemTime.UtcNow);
                return(fs);
            }).ContinueWith(task =>
            {
                if (task.Status == TaskStatus.Faulted) // this observes the task exception
                {
                    Logger.WarnException("Failed to create filesystem " + tenantId, task.Exception);
                }
                return(task);
            }).Unwrap());
            return(true);
        }
Example #8
0
        private void Disposition(WaitKey key, Action <PendingWait> action)
        {
            if (Waits.TryGetValue(key, out var queue) && queue.TryDequeue(out var wait))
            {
                action(wait);
                wait.Dispose();

                if (Locks.TryGetValue(key, out var recordLock))
                {
                    // enter a read lock first; TryPeek and TryDequeue are atomic so there's no risky operation until later.
                    recordLock.EnterUpgradeableReadLock();

                    try
                    {
                        // clean up entries in the Waits and Locks dictionaries if the corresponding ConcurrentQueue is empty. this is
                        // tricky, because we don't want to remove a record if another thread is in the process of enqueueing a new wait.
                        if (queue.IsEmpty)
                        {
                            // enter the write lock to prevent Wait() (which obtains a read lock) from enqueing any more waits before
                            // we can delete the dictionary record. it's ok and expected that Wait() might add this record back to the
                            // dictionary as soon as this unblocks; we're preventing new waits from being discarded if they are added
                            // by another thread just prior to the TryRemove() operation below.
                            recordLock.EnterWriteLock();

                            try
                            {
                                // check the queue again to ensure Wait() didn't enqueue anything between the last check and when we
                                // entered the write lock. this is guarateed to be safe since we now have exclusive access to the
                                // record and it should be impossible to remove a record containing a non-empty queue
                                if (queue.IsEmpty)
                                {
                                    Waits.TryRemove(key, out _);
                                    Locks.TryRemove(key, out _);
                                }
                            }
                            finally
                            {
                                recordLock.ExitWriteLock();
                            }
                        }
                    }
                    finally
                    {
                        recordLock.ExitUpgradeableReadLock();
                    }
                }
            }
        }
            public override async Task <bool> ShouldShowAsync(AccountDataItem account)
            {
                // Don't show for offline accounts or for devices that aren't Desktop
                if (account == null || !account.IsOnlineAccount || InterfacesUWP.DeviceInfo.DeviceFamily != InterfacesUWP.DeviceFamily.Desktop)
                {
                    return(false);
                }

                if (ApplicationData.Current.RoamingSettings.Values.ContainsKey(SETTING_HAS_PROMOTED_ANDROID_AND_IOS))
                {
                    return(false);
                }

                var dataStore = await AccountDataStore.Get(account.LocalAccountId);

                // If they actually have some classes
                bool hasContent;

                using (await Locks.LockDataForReadAsync())
                {
                    hasContent = dataStore.TableClasses.Count() > 1;
                }

                if (hasContent)
                {
                    // Try downloading and then show
                    ShouldSuggestOtherPlatformsResponse response = await account.PostAuthenticatedAsync <ShouldSuggestOtherPlatformsRequest, ShouldSuggestOtherPlatformsResponse>(
                        Website.URL + "shouldsuggestotherplatforms",
                        new ShouldSuggestOtherPlatformsRequest()
                    {
                        CurrentPlatform = "Windows 10"
                    });

                    if (response.ShouldSuggest)
                    {
                        return(true);
                    }

                    // No need to suggest in the future nor show now
                    MarkShown(account);
                    return(false);
                }
                else
                {
                    // Not enough content to show right now
                    return(false);
                }
            }
        private static async Task <ClassData> LoadDataBlocking(AccountDataStore data, Guid classId, DateTime todayAsUtc, ClassTileSettings settings)
        {
            DateTime dateToStartDisplayingFrom = DateTime.SpecifyKind(settings.GetDateToStartDisplayingOn(todayAsUtc), DateTimeKind.Local);

            Guid semesterId = Guid.Empty;

            // We lock the outside, since we are allowing trackChanges on the view items groups (so we have a chance of loading a cached one)... and since we're on a background thread, the lists inside the
            // view items groups could change while we're enumerating, hence throwing an exception. So we lock it to ensure this won't happen, and then we return a copy of the items that we need.
            using (await Locks.LockDataForReadAsync())
            {
                // First we need to obtain the semester id
                var c = data.TableClasses.FirstOrDefault(i => i.Identifier == classId);

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

                semesterId = c.UpperIdentifier;
            }

            // We need all classes loaded, to know what time the end of day is
            var scheduleViewItemsGroup = await ScheduleViewItemsGroup.LoadAsync(data.LocalAccountId, semesterId, trackChanges : true, includeWeightCategories : false);

            var classViewItemsGroup = await ClassViewItemsGroup.LoadAsync(
                localAccountId : data.LocalAccountId,
                classId : classId,
                today : DateTime.SpecifyKind(todayAsUtc, DateTimeKind.Local),
                viewItemSemester : scheduleViewItemsGroup.Semester,
                includeWeights : false);

            classViewItemsGroup.LoadTasksAndEvents();
            await classViewItemsGroup.LoadTasksAndEventsTask;

            List <ViewItemTaskOrEvent> copied;

            using (await classViewItemsGroup.DataChangeLock.LockForReadAsync())
            {
                // Class view group sorts the items, so no need to sort
                copied = classViewItemsGroup.Class.TasksAndEvents.Where(i => i.Date.Date >= dateToStartDisplayingFrom).ToList();
            }

            return(new ClassData()
            {
                Class = classViewItemsGroup.Class,
                AllUpcoming = copied
            });
        }
Example #11
0
        public bool TryGetOrCreateResourceStore(string tenantId, out Task <DocumentDatabase> database)
        {
            if (ResourcesStoresCache.TryGetValue(tenantId, out database))
            {
                if (database.IsFaulted || database.IsCanceled)
                {
                    ResourcesStoresCache.TryRemove(tenantId, out database);
                    DateTime time;
                    LastRecentlyUsed.TryRemove(tenantId, out time);
                    // and now we will try creating it again
                }
                else
                {
                    return(true);
                }
            }

            if (Locks.Contains(tenantId))
            {
                throw new InvalidOperationException("Database '" + tenantId + "' is currently locked and cannot be accessed");
            }

            var config = CreateTenantConfiguration(tenantId);

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

            database = ResourcesStoresCache.GetOrAdd(tenantId, __ => Task.Factory.StartNew(() =>
            {
                var documentDatabase = new DocumentDatabase(config);
                AssertLicenseParameters(config);
                documentDatabase.SpinBackgroundWorkers();

                // if we have a very long init process, make sure that we reset the last idle time for this db.
                LastRecentlyUsed.AddOrUpdate(tenantId, SystemTime.UtcNow, (_, time) => SystemTime.UtcNow);
                return(documentDatabase);
            }).ContinueWith(task =>
            {
                if (task.Status == TaskStatus.Faulted) // this observes the task exception
                {
                    Logger.WarnException("Failed to create database " + tenantId, task.Exception);
                }
                return(task);
            }).Unwrap());
            return(true);
        }
Example #12
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void prepareMustAllowAcquiringNewLocksAfterStop()
        public virtual void PrepareMustAllowAcquiringNewLocksAfterStop()
        {
            // Given
            ClientA.prepare();
            ClientA.stop();

            // When
            ClientA.acquireShared(_tracer, NODE, 1);
            ClientA.acquireExclusive(_tracer, NODE, 2);

            // Stopped essentially has no effect when it comes after the client has entered the prepare phase
            LockCountVisitor lockCountVisitor = new LockCountVisitor();

            Locks.accept(lockCountVisitor);
            assertEquals(2, lockCountVisitor.LockCount);
        }
Example #13
0
        /// <inheritdoc/>
        protected override void OnDisposeStarted()
        {
            // We are under tree lock here
            // ---------------------------------------------------------

            // This method is not reenterant.
            // ---------------------------------------------------------
            _locks.ForEach(x => x.PulseDispose());

            if (Locks.All(x => x is IxInstanceChildLock))
            {
                SetDisposeSuspended(false);
            }

            base.OnDisposeStarted();
        }
Example #14
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustNotReleaseLocksAfterPrepareOnStop()
        public virtual void MustNotReleaseLocksAfterPrepareOnStop()
        {
            // Given
            ClientA.acquireShared(_tracer, NODE, 1L);
            ClientA.acquireExclusive(_tracer, NODE, 2L);
            ClientA.prepare();

            // When
            ClientA.stop();

            // The client entered the prepare phase, so it gets to keep its locks
            LockCountVisitor lockCountVisitor = new LockCountVisitor();

            Locks.accept(lockCountVisitor);
            assertEquals(2, lockCountVisitor.LockCount);
        }
Example #15
0
 private void UpdateDisposeSuspendState()
 {
     try
     {
         bool nonChildLocksExists = !Locks.All(x => x is IxInstanceChildLock);
         SetDisposeSuspended(nonChildLocksExists);
         if (!nonChildLocksExists && ProviderNode.AutoDisposeEnabled)
         {
             DisposeAsync();
         }
     }
     catch (InvalidOperationException)
     {
         Critical.Assert(false, "Cannot set lock, self dispose was started.");
     }
 }
        private IProjectFile GetSameDestinationFile([NotNull] IT4File file, [NotNull] string temporaryName)
        {
            Locks.AssertWriteAccessAllowed();
            var sourceFile = file.PhysicalPsiSourceFile.NotNull();
            var candidates = sourceFile
                             .ToProjectFile()
                             ?.ParentFolder
                             ?.GetSubItems(temporaryName)
                             .ToList()
                             .OfType <IProjectFile>()
                             .AsList();

            Assertion.AssertNotNull(candidates, "candidates != null");
            Assertion.Assert(candidates.Count <= 1, "candidates.Value.Length <= 1");
            return(candidates.SingleOrDefault());
        }
Example #17
0
        private static void Release([NotNull] object key)
        {
            InnerLock _lock;

            lock (Locks)
            {
                lock (_lock = Locks[key])
                {
                    _lock.Release();
                    if (_lock.CanDispose)
                    {
                        Locks.Remove(key);
                        _lock.Dispose();
                    }
                }
            }
        }
Example #18
0
 public static void UpdateActorLocks(AbstractActor source, ICombatant target, VisualScanType visualLock, SensorScanType sensorLock)
 {
     if (source != null && target != null)
     {
         Locks newLocks = new Locks(source, target, visualLock, sensorLock);
         if (PlayerActorLocks.ContainsKey(source.GUID))
         {
             PlayerActorLocks[source.GUID][target.GUID] = newLocks;
         }
         else
         {
             PlayerActorLocks[source.GUID] = new Dictionary <string, Locks> {
                 [target.GUID] = newLocks
             };
         }
     }
 }
Example #19
0
        public override void BeforeSave(Sungero.Domain.BeforeSaveEventArgs e)
        {
            // Проверка шаблона сайта.
            if (!string.IsNullOrEmpty(_obj.Url))
            {
                _obj.Url = _obj.Url.Trim();
                var error = Functions.DueDiligenceWebsite.CheckDueDiligenceWebsiteUrl(_obj.Url);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    e.AddError(_obj.Info.Properties.Url, error);
                }
            }

            // Проверка шаблона сайта (ИП).
            if (!string.IsNullOrEmpty(_obj.UrlForSelfEmployed))
            {
                _obj.UrlForSelfEmployed = _obj.UrlForSelfEmployed.Trim();
                var error = Functions.DueDiligenceWebsite.CheckDueDiligenceWebsiteUrl(_obj.UrlForSelfEmployed);
                if (!string.IsNullOrWhiteSpace(error))
                {
                    e.AddError(_obj.Info.Properties.UrlForSelfEmployed, error);
                }
            }

            // Если установить для текущего сайта флаг по умолчанию, то с другого сайта этот флаг снимается.
            if (_obj.IsDefault == true)
            {
                var defaultWebsite = Functions.DueDiligenceWebsite.GetDefaultDueDiligenceWebsite();
                if (defaultWebsite != null && !Equals(defaultWebsite, _obj))
                {
                    var lockInfo = Locks.GetLockInfo(defaultWebsite);
                    if (lockInfo != null && lockInfo.IsLocked)
                    {
                        var error = Commons.Resources.LinkedEntityLockedFormat(
                            defaultWebsite.Name,
                            defaultWebsite.Id,
                            lockInfo.OwnerName);
                        e.AddError(error);
                    }

                    defaultWebsite.IsDefault = false;
                }
            }
            _obj.HomeUrl = _obj.HomeUrl.Trim();
        }
Example #20
0
		public T4BuildResult Compile(Lifetime lifetime, IPsiSourceFile sourceFile)
		{
			Logger.Verbose("Compiling a file");
			Locks.AssertReadAccessAllowed();
			// Since we need no context when compiling a file, we need to build the tree manually
			var file = sourceFile.BuildT4Tree();
			var error = file.ThisAndDescendants<IErrorElement>().Collect();
			if (!error.IsEmpty()) return Converter.SyntaxErrors(error);

			return lifetime.UsingNested(nested =>
			{
				try
				{
					// Prepare the code
					var references = ReferenceExtractionManager.ExtractPortableReferencesTransitive(lifetime, file);
					string code = GenerateCode(file);

					// Prepare the paths
					var executablePath = TargetManager.GetTemporaryExecutableLocation(file);
					var compilation = CreateCompilation(code, references, executablePath);
					executablePath.Parent.CreateDirectory();
					var pdbPath = executablePath.Parent.Combine(executablePath.Name.WithOtherExtension("pdb"));

					// Delegate to Roslyn
					var emitOptions = new EmitOptions(
						debugInformationFormat: DebugInformationFormat.PortablePdb,
						pdbFilePath: pdbPath.FullPath
					);
					using var executableStream = executablePath.OpenFileForWriting();
					using var pdbStream = pdbPath.OpenFileForWriting();
					var emitResult = compilation.Emit(
						peStream: executableStream,
						pdbStream: pdbStream,
						options: emitOptions,
						cancellationToken: nested
					);

					return Converter.ToT4BuildResult(emitResult.Diagnostics.AsList(), file);
				}
				catch (T4OutputGenerationException e)
				{
					return Converter.ToT4BuildResult(e);
				}
			});
		}
Example #21
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void mustReleaseReadLockWaitersOnStop()
        public virtual void MustReleaseReadLockWaitersOnStop()
        {
            // Given
            ClientA.acquireExclusive(_tracer, NODE, 1L);
            ClientB.acquireExclusive(_tracer, NODE, 2L);
            AcquireShared(ClientB, _tracer, NODE, 1L).callAndAssertWaiting();

            // When
            ClientB.stop();
            ClientA.stop();

            // All locks clients should be stopped at this point, and all all locks should be released because none of the
            // clients entered the prepare phase
            LockCountVisitor lockCountVisitor = new LockCountVisitor();

            Locks.accept(lockCountVisitor);
            assertEquals(0, lockCountVisitor.LockCount);
        }
Example #22
0
        public static void SaveLog(string testName, string log)
        {
            if (!Locks.TryGetValue(testName, out var lockObject))
            {
                lockObject = new object();
                if (!Locks.TryAdd(testName, lockObject))
                {
                    lockObject = Locks[testName];
                }
            }

            lock (lockObject)
            {
                var filePath = System.IO.Path.Combine(Path, testName + ".txt");
                Directory.CreateDirectory(Path);
                File.AppendAllLines(filePath, new[] { log });
            }
        }
Example #23
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp()
        public virtual void SetUp()
        {
            _master = mock(typeof(Master));
            _databaseAvailabilityGuard = new DatabaseAvailabilityGuard(DEFAULT_DATABASE_NAME, Clocks.fakeClock(), Instance);

            _lockManager = new CommunityLockManger(Config.defaults(), Clocks.systemClock());
            _local       = spy(_lockManager.newClient());
            _logProvider = new AssertableLogProvider();

            LockResult lockResultOk = new LockResult(LockStatus.OkLocked);
            TransactionStreamResponse <LockResult> responseOk = new TransactionStreamResponse <LockResult>(lockResultOk, null, Org.Neo4j.com.TransactionStream_Fields.Empty, Org.Neo4j.com.ResourceReleaser_Fields.NoOp);

            WhenMasterAcquireShared().thenReturn(responseOk);

            WhenMasterAcquireExclusive().thenReturn(responseOk);

            _client = new SlaveLocksClient(_master, _local, _lockManager, mock(typeof(RequestContextFactory)), _databaseAvailabilityGuard, _logProvider);
        }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void loadSimpleStatementLocksFactoryWhenNoServices()
        public virtual void LoadSimpleStatementLocksFactoryWhenNoServices()
        {
            Locks        locks       = mock(typeof(Locks));
            Locks_Client locksClient = mock(typeof(Locks_Client));

            when(locks.NewClient()).thenReturn(locksClient);

            StatementLocksFactorySelector loader = NewLoader(locks);

            StatementLocksFactory factory        = loader.Select();
            StatementLocks        statementLocks = factory.NewInstance();

            assertThat(factory, instanceOf(typeof(SimpleStatementLocksFactory)));
            assertThat(statementLocks, instanceOf(typeof(SimpleStatementLocks)));

            assertSame(locksClient, statementLocks.Optimistic());
            assertSame(locksClient, statementLocks.Pessimistic());
        }
Example #25
0
        public override async Task <T> InvokeAndStrip(
            ComputeMethodInput input, IComputed?usedBy, ComputeContext?context,
            CancellationToken cancellationToken = default)
        {
            context ??= ComputeContext.Current;
            ResultBox <T>?output;

            // Read-Lock-RetryRead-Compute-Store pattern

            var computed = TryGetExisting(input);

            if (computed != null)
            {
                output = await computed.TryUseExisting(context, usedBy, cancellationToken)
                         .ConfigureAwait(false);

                if (output != null)
                {
                    return(output.Value);
                }
            }

            using var @lock = await Locks.Lock(input, cancellationToken).ConfigureAwait(false);

            computed = TryGetExisting(input);
            if (computed != null)
            {
                output = await computed.TryUseExisting(context, usedBy, cancellationToken)
                         .ConfigureAwait(false);

                if (output != null)
                {
                    return(output.Value);
                }
            }

            computed = (IAsyncComputed <T>) await Compute(input, computed, cancellationToken)
                       .ConfigureAwait(false);

            var rOutput = computed.Output; // RenewTimeouts isn't called yet, so it's ok

            computed.UseNew(context, usedBy);
            return(rOutput !.Value);
        }
Example #26
0
        private ConcurrentBigSet(
            int concurrencyLevel,
            BigBuffer <TItem> backingItemsBuffer,
            BigBuffer <Node> backingNodesBuffer,
            Buckets backingBuckets,
            int nodeLength,
            int capacity = DefaultCapacity,
            int ratio    = DefaultBucketToItemsRatio,
            int itemsPerEntryBufferBitWidth = 12)
        {
            Contract.Requires(concurrencyLevel >= 1);
            Contract.Requires(ratio >= 1);

            concurrencyLevel = Math.Max(concurrencyLevel, MinConcurrencyLevel);
            if (concurrencyLevel > capacity)
            {
                capacity = concurrencyLevel;
            }

            var actualConcurrencyLevel = (int)Bits.HighestBitSet((uint)concurrencyLevel);
            var actualCapacity         = (int)Bits.HighestBitSet((uint)capacity);

            capacity         = capacity > actualCapacity ? actualCapacity << 1 : actualCapacity;
            concurrencyLevel = concurrencyLevel > actualConcurrencyLevel ? actualConcurrencyLevel << 1 : actualConcurrencyLevel;

            m_locks = new Locks(concurrencyLevel);

            // Create free node pointer for every lock
            m_freeNodes = new int[m_locks.Length];
            for (int i = 0; i < m_freeNodes.Length; i++)
            {
                m_freeNodes[i] = -1;
            }

            m_lockBitMask = concurrencyLevel - 1;

            m_items   = backingItemsBuffer ?? new BigBuffer <TItem>(itemsPerEntryBufferBitWidth);
            m_nodes   = backingNodesBuffer ?? new BigBuffer <Node>(NodesPerEntryBufferBitWidth);
            m_buckets = backingBuckets ?? new Buckets(capacity, ratio);

            m_nodeLength = nodeLength;
            m_accessors  = new Accessors(this);
        }
Example #27
0
 public void BeginGuardedOperation()
 {
     lock (sync)
     {
         if (lockID == Guid.Empty)
         {
             throw new InvalidOperationException("Guarded operation " +
                                                 "was blocked because no lock has been obtained.");
         }
         object currentLock;
         Locks.TryGetValue(lockID, out currentLock);
         if (currentLock != SlotMarker)
         {
             throw new InvalidOperationException("Guarded operation " +
                                                 "was blocked because the lock was obtained on a " +
                                                 "different thread from the calling thread.");
         }
     }
 }
Example #28
0
        public override void Deleting(Sungero.Domain.DeletingEventArgs e)
        {
            var document = _obj.DocumentGroup.OfficialDocuments.FirstOrDefault();

            if (document == null || Locks.GetLockInfo(document).IsLocked)
            {
                return;
            }

            // Удалить записи о выдаче документа (иначе не даст удалить из-за зависимостей).
            var tracking = document.Tracking.Where(r => Equals(r.ReturnTask, _obj)).ToList();

            foreach (var row in tracking)
            {
                row.ReturnTask = null;
            }

            document.Save();
        }
Example #29
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
//ORIGINAL LINE: private static KernelTransactions newKernelTransactions(boolean testKernelTransactions, TransactionCommitProcess commitProcess, org.neo4j.storageengine.api.StorageReader firstReader, org.neo4j.storageengine.api.StorageReader... otherReaders) throws Throwable
        private static KernelTransactions NewKernelTransactions(bool testKernelTransactions, TransactionCommitProcess commitProcess, StorageReader firstReader, params StorageReader[] otherReaders)
        {
            Locks locks = mock(typeof(Locks));

            Org.Neo4j.Kernel.impl.locking.Locks_Client client = mock(typeof(Org.Neo4j.Kernel.impl.locking.Locks_Client));
            when(locks.NewClient()).thenReturn(client);

            StorageEngine storageEngine = mock(typeof(StorageEngine));

            when(storageEngine.NewReader()).thenReturn(firstReader, otherReaders);
            doAnswer(invocation =>
            {
                ICollection <StorageCommand> argument = invocation.getArgument(0);
                argument.add(mock(typeof(StorageCommand)));
                return(null);
            }).when(storageEngine).createCommands(anyCollection(), any(typeof(ReadableTransactionState)), any(typeof(StorageReader)), any(typeof(ResourceLocker)), anyLong(), any(typeof(TxStateVisitor.Decorator)));

            return(NewKernelTransactions(locks, storageEngine, commitProcess, testKernelTransactions));
        }
Example #30
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void newInstanceCreatesDeferredLocksWhenConfigSet()
        public virtual void NewInstanceCreatesDeferredLocksWhenConfigSet()
        {
            Locks        locks  = mock(typeof(Locks));
            Locks_Client client = mock(typeof(Locks_Client));

            when(locks.NewClient()).thenReturn(client);

            Config config = Config.defaults(deferred_locks_enabled, Settings.TRUE);

            DeferringStatementLocksFactory factory = new DeferringStatementLocksFactory();

            factory.Initialize(locks, config);

            StatementLocks statementLocks = factory.NewInstance();

            assertThat(statementLocks, instanceOf(typeof(DeferringStatementLocks)));
            assertThat(statementLocks.Optimistic(), instanceOf(typeof(DeferringLockClient)));
            assertSame(client, statementLocks.Pessimistic());
        }
Example #31
0
        public override void BeforeSave(Sungero.Domain.BeforeSaveEventArgs e)
        {
            Functions.Employee.UpdateName(_obj, _obj.Person);

            if (string.IsNullOrEmpty(_obj.Name))
            {
                _obj.Name = " ";
            }

            if (!Functions.Employee.IsValidEmail(_obj.Email))
            {
                e.AddWarning(_obj.Info.Properties.Email, Parties.Resources.WrongEmailFormat);
            }
            else if (!Docflow.PublicFunctions.Module.IsASCII(_obj.Email))
            {
                e.AddWarning(_obj.Info.Properties.Email, Docflow.Resources.ASCIIWarning);
            }

            var oldDepartment = _obj.State.Properties.Department.OriginalValue;
            var newDepartment = _obj.Department;

            if (!Equals(oldDepartment, newDepartment))
            {
                if (newDepartment != null)
                {
                    var newDepartmentLockInfo = Locks.GetLockInfo(newDepartment);
                    if (newDepartmentLockInfo.IsLockedByOther)
                    {
                        e.AddError(Employees.Resources.DeparmentLockedByUserFormat(newDepartment.Name, newDepartmentLockInfo.OwnerName));
                    }
                }

                if (oldDepartment != null)
                {
                    var oldDepartmentLockInfo = Locks.GetLockInfo(oldDepartment);
                    if (oldDepartmentLockInfo.IsLockedByOther)
                    {
                        e.AddError(Employees.Resources.DeparmentLockedByUserFormat(oldDepartment.Name, oldDepartmentLockInfo.OwnerName));
                    }
                }
            }
        }