Example #1
0
        public FolderViewService(ListView listViewFolders, string packageCachePath, int updateCount = 100) : base(ThreadPriority.Normal, 100, 20000, 20000)
        {
            cacheDirectory = new DirectoryInfo(packageCachePath);

            lockObject = LockManager.CreateObject();

            backingList = cacheDirectory.GetFileSystemInfos().OrderBy(i => i is FileInfo ? 1 : 0).ThenBy(i => i.Name).ToList();

            this.listViewFolders  = listViewFolders;
            this.updateCount      = updateCount;
            this.packageCachePath = packageCachePath;

            fileSystemWatcher = new FileSystemWatcher(packageCachePath);
            fileSystemWatcher.EnableRaisingEvents = true;

            fileSystemWatcher.Created += FileSystemWatcher_Created;
            fileSystemWatcher.Changed += FileSystemWatcher_Changed;
            fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;

            this.listViewFolders.VirtualListSize = backingList.Count;
            this.listViewFolders.VirtualMode     = true;
            this.listViewFolders.Scrollable      = true;

            listViewFolders.RetrieveVirtualItem += ListViewFolders_RetrieveVirtualItem;
        }
Example #2
0
        public PackageCacheService(string root, string packageCachePath) : base(ThreadPriority.Lowest, TimeSpan.FromMilliseconds(1000), TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(15))
        {
            this.root             = root;
            this.packageCachePath = packageCachePath;
            this.logWriter        = new LogWriter(Path.Combine(this.packageCachePath, "Log.txt"));

            sweepsPath                 = Path.Combine(packageCachePath, "sweeps");
            nodeModulesPath            = Path.Combine(root, "node_modules");
            pathsToProcess             = new List <string>();
            pathsToNotProcess          = new List <string>();
            pathsProcessed             = new Dictionary <string, List <PathCacheStatus> >();
            installsFromCacheToProcess = new Dictionary <string, PackageWorkingInstallFromCache>();
            statusStack                = new Stack <CacheStatusType>();
            cacheStatusType            = CacheStatusType.Initialized;
            lockObject                 = LockManager.CreateObject();
            memoryStatus               = MemoryStatus.Create();
            currentActionVerb          = "No current action";
            packageModules             = new NpmNodeModules(nodeModulesPath);

            this.NothingToPoll = true;

            if (!Directory.Exists(nodeModulesPath))
            {
                Directory.CreateDirectory(nodeModulesPath);
            }

            fileSystemWatcher = new FileSystemWatcher(nodeModulesPath);
            fileSystemWatcher.EnableRaisingEvents = true;

            fileSystemWatcher.Created += FileSystemWatcher_Created;
            fileSystemWatcher.Changed += FileSystemWatcher_Changed;
        }
Example #3
0
        public static AjaxResult AddPassword(string id, string deviceId, string password, string startDate, string endDate, string locktype)
        {
            NewLockManager managerNew = new NewLockManager();
            string         start      = managerNew.GetDateTime(startDate).ToString();
            string         end        = managerNew.GetDateTime(endDate).ToString();

            if (locktype == "1") //新锁
            {
                string type       = startDate == endDate ? "1" : "2";
                string returnDate = managerNew.GetPostInterface(deviceId, "Admin", type, password, start, end);
                Dictionary <string, object> returnInfo = new Dictionary <string, object>();
                returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(returnDate);
                if (returnInfo["ret"].ToString() == "1")
                {
                    return(AjaxResult.Error(returnInfo["msg"].ToString()));
                }
            }
            else
            {
                LockManager manager = new LockManager();
                manager.AddPassword(deviceId, password, startDate, endDate);

                string ret = manager.UpdatePassengerInfoToDevice(deviceId, "", "", "", password, DateTime.Parse(start).ToString("yyyyMMddHHmm").Substring(2, 10), DateTime.Parse(end).ToString("yyyyMMddHHmm").Substring(2, 10), "3");
            }

            return(AjaxResult.Success());
        }
