internal Simulator GetSimulator(ulong handle) { if (handle == 0) { return(client.Network.CurrentSim); } // lock (AllSimulators) { foreach (Simulator sim in AllSimulators) { if (sim.Handle == handle && sim.Connected) { return(sim); } } } // lock (client.Network.Simulators) { foreach (Simulator sim in LockInfo.CopyOf(client.Network.Simulators)) { if (sim.Handle == handle && sim.Connected) { return(sim); } } } return(GetRegion(handle).TheSimulator); }
private R UserOper <R>(string operationType, Func <R> action, OutputDelegate output) { OutputDelegate prev = userTraceRedir; //lock (OnBotCreatedHooks) Action needsExit = LockInfo.MonitorTryEnter("UserOper " + operationType, BotUsers, MaxWaitTryEnter); try { userTraceRedir = output; try { return(action()); } catch (ChatSignal ex) { throw; } catch (Exception e) { writeToLog(e); if (!ChatOptions.AllowRuntimeErrors) { return(default(R)); } throw; } } finally { userTraceRedir = prev; needsExit(); } }
LockInfo ILockRepository.Query(string key) { LockInfo result = null; var sql = "SELECT [Key],[Role],[Company],[CompanyName],[Account],[Remark],[Time],[Name] FROM dbo.T_LockInfo WHERE [Key]=@KEY"; using (var dbOperator = new DbOperator(Provider, ConnectionString)) { dbOperator.AddParameter("KEY", key); using (var reader = dbOperator.ExecuteReader(sql)) { if (reader.Read()) { result = new LockInfo(reader.GetString(0)) { LockRole = (LockRole)reader.GetByte(1), Company = reader.GetGuid(2), CompanyName = reader.IsDBNull(3) ? string.Empty : reader.GetString(3), Account = reader.GetString(4), Remark = reader.IsDBNull(5) ? string.Empty : reader.GetString(5), Time = reader.GetDateTime(6), Name = reader.IsDBNull(7) ? string.Empty : reader.GetString(7) }; } } } return(result); }
LockInfo ILockRepository.Lock(LockInfo lockInfo) { LockInfo result = null; var sql = "dbo.P_Lock"; using (var dbOperator = new DbOperator(Provider, ConnectionString)) { dbOperator.AddParameter("@pKey", lockInfo.Key); dbOperator.AddParameter("@pRole", (byte)lockInfo.LockRole); dbOperator.AddParameter("@pCompany", lockInfo.Company); dbOperator.AddParameter("@pCompanyName", Utility.StringUtility.Trim(lockInfo.CompanyName) ?? string.Empty); dbOperator.AddParameter("@pAccount", Utility.StringUtility.Trim(lockInfo.Account) ?? string.Empty); dbOperator.AddParameter("@pRemark", Utility.StringUtility.Trim(lockInfo.Remark) ?? string.Empty); dbOperator.AddParameter("@pTime", lockInfo.Time); dbOperator.AddParameter("@pName", Utility.StringUtility.Trim(lockInfo.Name) ?? string.Empty); using (var reader = dbOperator.ExecuteReader(sql, System.Data.CommandType.StoredProcedure)) { if (reader.Read()) { result = new LockInfo(reader.GetString(0)) { LockRole = (LockRole)reader.GetByte(1), Company = reader.GetGuid(2), CompanyName = reader.IsDBNull(3) ? string.Empty : reader.GetString(3), Account = reader.GetString(4), Remark = reader.IsDBNull(5) ? string.Empty : reader.GetString(5), Time = reader.GetDateTime(6), Name = reader.IsDBNull(7) ? string.Empty : reader.GetString(7) }; } } } return(result); }
/// <summary> /// Attempt to get a lock for updating a persiston. Fails if another user has it locked already. /// Succeeds efficiently if this user already had it locked. /// </summary> /// <returns>success flag and error reason code</returns> public (bool, string) RequestLock(DatonKey datonKey, string version, string sessionKey) { //check if already locked by this server if (Locks.TryGetValue(datonKey, out LockInfo linfo)) { bool isLockedByMe = linfo.SessionKey == sessionKey; if (!isLockedByMe) { return(false, Constants.ERRCODE_LOCK); //someone else on this server has it locked } return(true, null); //this session already has it locked } //attempt lock on database using (var lockdb = GetLockConnection()) { if (RetroLock.Lock(lockdb, datonKey, version, sessionKey)) { //success Locks[datonKey] = new LockInfo { SessionKey = sessionKey, DatonKey = datonKey, OldVersion = version }; return(true, null); } //failed, so determine why (string verifiedVersion, _) = RetroLock.GetVersion(lockdb, datonKey); if (verifiedVersion != version) { return(false, Constants.ERRCODE_VERSION); //the most recent version is newer than the version known by the caller } return(false, Constants.ERRCODE_LOCK); //someone else on another server has it locked } }
private void QueryApplyForm(Pagination pagination) { try { List <ApplyformListView> forms = ApplyformQueryService.ProviderQueryBalanceRefundForReturnMoney(getCondition(), pagination).ToList(); var lockInfos = LockService.Query(forms.Select(form => form.ApplyformId.ToString())).ToList(); dataList.DataSource = forms.Select(form => { LockInfo lockInfo = lockInfos.FirstOrDefault(l => l.Key == form.ApplyformId.ToString()); return(new { form.ApplyformId, PNR = form.OriginalPNR.ToListString(), AirportPair = form.Flights.Join("<br />", f => string.Format( "{0}-{1}", f.DepartureCity, f.ArrivalCity)), FlightInfo = form.Flights.Join("<br />", f => string.Format( "{0}{1}<br />{2} / {3}", f.Carrier, f.FlightNo, string.IsNullOrEmpty(f.Bunk) ? "-" : f.Bunk, f.Discount.HasValue ? (f.Discount.Value * 100).TrimInvaidZero() : string.Empty)), TakeoffTime = form.Flights.Join("<br />", f => f.TakeoffTime.ToString("yyyy-MM-dd<br />HH:mm")), Passengers = string.Join("<br />", form.Passengers), ApplyType = form.ApplyformType.GetDescription(), ProcessStatus = GetProcessStatus(form), AppliedTime = form.AppliedTime.ToString("yyyy-MM-dd<br />HH:mm"), form.ApplierAccount, ProductType = form.ProductType.GetDescription(), form.ApplyformType, LockInfo = lockInfo == null ? string.Empty : lockInfo.Company == CurrentCompany.CompanyId ? string.Format("{0}<br />{1}", lockInfo.Account, lockInfo.Name) : string.Format("{0}<br />({1})", lockInfo.LockRole.GetDescription(), lockInfo.Account) }); }); dataList.DataBind(); if (forms.Any()) { pager.Visible = true; if (pagination.GetRowCount) { pager.RowCount = pagination.RowCount; } } else { pager.Visible = false; } } catch (Exception ex) { ShowExceptionMessage(ex, "查询"); } }
public async Task <RefreshLockResult> RefreshLockAsync(string token, TimeSpan?timeout) { IEnumerable <LockInfo> activeLocks = await GetActiveLocksAsync(); LockInfo l = activeLocks.FirstOrDefault(al => al.Token == token); if (l == null) { throw new DavException("The lock doesn't exist", DavStatus.PRECONDITION_FAILED); } if (!timeout.HasValue || timeout == TimeSpan.MaxValue) { // If timeout is absent or infinity timeout requested, // grant 5 minute lock. l.TimeOut = TimeSpan.FromMinutes(5); } else { // Otherwise use new timeout. l.TimeOut = timeout.Value; } DateTime expires = DateTime.UtcNow + (TimeSpan)l.TimeOut; await Context.ExecuteNonQueryAsync( "UPDATE Lock SET Expires = @Expires WHERE Token = @Token", "@Expires", expires, "@Token", token); await Context.socketService.NotifyLockedAsync(Path); return(new RefreshLockResult(l.Level, l.IsDeep, (TimeSpan)l.TimeOut, l.Owner)); }
public WebDAVResponse RefreshLock(ref LockInfo lockInfo) { lockInfo.Shared = true; lockInfo.Deep = false; lockInfo.Owner = "Name"; return(new OkResponse()); }
public static void lockTaskForceUpdatePages(int ttid, string currentlock, int userid) { LockInfo li = Defect.Locktask(ttid.ToString(), currentlock, userid.ToString(), true); var context = GlobalHost.ConnectionManager.GetHubContext <NotifyHub>(); context.Clients.All.OnLockTask(ttid); }
public async Task TestWaitForLockTimeoutAsync() { using (var manager = LockManagerFactory.Create(() => TestDbContext.Create())) { var resource = new Guid("3767EF33-8296-4363-95CE-120E0453E3D0"); LockInfo lockInfo = await manager.TryLockAsync(resource, TimeSpan.FromMinutes(5)); Assert.True(lockInfo.AsImmutable().HasLock()); LockInfo lockInfo2 = await manager.WaitForLockAsync(resource, TimeSpan.FromMinutes(1), TimeSpan.FromMilliseconds(50)); Assert.False(lockInfo2.AsImmutable().HasLock()); //Already cancelled token LockInfo lockInfo3 = await manager.WaitForLockAsync(resource, TimeSpan.FromMinutes(1), TimeSpan.Zero); Assert.False(lockInfo3.AsImmutable().HasLock()); await manager.ReleaseAsync(lockInfo); await manager.ReleaseAsync(lockInfo2); await manager.ReleaseAsync(lockInfo3); } }
public LockInfo(Thread thread, LockInfo next) { this.next = next; this.thread = thread; this.numReadLocks = 0; this.numWriteLocks = 0; }
/// <summary> /// Returns list of <see cref="LockInfo"/> from database by executing specified command /// with specified parameters. /// </summary> /// <param name="command">Command text.</param> /// <param name="prms">Pairs of parameter name, parameter value.</param> /// <returns>List of <see cref="LockInfo"/>.</returns> public List <LockInfo> ExecuteLockInfo(string command, params object[] prms) { List <LockInfo> l = new List <LockInfo>(); using (SqlDataReader reader = prepareCommand(command, prms).ExecuteReader()) { while (reader.Read()) { LockInfo li = new LockInfo(); li.Token = reader.GetString(reader.GetOrdinal("Token")); li.Level = reader.GetBoolean(reader.GetOrdinal("Shared")) ? LockLevel.Shared : LockLevel.Exclusive; li.IsDeep = reader.GetBoolean(reader.GetOrdinal("Deep")); DateTime expires = reader.GetDateTime(reader.GetOrdinal("Expires")); if (expires <= DateTime.UtcNow) { li.TimeOut = TimeSpan.Zero; } else { li.TimeOut = expires - DateTime.UtcNow; } li.Owner = reader.GetString(reader.GetOrdinal("Owner")); l.Add(li); } } return(l); }
// Restore all locks for the curent thread to a previous "Release" value. public void RestoreLock(ref LockCookie lockCookie) { lock (this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if (info == null) { return; } // Bail out if the cookie is not "Saved" or if // we have prevailing locks at the moment. if (lockCookie.type != LockCookie.CookieType.Saved || lockCookie.thread != Thread.CurrentThread || info.numReadLocks > 0 || info.numWriteLocks > 0) { return; } // Restore the thread to its previous lock state. RestoreLockState(info, lockCookie.readCount, lockCookie.writeCount); } }
// Release the write lock. public void ReleaseWriterLock() { lock (this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if (info == null) { return; } // Bail out with an exception if we have read locks. if (info.numReadLocks > 0) { throw new ApplicationException(_("Invalid_RWLock")); } // Update the thread and global lock count values. if (info.numWriteLocks == 0) { return; } --(info.numWriteLocks); --numWriteLocks; // Determine if we need to wake up a waiting thread. if (numWriteLocks == 0) { Monitor.Pulse(this); } } }
public DataBaseDescriptor(Authentication authentication, IDataBase dataBase, DescriptorTypes descriptorTypes, object owner) : base(authentication, dataBase, descriptorTypes) { this.dataBase = dataBase; this.owner = owner ?? this; this.dataBase.Dispatcher.VerifyAccess(); this.dataBaseInfo = dataBase.DataBaseInfo; this.dataBaseState = dataBase.DataBaseState; this.authenticationInfos = dataBase.AuthenticationInfos; this.lockInfo = dataBase.LockInfo; this.accessInfo = dataBase.AccessInfo; this.accessType = dataBase.GetAccessType(authentication); if (this.descriptorTypes.HasFlag(DescriptorTypes.IsSubscriptable) == true) { this.dataBase.Renamed += DataBase_Renamed; this.dataBase.Deleted += DataBase_Deleted; this.dataBase.Loaded += DataBase_Loaded; this.dataBase.Unloaded += DataBase_Unloaded; this.dataBase.AuthenticationEntered += DataBase_AuthenticationEntered; this.dataBase.AuthenticationLeft += DataBase_AuthenticationLeft; this.dataBase.DataBaseInfoChanged += DataBase_DataBaseInfoChanged; this.dataBase.DataBaseStateChanged += DataBase_DataBaseStateChanged; this.dataBase.AccessChanged += DataBase_AccessChanged; this.dataBase.LockChanged += DataBase_LockChanged; } }
private bool Follow(string name) { foreach (Simulator sim in LockInfo.CopyOf(Client.Network.Simulators)) { Avatar target = sim.ObjectsAvatars.Find( delegate(Avatar avatar) { return(avatar.Name == name); } ); if (target != null) { targetLocalID = target.LocalID; Active = true; EnsureRunning(); return(true); } } if (Active) { Client.Self.AutoPilotCancel(); Active = false; } return(false); }
/// <summary> /// Locks the file in the remote storage or gets existing lock. /// </summary> /// <param name="lockFileOpenMode"> /// Indicates if a new lock should be created or existing lock file to be opened. /// Allowed options are <see cref="FileMode.OpenOrCreate"/>, <see cref="FileMode.Open"/> and <see cref="FileMode.CreateNew"/>. /// </param> /// <param name="lockMode"> /// Indicates automatic or manual lock. Saved only for new files, ignored when existing lock is opened. /// </param> /// <exception cref="ClientLockFailedException"> /// Thrown when a file can not be locked. For example when a lock-token file is blocked /// from another thread, during update, lock and unlock operations. /// </exception> /// <returns>File lock.</returns> private async Task <Lock> LockAsync(FileMode lockFileOpenMode, LockMode lockMode = LockMode.Manual) { // Get existing lock or create a new lock. Lock fileLock = await Lock.LockAsync(userFileSystemPath, lockFileOpenMode, lockMode, logger); if (fileLock.IsNew()) { logger.LogMessage("Locking", userFileSystemPath); // Set pending icon. await new UserFileSystemRawItem(userFileSystemPath).SetLockPendingIconAsync(true); // Lock file in remote storage. LockInfo lockInfo = await new UserFileSystemItem(userFileSystemPath).LockAsync(); // Save lock-token in lock-file. await fileLock.SetLockInfoAsync(lockInfo); // Set locked icon. await new UserFileSystemRawItem(userFileSystemPath).SetLockIconAsync(true); logger.LogMessage($"Locked succesefully. Mode: {lockMode}", userFileSystemPath); } return(fileLock); }
public override CmdResult ExecuteRequest(CmdRequest args) { StringBuilder output = new StringBuilder(); { foreach (Simulator sim in LockInfo.CopyOf(Client.Network.Simulators)) { output.AppendLine(String.Format( "[{0}] Dilation: {1} InBPS: {2} OutBPS: {3} ResentOut: {4} ResentIn: {5}", sim.ToString(), sim.Stats.Dilation, sim.Stats.IncomingBPS, sim.Stats.OutgoingBPS, sim.Stats.ResentPackets, sim.Stats.ReceivedResends)); output.Append("Packets in the queue: " + Client.Network.InboxCount); Simulator csim = sim; output.AppendLine( String.Format( "FPS : {0} PhysicsFPS : {1} AgentUpdates : {2} Objects : {3} Scripted Objects : {4}", csim.Stats.FPS, csim.Stats.PhysicsFPS, csim.Stats.AgentUpdates, csim.Stats.Objects, csim.Stats.ScriptedObjects)); output.AppendLine( String.Format( "Frame Time : {0} Net Time : {1} Image Time : {2} Physics Time : {3} Script Time : {4} Other Time : {5}", csim.Stats.FrameTime, csim.Stats.NetTime, csim.Stats.ImageTime, csim.Stats.PhysicsTime, csim.Stats.ScriptTime, csim.Stats.OtherTime)); output.AppendLine(String.Format("Agents : {0} Child Agents : {1} Active Scripts : {2}", csim.Stats.Agents, csim.Stats.ChildAgents, csim.Stats.ActiveScripts)); } } return(Success(output.ToString())); }
/// <summary> /// Lock some lead/customer on edit/convert /// </summary> /// <param name="id">Id of lead/customer</param> /// <param name="groupName">lead or customer</param> public void Lock(int id, string groupName) { if (Context.User.Identity.IsAuthenticated && GetGroupName(groupName, out string validateGroupName)) { var userCreads = Context.User.GetCurrentUserCreads(); User user = _unitOfWork.UsersRepository.FindById(userCreads.Id); var lockInfo = new LockInfo() { Id = id, LockName = $"{user.FirstName} {user.LastName}" }; Clients.Group(validateGroupName, Context.ConnectionId).LockEdit(lockInfo); Clients.Others.onResetPopUp(); dataToLock.AddOrUpdate(validateGroupName, new List <LockInfo> { lockInfo }, (key, value) => { value.Add(lockInfo); return(value); }); } }
public TypeDescriptor(Authentication authentication, IType type, DescriptorTypes descriptorTypes, object owner) : base(authentication, type, descriptorTypes) { this.type = type; this.owner = owner ?? this; this.type.Dispatcher.VerifyAccess(); this.typeInfo = type.TypeInfo; this.typeState = type.TypeState; if (this.type.TypeInfo.IsFlag == true) { this.typeAttribute |= TypeAttribute.IsFlag; } this.lockInfo = type.LockInfo; this.accessInfo = type.AccessInfo; this.accessType = type.GetAccessType(this.authentication); this.templateDescriptor = new TypeTemplateDescriptor(authentication, type.Template, descriptorTypes); if (this.descriptorTypes.HasFlag(DescriptorTypes.IsSubscriptable) == true) { this.type.Deleted += Type_Deleted; this.type.LockChanged += Type_LockChanged; this.type.AccessChanged += Type_AccessChanged; this.type.TypeInfoChanged += Type_TypeInfoChanged; this.type.TypeStateChanged += Type_TypeStateChanged; } }
// Release the read lock. public void ReleaseReaderLock() { lock (this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if (info == null) { return; } // Save the global write lock count. int saveRead = numReadLocks; int saveWrite = numWriteLocks; // Update the thread and global lock count values. if (info.numReadLocks > 0) { --(info.numReadLocks); --numReadLocks; } // Determine if we need to wake up a waiting thread. if (saveRead > numReadLocks && numReadLocks == 0) { Monitor.Pulse(this); } else if (saveWrite > numWriteLocks && numWriteLocks == 0) { Monitor.Pulse(this); } } }
LockInfo ConvertXmlToLockInfo(string xml) { var result = new LockInfo(); var m = Regex.Match(xml, "lockscope[^>]?>[^:]+:([^ />]+)/"); if (m.Groups.Count > 1) { result.LockScope = m.Groups[1].Value; } m = Regex.Match(xml, "locktype[^>]?>[^:]+:([^ />]+)"); if (m.Groups.Count > 1) { result.LockType = m.Groups[1].Value; } m = Regex.Match(xml, "owner[^>]?>[^:]+:([^ />]+)>([^<]+)<"); if (m.Groups.Count > 2) { result.Owner = m.Groups[2].Value; } return(result); }
private void DiscoverMoreSysvars() { foreach (var ms in LockInfo.CopyOf(Plugins).Values) { ConfigSettingAttribute.AddSingletonClass(ms.GetType()); } }
static public bool DevolveURIWithNamespace(INamespaceMapper mapper, string s, out string uri, out string prefix, out string atom) { atom = null; uri = null; prefix = null; foreach (var pfx in LockInfo.WithLock <IEnumerable <string> >(mapper, mapper.Prefixes.ToArray)) { prefix = pfx; var uril = LockInfo.WithLock(mapper, () => mapper.GetNamespaceUri(pfx)); uri = uril.ToString(); int len = uri.Length; if (len > 0 && s.StartsWith(uri)) { if (String.IsNullOrEmpty(prefix)) { prefix = LockInfo.WithLock(mapper, () => mapper.GetPrefix(uril)); } atom = s.Substring(len); return(true); } string prefixc = prefix + ":"; if (s.StartsWith(prefixc)) { atom = s.Substring(prefixc.Length); return(true); } } atom = null; uri = null; prefix = null; return(false); }
public LockModel CreateLock(string lockName, IList <int> allowedUsers) { using (var smartLock = new SmartLockEntities()) { int changes = 0; var lockInfo = new LockInfo { Name = lockName, State = "Locked" }; smartLock.LockInfoes.Add(lockInfo); changes += smartLock.SaveChanges(); if (allowedUsers.Count > 0) { smartLock.LockAccesses.AddRange(this.PopulateLockAccessList(lockInfo.LockId, allowedUsers)); changes += smartLock.SaveChanges(); } if (changes == allowedUsers.Count + 1) { return(new LockModel { LockId = lockInfo.LockId, Name = lockName, State = lockInfo.State, AllowedUsers = allowedUsers }); } return(null); } }
public bool ModifyLockState(int lockId, int userId, LockState state) { using (var smartLock = new SmartLockEntities()) { LockInfo lockInfo = smartLock.LockInfoes.FirstOrDefault(l => l.LockId == lockId); if (lockInfo == null) { // lock not found. throw new LockNotFoundException("Lock not found."); } LockAccess lockAccess = smartLock.LockAccesses.FirstOrDefault(l => l.UserId == userId && l.LockId == lockId); // TODO: Expand check to limit access based on time if (lockAccess == null) { // user does not have access to the lock. Throw exception. throw new UnauthorizedUserException("User unauthorized."); } // modify lock state. lockInfo.State = String.Concat(state.ToString(), "ed"); int changes = smartLock.SaveChanges(); return(changes == 1 ? true : false); } }
void ScanForLinksets(SimObject O) { if (O.Children == null) { return; } if (O.Children.Count == 0) { lock (fileWriterLock) File.WriteAllText(dumpDir + O.ID + ".link", ""); } var lst = new SortedList <uint, UUID>(); foreach (var o in LockInfo.CopyOf(O.Children)) { lst.Add(o.LocalID, o.ID); } string contents = "" + O.ID; foreach (KeyValuePair <uint, UUID> uuid in lst) { contents += "," + uuid.Value; } lock (fileWriterLock) File.WriteAllText(dumpDir + O.ID + ".link", contents); }
public async Task UT_WebDavClient_LockRootFolder() { var lockRequestContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:lockinfo xmlns:D=\"DAV:\"><D:lockscope><D:exclusive /></D:lockscope><D:locktype><D:write /></D:locktype><D:owner><D:href>[email protected]</D:href></D:owner></D:lockinfo>"; var lockResponseContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock><D:locktype><D:write/></D:locktype><D:lockscope><D:exclusive/></D:lockscope><D:depth>infinity</D:depth><D:owner><D:href>[email protected]</D:href></D:owner><D:timeout>Second-60</D:timeout><D:locktoken><D:href>opaquelocktoken:a2324814-cbe3-4fb4-9c55-cba99a62ef5d.008f01d2b2dafba0</D:href></D:locktoken><D:lockroot><D:href>http://127.0.0.1/webdav/</D:href></D:lockroot></D:activelock></D:lockdiscovery></D:prop>"; var oneMinuteTimeout = WebDavTimeoutHeaderValue.CreateWebDavTimeout(TimeSpan.FromMinutes(1)); var depth = WebDavDepthHeaderValue.Infinity; var lockInfo = new LockInfo() { LockScope = LockScope.CreateExclusiveLockScope(), LockType = LockType.CreateWriteLockType(), OwnerHref = "*****@*****.**" }; var mockHandler = new MockHttpMessageHandler(); var requestHeaders = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>(WebDavConstants.Depth, depth.ToString()), new KeyValuePair <string, string>(WebDavRequestHeader.Timeout, oneMinuteTimeout.ToString()) }; mockHandler.When(WebDavMethod.Lock, WebDavRootFolder).WithHeaders(requestHeaders).WithContent(lockRequestContent).Respond(HttpStatusCode.OK, new StringContent(lockResponseContent)); using (var client = CreateWebDavClient(mockHandler)) { var response = await client.LockAsync(WebDavRootFolder, oneMinuteTimeout, depth, lockInfo); Assert.IsTrue(response.IsSuccessStatusCode); } }
public void AcquireGlobalLock() { lock (_sync_mutex) { //wait untill global lock is released. if (_globalLockingContext != null && _globalLockingContext.IsCurrentContext) { _globalLockingContext.IncrementRefCount(); return; } while (_globalLock || _waiting4globalLock) { Monitor.Wait(_sync_mutex); } if (_lockTable.Count == 0) { //global lock is acquired. _globalLock = true; } else { _waiting4globalLock = true; _globalLockInfo = new LockInfo(); } } if (_globalLockInfo != null && !_globalLock) { _globalLockInfo.AddWaitingThread(); } _globalLockingContext = new LockingContext(); _globalLockingContext.IncrementRefCount(); }
public void AcquireLock(object key) { LockInfo info = null; lock (_sync_mutex) { while (_globalLock || _waiting4globalLock) { if (_globalLock && _globalLockingContext != null && _globalLockingContext.IsCurrentContext) { break; } Monitor.Wait(_sync_mutex); } if (!_lockTable.Contains(key)) { _lockTable.Add(key, new LockInfo()); } else { info = _lockTable[key] as LockInfo; } } if (info != null) { bool lockAcquired = info.AddWaitingThread(); //retry if (!lockAcquired) { AcquireLock(key); } } }
// Constructor. public ReaderWriterLock() { numReadLocks = 0; numWriteLocks = 0; seqNum = 0; lastWriteSeqNum = -1; lockList = null; }
/// <summary> /// Add a lock as a depenedtent of this lock. /// </summary> /// <param name="lockInfo">The lock information.</param> public void AddDependent(LockInfo lockInfo) { #if !CAPTURE_STACK_TRACES if (this.IsDependent(lockInfo)) { return; } #endif DependentLockInfo foundInfo = null; foreach (DependentLockInfo dependLockInfo in this._dependentLocks) { if (dependLockInfo.LockInfo == lockInfo) { foundInfo = dependLockInfo; break; } } if (foundInfo == null) { foundInfo = new DependentLockInfo(lockInfo); this._dependentLocks.Add(foundInfo); } #if CAPTURE_STACK_TRACES StackTrace callStack = new StackTrace(true); foreach (StackTrace currentTraces in foundInfo.CallStacks) { if (IsSameCallStack(callStack, currentTraces)) return; } foundInfo.CallStacks.Add(callStack); #endif }
/// <summary> /// Initializes a new instance of the <see cref="DependentLockInfo"/> class. /// </summary> /// <param name="lockInfo">The lock info.</param> public DependentLockInfo(LockInfo lockInfo) { this.LockInfo = lockInfo; this.CallStacks = new List<StackTrace>(); }
/// <summary> /// Find a lock. /// </summary> /// <param name="obj">The object to inspect.</param> /// <returns>The lock information for the object.</returns> private static LockInfo FindLock(object obj) { for (int i = RgLocks.Count - 1; i >= 0; i--) { if (!RgLocks[i].IsAlive) { LockInfo infoRemove = RgLocks[i]; RgLocks.RemoveAt(i); foreach (LockInfo info in RgLocks) { info.KillDependent(infoRemove); } } else { if (object.ReferenceEquals(RgLocks[i].Lock, obj)) { return RgLocks[i]; } } } LockInfo lockInfo = new LockInfo(obj); RgLocks.Add(lockInfo); return lockInfo; }
/// <summary> /// Initializes a new instance of the <see cref="ExitOnDispose"/> class. /// </summary> /// <param name="obj">The obj.</param> /// <param name="lockInfo">The lock info.</param> /// <param name="isRecLock">If set to <c>true</c> lock.</param> public ExitOnDispose(object obj, LockInfo lockInfo, bool isRecLock) { this._object = obj; this._lockInfo = lockInfo; this._recLock = isRecLock; }
/// <summary> /// Kills a depend object, ihearting its dependents. /// </summary> /// <param name="lockInfo">The lock information.</param> public void KillDependent(LockInfo lockInfo) { int index = -1; for (int i = 0; i < this._dependentLocks.Count; i++) { if (this._dependentLocks[i].LockInfo == lockInfo) { index = i; break; } } if (index == -1) { return; } this._dependentLocks.RemoveAt(index); this._dependentLocks.AddRange(lockInfo._dependentLocks); }
public override bool Generate(CommandExecutionContext context) { var target = context.NativeDbgEngTarget; var unifiedStackTraces = new UnifiedStackTraces(target.DebuggerInterface, context); var blockingObjectsStrategy = new DumpFileBlockingObjectsStrategy(context.Runtime, unifiedStackTraces, target); foreach (var thread in unifiedStackTraces.Threads) { // This function is created lazily because we don't need the managed // code state for each thread. Func<bool> checkManagedCodeStateForThisThread = () => unifiedStackTraces.GetStackTrace(thread.EngineThreadId) .Any(f => f.Type == UnifiedStackFrameType.Managed); var threadWithBlockingInfo = blockingObjectsStrategy.GetThreadWithBlockingObjects(thread); var threadInfo = new ThreadInfo { ManagedThreadId = threadWithBlockingInfo.ManagedThreadId, OSThreadId = threadWithBlockingInfo.OSThreadId, IsRunningManagedCode = checkManagedCodeStateForThisThread }; foreach (var blockingObject in threadWithBlockingInfo.BlockingObjects) { var lockInfo = new LockInfo { Reason = blockingObject.Reason.ToString() }; if (blockingObject.Type == UnifiedBlockingType.ClrBlockingObject) { lockInfo.Object = blockingObject.ManagedObjectAddress; lockInfo.ManagedObjectType = context.Heap.GetObjectType(lockInfo.Object)?.Name; } else { lockInfo.Object = blockingObject.Handle; lockInfo.OSObjectName = blockingObject.KernelObjectName; } lockInfo.OwnerThreadOSIds.AddRange(blockingObject.OwnerOSThreadIds); threadInfo.Locks.Add(lockInfo); } Threads.Add(threadInfo); RecommendFinalizerThreadBlocked(context); RecommendDeadlockedThreads(); } return Threads.Any(); }
// Get the lock information for the current thread, creating // a new information object if one doesn't exist yet. private LockInfo GetOrCreateLockInfo() { Thread thread = Thread.CurrentThread; LockInfo info = lockList; while(info != null) { if(info.thread == thread) { return info; } info = info.next; } info = new LockInfo(thread, lockList); lockList = info; return info; }
/// <summary> /// Releases the write lock on the list for the current thread. /// </summary> /// <param name="info">The lock info.</param> protected void ReleaseWriterLock(LockInfo info) { // If the writer lock was upgrader from a reader lock. if (info.Cookie.HasValue) { // Downgrade the writer lock to a reader lock. LockCookie cookie = info.Cookie.Value; this.sync.DowngradeFromWriterLock(ref cookie); } // Else, if a new lock was acquired. else if (info.Locked) { // Release the writer lock. this.sync.ReleaseWriterLock(); } }
// Restore the lock state for the current thread. private void RestoreLockState(LockInfo info, int readCount, int writeCount) { // Save the current global lock state. int saveRead = numReadLocks; int saveWrite = numWriteLocks; // Remove the locks that are currently held by the thread. numReadLocks -= info.numReadLocks; numWriteLocks -= info.numWriteLocks; info.numReadLocks = 0; info.numWriteLocks = 0; // Wake up any waiting threads. if(saveRead > numReadLocks && numReadLocks == 0) { Monitor.Pulse(this); } else if(saveWrite > numWriteLocks && numWriteLocks == 0) { Monitor.Pulse(this); } // Re-acquire the locks based upon the type required. if(readCount > 0 && writeCount == 0) { // Re-acquire read locks only. while(numWriteLocks > 0) { Monitor.Wait(this); } info.numReadLocks += readCount; numReadLocks += readCount; } else if(readCount == 0 && writeCount > 0) { // Re-acquire write locks only. while(numReadLocks > 0 && numWriteLocks > 0) { Monitor.Wait(this); } info.numWriteLocks += writeCount; numWriteLocks += writeCount; } else if(readCount > 0 && writeCount > 0) { // Re-acquire both read and write locks. while(numWriteLocks > 0) { Monitor.Wait(this); } info.numReadLocks += readCount; numReadLocks += readCount; info.numWriteLocks += writeCount; numWriteLocks += writeCount; } }
private LockInfo GetLockInfo(Guid lockable, Guid owner) { var info = new LockInfo(lockable, owner); var db = ApplicationManager.INSTANCE.GetDbProvider(); var connection = db.CreateConnection(); connection.Open(); try { using(var command = connection.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = string.Format(CHECK_SQL, lockable.ToString(), owner.ToString()); var reader = command.ExecuteReader(); if(reader.Read()) { LockType result = LockType.None; if (Enum.TryParse(((byte)reader["LockType"]).ToString(), out result)) info.LockType = result; } } } finally { connection.Close(); } return info; }
/// <summary> /// Is a lock a depenedent of this lock. /// </summary> /// <param name="lockInfo">The lock information.</param> /// <returns>True if the lock is dependent; false otherwise.</returns> public bool IsDependent(LockInfo lockInfo) { if (this == lockInfo) { return true; } foreach (DependentLockInfo child in this._dependentLocks) { if (child.LockInfo.IsDependent(lockInfo)) { return true; } } return false; }
public static void Lock(string type, int id) { string elementToLock = type + id; string TabID = ""; string username = ""; HttpContext context = HttpContext.Current; HttpSessionState session = (context == null) ? null : context.Session; if (context != null) { username = (string)context.User.Identity.Name; } else { TabID = "notab"; username = "******"; } LockInfo currentLock; if (LockedItems.TryGetValue(elementToLock, out currentLock)) //está bloqueado { throw new LockControlHelperException(currentLock); } else //no bloqueado! { string sessionID = (session != null) ? session.SessionID : "nosession"; LockedItems[type + id] = new LockInfo(username, DateTime.Now, sessionID, TabID, elementToLock, type, id.ToString()); if (!LocksBySession.ContainsKey(sessionID)) LocksBySession[sessionID] = new Dictionary<string, List<string>>(); if (!LocksBySession[sessionID].ContainsKey(TabID)) LocksBySession[sessionID][TabID] = new List<string>(); LocksBySession[sessionID][TabID].Add(elementToLock); } }
public async Task<object> LockInterpreterAsync(IPythonInterpreterFactory factory, object moniker, TimeSpan timeout) { LockInfo info; Dictionary<object, LockInfo> locks; lock (_locksLock) { if (_locks == null) { _locks = new Dictionary<IPythonInterpreterFactory, Dictionary<object, LockInfo>>(); } if (!_locks.TryGetValue(factory, out locks)) { _locks[factory] = locks = new Dictionary<object, LockInfo>(); } if (!locks.TryGetValue(moniker, out info)) { locks[moniker] = info = new LockInfo(); } } Interlocked.Increment(ref info._lockCount); bool result = false; try { result = await info._lock.WaitAsync(timeout.TotalDays > 1 ? Timeout.InfiniteTimeSpan : timeout); return result ? (object)info : null; } finally { if (!result) { Interlocked.Decrement(ref info._lockCount); } } }
private bool TryGetLock(string fileId, out LockInfo lockInfo) { // TODO: This lock implementation is not thread safe and not persisted and all in all just an example. if (Locks.TryGetValue(fileId, out lockInfo)) { if (lockInfo.Expired) { Locks.Remove(fileId); return false; } return true; } return false; }
/// <summary> /// Releases the read lock on the list for the current thread. /// </summary> /// <param name="info">The lock info.</param> protected void ReleaseReaderLock(LockInfo info) { // If the a new lock was acquired. if (info.Locked) { // Release the lock. this.sync.ReleaseReaderLock(); } }