Example #4
0
        private static void DumpLockInfo(string[] paths)
        {
            var infos = LockManager.GetLockingProcessInfos(paths, LockManagerFeatures.UseLowLevelApi);

            if (!infos.Any())
            {
                Console.WriteLine("No locking processes found.");
                return;
            }

            bool first = true;

            foreach (var p in infos)
            {
                if (!first)
                {
                    Console.WriteLine("----------------------------------------------------");
                }

                Console.WriteLine("Process ID        : {0}", p.ProcessId);
                Console.WriteLine("Process Start Time: {0}", p.StartTime.ToString("F"));
                Console.WriteLine("Process File Path : {0}", p.ExecutableFullPath);
                Console.WriteLine("Process User Name : {0}", p.Owner);
                Console.WriteLine("Executable  Name  : {0}", p.ExecutableName);
                Console.WriteLine("Application Name  : {0}", p.ApplicationName);
                Console.WriteLine("Session ID        : {0}", p.SessionId);
                first = false;
            }
        }
Example #5
0
        public static AjaxResult DeleteDevice(string ID)
        {
            LockManager manager = new LockManager();

            manager.DeleteLockDevice(ID);
            return(AjaxResult.Success());
        }
Example #6
0
        public static AjaxResult UnFreezeDevice(string ID)
        {
            LockManager manager = new LockManager();

            manager.UnFreezeICCard(ID);
            return(AjaxResult.Success());
        }
Example #7
0
 public static void RestartLDMAndUnlockDisksAndVolumes()
 {
     // We stop LDM before unlocking the disk (not sure if it's necessary to do so before unlocking the disks, but better safe than sorry)
     StopLogicalDiskManagerServices();
     LockManager.UnlockAllDisksAndVolumes();
     StartLogicalDiskManagerServices(false);
 }
        /// <summary>
        /// Retrieves a cached object or loads the object if it does not exist in cache.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cache"></param>
        /// <param name="cacheKey"></param>
        /// <param name="load"></param>
        /// <param name="insert"></param>
        /// <param name="regionName"></param>
        /// <returns></returns>
        public virtual T Get <T>(
            ObjectCache cache,
            string cacheKey,
            Func <ObjectCache, T> load,
            Action <ObjectCache, T> insert,
            string regionName = null)
        {
            return(LockManager.Get(
                       cacheKey,
                       // try to load from cache
                       key => this.GetCacheItemValue(cache, key.ToLower(), regionName),
                       key =>
            {
                // load object from the service

                var obj = load(cache);

                if (insert != null)
                {
                    // insert object into cache

                    insert(cache, obj);
                }

                return obj;
            }));
        }
Example #9
0
        public async Task LockManager_BasicTest()
        {
            LockManager <int, int> lockManager = new LockManager <int, int>();
            await lockManager.AcquireLock(1, 1, LockMode.Update);

            await lockManager.AcquireLock(1, 2, LockMode.Update);

            await lockManager.AcquireLock(1, 3, LockMode.Update);

            Task[] tasks = new Task[]
            {
                lockManager.AcquireLock(2, 1, LockMode.Update),
                lockManager.AcquireLock(3, 2, LockMode.Update),
                lockManager.AcquireLock(4, 3, LockMode.Update),
            };

            lockManager.ReleaseLocks(1);
            Task.WaitAll(tasks);

            lockManager.ReleaseLocks(2);
            lockManager.ReleaseLocks(3);

            await lockManager.AcquireLock(5, 1, LockMode.Default);

            await lockManager.AcquireLock(5, 2, LockMode.Default);

            await Assert.ThrowsExceptionAsync <TimeoutException>(
                async() =>
            {
                await lockManager.AcquireLock(5, 3, LockMode.Default, timeout: TimeSpan.FromMilliseconds(10));
            }
                );
        }
        LockManager GetLockManager(string containerName)
        {
            var container = _blobs.GetContainerReference(containerName);
            var manager   = new LockManager(container, TimeSpan.FromSeconds(20));

            return(manager);
        }
Example #11
0
    public string ClearPasswordToLock(string aarId)
    {
        Dictionary <string, string> dic = new Dictionary <string, string>();
        RentAttribute a      = new RentAttribute(int.Parse(aarId));
        DataTable     dt     = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand("select * from Rent_Locks where rentno='" + a.RentNo + "'")).Tables[0];
        string        lockID = dt.Rows.Count.ToString();
        string        a1     = a.RRAStartDate.ToString("yyyy-MM-dd HH:mm:ss");
        string        a2     = a.RRAEndDate.ToString("yyyy-MM-dd HH:mm:ss");
        ////LockID='" + dt.Rows[0]["DeviceID"].ToString() + "' and StartDate='" + a1 + "' and EndDate='" + a2 + "'
        //string sql = "select * from Rent_Locks_ICCards where LockID='" + dt.Rows[0]["DeviceID"].ToString() + "' and StartDate='" + a.RRAStartDate.ToString("yyyy-MM-dd HH:mm:ss") + "' and EndDate='" + a.RRAEndDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";
        string sql = "select * from Rent_Locks_ICCards where LockID='" + lockID + "'";

        LockManager manager = new LockManager();
        DataTable   dt1     = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];

        foreach (DataRow row in dt1.Rows)
        {
            string returnStr = manager.UpdatePassengerInfoToDevice(dt.Rows[0]["DeviceID"].ToString(), row["ICCard"].ToString(), "", "", "", a.RRAStartDate.ToString("yyyyMMddHHmm").Substring(2, 10), a.RRAEndDate.ToString("yyyyMMddHHmm").Substring(2, 10), "2");
        }

        if (dt.Rows.Count > 0)
        {
            string returnStr = manager.UpdatePassengerInfoToDevice(dt.Rows[0]["DeviceID"].ToString(), "", "", "", a.RRANationName, a.RRAStartDate.ToString("yyyyMMddHHmm").Substring(2, 10), a.RRAEndDate.ToString("yyyyMMddHHmm").Substring(2, 10), "4");


            dic.Add("ret", "0");
            dic.Add("msg", returnStr);
        }
        else
        {
            dic.Add("ret", "1");
            dic.Add("msg", "未发现智能锁信息,无法添加密码");
        }
        return(JSONHelper.ToJson(dic));
    }
Example #12
0
        internal override async Task DoCommandAsync()
        {
            _code = HttpStatusCodes.SuccessOk;
            var buffer = new byte[ProgramCostants.DefautBufferSize];
            var offset = 0;

            try {
                int count;
                while (0 < (count = await _inputStream.ReadAsync(buffer, offset, buffer.Length - offset)))
                {
                    offset += count;
                }
            } catch (HttpListenerException e) {
                Console.WriteLine(e.Message);
            }
            _content = Encoding.UTF8.GetString(buffer, 0, offset);
            Logger.Trace(_content);
            _inputStream.Close();
            if (!_content.Any())
            {
                return;
            }
            LockHelper.ParseLockContent(_content, this);
            LockManager.GetInstanse()
            .LockFile(_mFileName, new LockInfo(_mFileName, _mLockType, _mLockScope, _mDepth, _mOwner, _mFileName));
        }
Example #13
0
        private void SetUp(int numSymbols, int numThreads, int numEvents, double timeWindowSize)
        {
            EPServiceProvider epService = EPServiceProviderManager.GetDefaultProvider(SupportConfigFactory.GetConfiguration());

            epService.Initialize();

            // Create a statement for Count number of symbols, each it's own listener
            var symbols = new String[numSymbols];

            _listeners = new ResultUpdateListener[symbols.Length];
            for (int i = 0; i < symbols.Length; i++)
            {
                var index = i;
                symbols[i] = "S" + i;
                String viewExpr = "select Symbol, sum(Volume) as sumVol " +
                                  "from " + typeof(SupportMarketDataBean).FullName +
                                  "(Symbol='" + symbols[i] + "').win:time(" + timeWindowSize + ")";
                EPStatement testStmt = epService.EPAdministrator.CreateEPL(viewExpr);
                _listeners[i]    = new ResultUpdateListener();
                testStmt.Events += (s, e) => _listeners[index].Update(e.NewEvents, e.OldEvents);
            }

            // Create threads to send events
            _threads = new List <Thread>();
            var @lock = LockManager.CreateDefaultLock();

            for (int i = 0; i < numThreads; i++)
            {
                var runnable = new TimeWinRunnable(i, epService.EPRuntime, @lock, symbols, numEvents);
                _threads.Add(new Thread(runnable.Run));
            }
        }
Example #14
0
    private bool UnlockIapItem(string iapKey)
    {
        LockManager.IAP_TYPE iapType = LockManager.IAP_TYPE.NONE;
        bool isUnlock = true;

        if (iapKey == GameManager.Instance.KEY_FULL)
        {
            LockManager.UnlockFull();
            iapType = LockManager.IAP_TYPE.FULL;
        }
        else
        {
            isUnlock = false;
        }
        if (true == isUnlock)
        {
            UIManager.ShowMsgBox("Thank you for your purchase.");
        }
        else
        {
            UIManager.ShowMsgBox(string.Format("Purchase Product '{0}' Fail.", iapKey));
        }
        if (null != _iapCallback && iapType != LockManager.IAP_TYPE.NONE)
        {
            _iapCallback(iapType);
        }
        Close();
        return(isUnlock);
    }
        ///<inheritdoc>
        public async Task LockAsync(LockMode lockMode)
        {
            Logger.LogMessage($"{nameof(ILock)}.{nameof(LockAsync)}()", UserFileSystemPath);

            ExternalDataManager customDataManager = Engine.CustomDataManager(UserFileSystemPath, Logger);
            LockManager         lockManager       = customDataManager.LockManager;

            if (!await lockManager.IsLockedAsync() &&
                !Engine.CustomDataManager(UserFileSystemPath).IsNew)
            {
                // Set pending icon, so the user has a feedback as lock operation may take some time.
                await customDataManager.SetLockPendingIconAsync(true);

                // Call your remote storage here to lock the item.
                // Save the lock token and other lock info received from the remote storage on the client.
                // Supply the lock-token as part of each remote storage update in File.WriteAsync() method.
                // For demo purposes we just fill some generic data.
                ServerLockInfo lockInfo = new ServerLockInfo()
                {
                    LockToken = "ServerToken", Owner = "You", Exclusive = true, LockExpirationDateUtc = DateTimeOffset.Now.AddMinutes(30)
                };

                // Save lock-token and lock-mode.
                await lockManager.SetLockInfoAsync(lockInfo);

                await lockManager.SetLockModeAsync(lockMode);

                // Set lock icon and lock info in custom columns.
                await customDataManager.SetLockInfoAsync(lockInfo);

                Logger.LogMessage("Locked in remote storage succesefully.", UserFileSystemPath);
            }
        }
        public ActionResult Index()
        {
            Response.Clear();
            Response.ContentType = "text/plain";

            var product = new Product {
                Id = 1, Name = "Heineken", Price = 1.2M
            };

            if (!LockManager.Lock(product, Session.SessionID))
            {
                Response.Write("Object has already lock on it!\r\n");
                Response.End();
                return(null);
            }

            Response.Write("Object successfully locked\r\n");
            Response.Flush();
            Thread.Sleep(20000);

            Response.Write("Releasing lock\r\n");
            LockManager.ReleaseLock(product, Session.SessionID);
            Response.Write("Lock released\r\n");

            Response.End();
            return(null);
        }
Example #17
0
            internal PipLock(LockManager owner, PipId pipId1, PipId pipId2, object accessVerifier)
            {
                Contract.Requires(owner != null);
                Contract.Requires(pipId1.IsValid);
                Contract.Assert(owner.m_accessVerifier == accessVerifier, "PipLocks can only be created by a parent LockManager");

                m_owner = owner;
#if DEBUG
                m_owner.m_outstandingNonGlobalLocks.Value = m_owner.m_outstandingNonGlobalLocks.Value + 1;
#endif

                // Try to acquire the global shared lock
                m_globalSharedLock = owner.AcquireGlobalSharedLockIfApplicable();

                m_minScope = owner.m_scopedPipLockMap.OpenScope(pipId1);
                m_minScope.Value.EnterWriteLock();

                // Second pip id may be invalid if this is only being used to lock a single pip
                if (pipId2.IsValid)
                {
                    m_maxScope = owner.m_scopedPipLockMap.OpenScope(pipId2);
                    m_maxScope.Value.EnterWriteLock();
                }
                else
                {
                    m_maxScope = default(ScopedReferenceMap <PipId, ReadWriteLock> .Scope);
                }
            }
Example #18
0
 /// <summary>
 /// Deserializa os dados na instancia.
 /// </summary>
 /// <param name="reader"></param>
 public void Deserialize(CompactReader reader)
 {
     lock (this)
     {
         this.Value         = reader.ReadObject();
         _flags             = new BitSet(reader.ReadByte());
         _evictionHint      = EvictionHint.ReadEvcHint(reader);
         _expirationHint    = ExpirationHint.ReadExpHint(reader);
         _grpInfo           = GroupInfo.ReadGrpInfo(reader);
         _syncDependency    = reader.ReadObject() as Colosoft.Caching.Synchronization.CacheSyncDependency;
         _queryInfo         = (Hashtable)reader.ReadObject();
         _keysDependingOnMe = (Hashtable)reader.ReadObject();
         _size               = reader.ReadInt32();
         _lockId             = reader.ReadObject();
         _lockDate           = reader.ReadDateTime();
         _version            = reader.ReadUInt64();
         _lockExpiration     = reader.ReadObject() as LockExpiration;
         _creationTime       = reader.ReadDateTime();
         _lastModifiedTime   = reader.ReadDateTime();
         _resyncProviderName = reader.ReadObject() as string;
         _priorityValue      = (CacheItemPriority)reader.ReadInt32();
         _lockManager        = reader.ReadObject() as LockManager;
         _providerName       = reader.ReadObject() as string;
     }
 }
        public ChangeRequestTask GetChangeRequestTaskByIdForEdit(int id, string currentUser)
        {
            using (var transaction = _appDataContext.Database.BeginTransaction(System.Data.IsolationLevel.Serializable))
            {
                try
                {
                    LockManager lockManager = new LockManager(_appDataContext);
                    lockManager.AcquireLock(id, "ChangeRequestTask", currentUser);

                    ChangeRequestTask crt = _appDataContext.ChangeRequestTasks.Where(c => c.ID == id).SingleOrDefault();
                    if (crt != null)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        throw new ConcurrencyException(
                                  "Entity not found. Entity man have been deleted by another user.");
                    }

                    return(crt);
                }
                catch (ConcurrencyException ex)
                {
                    transaction.Rollback();
                    string newMessage = ex.Message.Replace("Entity", "Change Request Task " + id.ToString("D5"));
                    throw new ConcurrencyException(newMessage);
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
Example #20
0
 /// <summary>Ctor. </summary>
 /// <param name="knownTypes">types known at cache construction type, may be an empty list for the ANY type variance.</param>
 public VariantPropertyGetterCache(EventType[] knownTypes)
 {
     _iLock      = LockManager.CreateLock(GetType());
     _knownTypes = knownTypes;
     _allGetters = new Dictionary <EventType, VariantPropertyGetterRow>();
     _properties = new List <String>();
 }
Example #21
0
        ///<inheritdoc>
        public async Task UnlockAsync()
        {
            if (MsOfficeHelper.IsMsOfficeLocked(UserFileSystemPath)) // Required for PowerPoint. It does not block the for writing.
            {
                throw new ClientLockFailedException("The file is blocked for writing.");
            }

            ExternalDataManager customDataManager = Engine.CustomDataManager(UserFileSystemPath, Logger);
            LockManager         lockManager       = customDataManager.LockManager;

            // Set pending icon, so the user has a feedback as unlock operation may take some time.
            await customDataManager.SetLockPendingIconAsync(true);

            // Read lock-token from lock-info file.
            string lockToken = (await lockManager.GetLockInfoAsync()).LockToken;

            // Unlock the item in the remote storage.
            try
            {
                await Program.DavClient.UnlockAsync(new Uri(RemoteStoragePath), lockToken);
            }
            catch (ITHit.WebDAV.Client.Exceptions.ConflictException)
            {
                // The item is already unlocked.
            }

            // Delete lock-mode and lock-token info.
            lockManager.DeleteLock();

            // Remove lock icon and lock info in custom columns.
            await customDataManager.SetLockInfoAsync(null);

            Logger.LogMessage("Unlocked in the remote storage succesefully", UserFileSystemPath);
        }
Example #22
0
        private void MasterKeySynchProc()
        {
            string MasterKey = null;
            string CreateDateStr;

            //---母码部分--------------------------------------------------------------------------------------------------------------
            for (int i = 0; i < 6; i++)
            {
                MasterKey = MasterKey + this.MyReadBuffers[22 + i].ToString();
            }
            CreateDateStr = Encoding.ASCII.GetString(this.MyReadBuffers, 28, 15);

            //CreateDateStr = CreateDateStr.Insert(4, "-");
            //CreateDateStr = CreateDateStr.Insert(7, "-");
            //CreateDateStr = CreateDateStr.Insert(10, " ");
            ///CreateDateStr = CreateDateStr.Insert(13, ":");
            //CreateDateStr = CreateDateStr.Insert(16, ":");

            MyAsynchLockServerSocketService.DisplayResultInfor(1, string.Format("[{0}]母码修改为[{1}]", MyLockIDStr, MasterKey));

            //LockManager MyLockManager = new LockManager();
            //MyLockManager.UpdateMasterKey(MyLockIDStr, MasterKey);//--保存数据库

            LockManager MyLockManager = new LockManager();

            MyLockManager.UpdateMasterKey(MyLockIDStr, MasterKey); //--保存数据库
        }
        public void No_deadlock_and_no_race_condition_on_resources()
        {
            var mgr = new LockManager();

            var watch = new Stopwatch();

            watch.Start();

            int iterations = 10_000;

            Parallel.For(0, iterations, i =>
            {
                Parallel.Invoke(
                    () => mgr.DoWithReadLock(ReadAbc, "a", "b", "c"),
                    () => mgr.DoWithReadLock(ReadA, "a"),
                    () => mgr.DoWithWriteLock(WriteAbc, "a", "b", "c"),
                    () => mgr.DoWithWriteLock(WriteA, "a")
                    );
            });

            watch.Stop();

            Console.WriteLine($"{iterations} iterations took {watch.ElapsedMilliseconds} ms");
            Console.WriteLine($"retries = {mgr.Retries}");
            Console.WriteLine($"a = {_resourceA.Count} b = {_resourceB.Count} c = {_resourceC.Count}");


            int locks = mgr.GetCurrentlyHoldLocks();

            Assert.AreEqual(0, locks);
        }
Example #24
0
 public void IapUnlock(LockManager.IAP_TYPE iapType, UnlockAnimCallbackWithItem callback = null)
 {
     if (iapType == LockManager.IAP_TYPE.FULL)
     {
         if (LockManager.IsFullUnlocked())
         {
             bool hasCallback = false;
             if (null != _arrayCharactersLockItem && _arrayCharactersLockItem.Length > 0)
             {
                 UnlockItemArray(_arrayCharactersLockItem, callback);
                 hasCallback = true;
             }
             if (null != _arrayAccessoriesLockItem && _arrayAccessoriesLockItem.Length > 0)
             {
                 UnlockItemArray(_arrayAccessoriesLockItem, callback);
                 hasCallback = true;
             }
             if (null != _arrayDecorationsLockItem && _arrayDecorationsLockItem.Length > 0)
             {
                 UnlockDecorationItemArray(_arrayDecorationsLockItem, callback);
                 hasCallback = true;
             }
             if (false == hasCallback)
             {
                 callback();
             }
         }
     }
     CheckHideShop();
 }
Example #25
0
 public SupportMTUpdateListener()
 {
     _id          = string.Empty;
     _oLock       = LockManager.CreateLock(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     _newDataList = new List <EventBean[]>();
     _oldDataList = new List <EventBean[]>();
 }
        public void Consistent_read_sessions()
        {
            ILockManager lockManager = new LockManager(null);

            var session = Guid.NewGuid();

            lockManager.AcquireLock(session, false, "x", "y", "z");


            bool success = lockManager.CheckLock(session, false, "x");

            Assert.IsTrue(success);


            // try with a new session (should not work)
            success = lockManager.CheckLock(Guid.NewGuid(), false, "x");
            Assert.IsFalse(success);

            // read-only lock so it should not work
            success = lockManager.CheckLock(session, true, "x");
            Assert.IsFalse(success);

            // different resource so it should not work
            success = lockManager.CheckLock(session, true, "nope");
            Assert.IsFalse(success);


            // trying to close an inactive session throws an exception
            Assert.Throws <NotSupportedException>(() => lockManager.CloseSession(Guid.NewGuid()));
        }
        public static DiskGroupLockResult LockDiskGroup(List <DynamicDisk> diskGroup)
        {
            // Lock disks and volumes
            LockStatus status = LockManager.LockDynamicDiskGroup(diskGroup, true);

            if (status != LockStatus.Success)
            {
                if (status == LockStatus.CannotLockDisk)
                {
                    return(DiskGroupLockResult.CannotLockDisk);
                }
                else
                {
                    return(DiskGroupLockResult.CannotLockVolume);
                }
            }

            if (Environment.OSVersion.Version.Major >= 6)
            {
                if (!DiskOfflineHelper.IsDiskGroupOnlineAndWritable(diskGroup))
                {
                    LockManager.UnlockAllDisksAndVolumes();
                    return(DiskGroupLockResult.OneOrMoreDisksAreOfflineOrReadonly);
                }

                bool success = DiskOfflineHelper.OfflineAllOrNone(diskGroup);
                if (!success)
                {
                    LockManager.UnlockAllDisksAndVolumes();
                    return(DiskGroupLockResult.CannotTakeDiskOffline);
                }
            }

            return(DiskGroupLockResult.Success);
        }
        private void SetUp(int numSymbols, int numThreads, int numEvents, double timeWindowSize)
        {
            var epService = EPServiceProviderManager.GetDefaultProvider(SupportConfigFactory.GetConfiguration());

            epService.Initialize();

            // Create a statement for N number of Symbols, each it's own listener
            var symbols = new string[numSymbols];

            _listeners = new ResultUpdateListener[symbols.Length];
            for (var i = 0; i < symbols.Length; i++)
            {
                symbols[i] = "S" + i;
                var viewExpr = "select Symbol, sum(Volume) as sumVol " +
                               "from " + typeof(SupportMarketDataBean).FullName +
                               "(Symbol='" + symbols[i] + "').win:time(" + timeWindowSize + ")";
                var testStmt = epService.EPAdministrator.CreateEPL(viewExpr);
                _listeners[i]    = new ResultUpdateListener();
                testStmt.Events += _listeners[i].Update;
            }

            // Create threads to send events
            _threads = new Thread[numThreads];
            var runnables = new TimeWinRunnable[_threads.Length];
            var rlock     = LockManager.CreateDefaultLock();

            for (var i = 0; i < _threads.Length; i++)
            {
                runnables[i] = new TimeWinRunnable(i, epService.EPRuntime, rlock, symbols, numEvents);
                _threads[i]  = new Thread(runnables[i].Run);
            }
        }
Example #29
0
 /// <summary>
 /// Resets the cached dependencies.
 /// </summary>
 public static void Reset()
 {
     _provider = new Lazy <CrmConfigurationProvider>(CreateProvider);
     OrganizationService.Reset();
     ObjectCacheManager.Reset();
     LockManager.Reset();
 }
Example #30
0
 /// <summary>
 /// Initializes all resources required for the transaction manager.
 /// </summary>
 /// <returns></returns>
 public async Task OpenAsync(CancellationToken cancellationToken)
 {
     this.stateLock.EnterWriteLock();
     try
     {
         AppTrace.TraceSource.WriteNoise("TransactionManager.Open", "{0}", this.owner);
         //
         // Create new lock manager.
         //
         this.lockManager = new LockManager();
         //
         // Open the lock manager.
         //
         await this.lockManager.OpenAsync(this.owner, cancellationToken);
     }
     finally
     {
         this.stateLock.ExitWriteLock();
     }
     this.drainAllRwTransactions = new TaskCompletionSource <bool>();
     //
     // Set the status of this transaction manager to be open for business.
     //
     this.status = true;
 }
 // Use this for initialization
 void Awake()
 {
     manager = GameObject.Find("Minigame").GetComponent<LockManager>();
     sprite = GetComponent<UISprite>();
     myX.SetActive(false);
 }
 void Awake()
 {
     instance = this;
 }