/// <summary> /// Attempts to obtain exclusive access to the lock. /// </summary> /// <param name="timeout">The amount of time to wait before failing to take the lock.</param> /// <returns> /// A task that, if cancelled, indicates the lock was not taken, /// and must be awaited to obtain the token that will release the /// lock on <see cref="IDisposable.Dispose"/>. /// </returns> /// <exception cref="TaskCanceledException">The <paramref name="timeout"/> expires before the lock could be taken.</exception> /// <remarks> /// <para> /// The following illustrates an example of using try-catch to detect a failure to take the lock. /// </para> /// /// <code> /// AsyncLock asyncLock = new AsyncLock(); /// /// try /// { /// using IDisposable token = await asyncLock.TryEnterAsync(); /// // Critical region /// } /// catch (TaskCanceledException) /// { /// // Lock failed /// } /// </code> /// /// <para> /// The following illustrates an example of using <see cref="Task.ContinueWith{TResult}(Func{Task, TResult})"/> /// to detect a failure to take the lock. /// </para> /// /// <code> /// AsyncLock asyncLock = new AsyncLock(); /// /// await asyncLock.TryEnterAsync().ContinueWith(async tokenTask => /// { /// if (tokenTask.IsCanceled) /// { /// // Lock failed /// return; /// } /// /// using IDisposable token = await tokenTask; /// // Critical region /// }).Unwrap(); /// </code> /// </remarks> public async Task <IDisposable> TryEnterAsync(TimeSpan timeout) { LockEntry lockEntry = new LockEntry(); try { Task timeoutTask = Task.Delay(timeout); Task lockReleasedTask = Interlocked.Exchange(ref m_task, lockEntry.WhenReleased()); await Task.WhenAny(timeoutTask, lockReleasedTask).ConfigureAwait(false); if (!lockReleasedTask.IsCompleted) { throw new TaskCanceledException("Timed out while attempting to get exclusive access to async lock."); } return(lockEntry); } catch { // Make sure to dispose the lock entry since // it's not being returned to the caller lockEntry.Dispose(); throw; } }
public override void Apply() { if (skill != null) { // check if the skill works var reqSkill = method.RequiredSkillValue; var diff = skill.ActualValue - (reqSkill == 1 ? 0 : reqSkill); if (!CheckSuccess(diff)) { // failed m_cast.Cancel(SpellFailedReason.TryAgain); return; } // skill gain var skillVal = skill.ActualValue; skillVal += (ushort)Gain(diff); skillVal = Math.Min(skillVal, skill.MaxValue); skill.CurrentValue = (ushort)skillVal; } // open lock var chr = m_cast.CasterChar; chr.AddMessage(() => { if (lockable is ObjectBase && !((ObjectBase)lockable).IsInWorld) { return; } LockEntry.Handle(chr, lockable, method != null ? method.InteractionType : LockInteractionType.None); }); }
public async Task <IDisposable> Acquire(string key, CancellationToken cancellationToken) { LockEntry entry; lock (locks) { if (!locks.TryGetValue(key, out entry)) { locks[key] = entry = new LockEntry(); } entry.Count++; } IDisposable releaser = await entry.Lock.Acquire(cancellationToken); return(new DisposeAction(() => { lock (locks) { entry.Count--; releaser.Dispose(); if (entry.Count == 0) { this.locks.Remove(key); entry.Dispose(); } } })); }
public async Task<IDisposable> Acquire(string key, CancellationToken cancellationToken) { LockEntry entry; lock(locks) { if (!locks.TryGetValue(key, out entry)) { locks[key] = entry = new LockEntry(); } entry.Count++; } IDisposable releaser = await entry.Lock.Acquire(cancellationToken); return new DisposeAction(() => { lock(locks) { entry.Count--; releaser.Dispose(); if (entry.Count == 0) { this.locks.Remove(key); entry.Dispose(); } } }); }
/// <summary> /// Attempts to enter the lock with exclusive access where no other /// readers or writers can execute concurrently with the writer. /// </summary> /// <param name="timeout">The amount of time to wait before timing out.</param> /// <returns>The token used to control the duration of entry.</returns> /// <exception cref="TimeoutException">The lock could not be entered before the <paramref name="timeout"/> expired.</exception> public async Task <IDisposable> TryEnterWriteLockAsync(TimeSpan timeout) { LockEntry lockEntry = new LockEntry(); try { // The writer must maintain exclusive access until the write operation is complete IDisposable readerListToken = await ReaderListLock.TryEnterAsync(timeout).ConfigureAwait(false); _ = lockEntry.WhenReleased().ContinueWith(_ => readerListToken.Dispose()); Task timeoutTask = Task.Delay(timeout); Task readerTask = Task.WhenAll(ReaderList); await Task.WhenAny(timeoutTask, readerTask).ConfigureAwait(false); if (!readerTask.IsCompleted) { throw new TaskCanceledException("Timed out waiting for readers to complete."); } // Completed readers will eventually remove themselves, // but may as well remove them all here ReaderList.Clear(); return(lockEntry); } catch { // Make sure to dispose the lock entry since // it's not being returned to the caller lockEntry.Dispose(); throw; } }
/// <summary> /// Checks the lock state and locks if required /// </summary> /// <param name="category">Category of the lock</param> /// <param name="id">Id of the resource</param> /// <param name="userIdentifier">User identifier to use for locking. If none is specified, no lock is acquired</param> /// <param name="lockIfFree">true if the resource should be locked if its free</param> /// <param name="appendProjectIdToKey">True if the project id must be appended to the key</param> /// <returns>Lock Response</returns> private async Task <IActionResult> CheckExternalLockInternal(string category, string id, string userIdentifier, bool lockIfFree, bool appendProjectIdToKey) { id = await AppendProjectIdIfRequired(id, appendProjectIdToKey); LockResponse response = new LockResponse(); response.LockedByOtherUser = false; response.LockValidForMinutes = LockTimespan; LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null) { if ((existingLock.UserId != ExternalUserConstants.ExternalUserId || (existingLock.UserId == ExternalUserConstants.ExternalUserId && existingLock.ExternalUserId != userIdentifier)) && existingLock.ExpireDate > DateTimeOffset.UtcNow) { response.LockedByUserName = _localizer["ExternalUser"]; response.LockedByOtherUser = true; return(Ok(response)); } } if (lockIfFree) { await _lockServiceDbAccess.LockResource(category, id, ExternalUserConstants.ExternalUserId, userIdentifier, DateTimeOffset.UtcNow.AddMinutes(LockTimespan)); } return(Ok(response)); }
public override void Apply() { if (skill != null) { uint requiredSkillValue = method.RequiredSkillValue; uint diff = skill.ActualValue - (requiredSkillValue == 1U ? 0U : requiredSkillValue); if (!CheckSuccess(diff)) { m_cast.Cancel(SpellFailedReason.TryAgain); return; } skill.CurrentValue = (ushort)Math.Min(skill.ActualValue + (ushort)Gain(diff), skill.MaxValue); } Character chr = m_cast.CasterChar; chr.AddMessage(() => { if (lockable is ObjectBase && !((ObjectBase)lockable).IsInWorld) { return; } LockEntry.Handle(chr, lockable, method != null ? method.InteractionType : LockInteractionType.None); }); }
public static void show(ref ConsoleSystem.Arg arg) { bool result = false; bool.TryParse(arg.Args[0], out result); LockEntry.Show(result); }
/// <summary> /// Checks the lock state and locks if required /// </summary> /// <param name="category">Category of the lock</param> /// <param name="id">Id of the resource</param> /// <param name="lockIfFree">true if the resource should be locked if its free</param> /// <returns>Lock Response</returns> private async Task <IActionResult> CheckLockInternal(string category, string id, bool lockIfFree) { GoNorthUser currentUser = await _userManager.GetUserAsync(User); LockResponse response = new LockResponse(); response.LockedByOtherUser = false; response.LockValidForMinutes = LockTimespan; LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null) { if (existingLock.UserId != currentUser.Id && existingLock.ExpireDate > DateTimeOffset.UtcNow) { GoNorthUser lockedByUser = await _userManager.FindByIdAsync(existingLock.UserId); response.LockedByUserName = lockedByUser.DisplayName; response.LockedByOtherUser = true; return(Ok(response)); } } if (lockIfFree) { await _lockServiceDbAccess.LockResource(category, id, currentUser.Id, DateTimeOffset.UtcNow.AddMinutes(LockTimespan)); } return(Ok(response)); }
public static void show(ref ConsoleSystem.Arg arg) { bool flag = false; bool.TryParse(arg.Args[0], out flag); LockEntry.Show(flag); }
/// <summary> /// Obtains exclusive access to the lock. /// </summary> /// <returns> /// A task that must be awaited to obtain the token that will /// release the lock on <see cref="IDisposable.Dispose"/>. /// </returns> public async Task <IDisposable> EnterAsync() { LockEntry lockEntry = new LockEntry(); await Interlocked.Exchange(ref m_task, lockEntry.WhenReleased()).ConfigureAwait(false); return(lockEntry); }
/// <summary> /// Attempts to enter the lock with concurrent access where all /// readers can execute concurrently with respect to each other. /// </summary> /// <param name="timeout">The amount of time to wait before timing out.</param> /// <returns>The token used to control the duration of entry.</returns> /// <exception cref="TimeoutException">The lock could not be entered before the <paramref name="timeout"/> expired.</exception> public async Task <IDisposable> TryEnterReadLockAsync(TimeSpan timeout) { LockEntry lockEntry = new LockEntry(); try { Task readerTask = lockEntry.WhenReleased(); // The exclusive lock must be obtained to update the reader list, // but it's also necessary so that the reader will wait on any // writers that entered before it using (await ReaderListLock.TryEnterAsync(timeout).ConfigureAwait(false)) ReaderList.Add(readerTask); // Prevent the reader list from growing indefinitely _ = readerTask.ContinueWith(async _ => { using (await ReaderListLock.EnterAsync().ConfigureAwait(false)) ReaderList.Remove(readerTask); }); return(lockEntry); } catch { // Make sure to dispose the lock entry since // it's not being returned to the caller lockEntry.Dispose(); throw; } }
//public DataTable fetchbybookingid(BALBooking obj) //{ // try // { // SqlConnection cn = new SqlConnection(strCon); // SqlDataAdapter da = new SqlDataAdapter(); // da.SelectCommand = new SqlCommand("[sp_CruiseBooking]", cn); // da.SelectCommand.Parameters.Clear(); // da.SelectCommand.Parameters.AddWithValue("@action", obj.action); // da.SelectCommand.Parameters.AddWithValue("@bookingId", obj._iBookingId); // da.SelectCommand.CommandType = CommandType.StoredProcedure; // cn.Open(); // da.SelectCommand.ExecuteReader(); // DataTable dtReturnData = new DataTable(); // cn.Close(); // da.Fill(dtReturnData); // if (dtReturnData != null) // return dtReturnData; // else // return null; // } // catch (Exception ex) // { // return null; // } //} // POST api/<controller> public void Post([FromBody] LockEntry lok) { string roomno = lok.roomno; int accomid = lok.accomid; int roomcatid = lok.roomcategoryid; cab.LockTheBooking(roomno, accomid, roomcatid); }
public static bool TryLoot(this ILockable lockable, Character chr) { if (!lockable.CanOpen(chr)) { return(false); } LockEntry.Loot(lockable, chr); return(true); }
public static bool TryLoot(this ILockable lockable, Character chr) { if (CanOpen(lockable, chr)) { // just open it LockEntry.Loot(lockable, chr); return(true); } return(false); }
public IActionResult Lock([FromBody] LockEntry newmodel) { if (ModelState.IsValid) { if (newmodel != null) { /* * var Entity = _mmmcontext.Entities.FirstOrDefault(x => x.Ent_ID == newmodel.IDFromWorkUnitsDBTable); * * if (Entity == null) * { * return BadRequest("Profile not found with Id " + newmodel.IDFromWorkUnitsDBTable); * } */ // look for an existing lock var existingLock = _context.RecordLocks .FirstOrDefault(x => (x.IDFromWorkUnitsDBTable == newmodel.IDFromWorkUnitsDBTable && x.WorkUnitTypeID == newmodel.WorkUnitTypeID)); //.FirstOrDefault(x => (x.IDFromWorkUnitsDBTable == newmodel.IDFromWorkUnitsDBTable && x.AppUserID == newmodel.AppUserID && x.WorkUnitTypeID == newmodel.WorkUnitTypeID)); if (existingLock != null) { return(BadRequest("Lock already exists for record")); } RecordLocks thisLock = new RecordLocks(); thisLock.AppUserID = newmodel.AppUserID; thisLock.IDFromWorkUnitsDBTable = newmodel.IDFromWorkUnitsDBTable; thisLock.WorkUnitTypeID = newmodel.WorkUnitTypeID; thisLock.DateTimeItemWasLockedUTC = DateTime.UtcNow; thisLock.CreatedBy = newmodel.AppUserID.ToString(); thisLock.DateCreatedUTC = DateTime.UtcNow; thisLock.UpdatedBy = newmodel.AppUserID.ToString(); thisLock.LastUpdatedUTC = DateTime.UtcNow; _context.RecordLocks.Add(thisLock); ReturnData ret; ret = _context.SaveData(); if (ret.Message == "Success") { return(Ok()); } return(NotFound(ret)); } } return(BadRequest()); }
public async Task <IActionResult> DeleteLock(string category, string id, bool appendProjectIdToKey = false) { id = await AppendProjectIdIfRequired(id, appendProjectIdToKey); GoNorthUser currentUser = await _userManager.GetUserAsync(User); LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null && existingLock.UserId == currentUser.Id) { await _lockServiceDbAccess.DeleteLockById(existingLock.Id); } return(Ok()); }
/// <summary> /// Enters the lock with exclusive access where no other /// readers or writers can execute concurrently with the writer. /// </summary> /// <returns>The token used to control the duration of entry.</returns> public async Task <IDisposable> EnterWriteAsync() { LockEntry lockEntry = new LockEntry(); // The writer must maintain exclusive access until the write operation is complete IDisposable readerListToken = await ReaderListLock.EnterAsync().ConfigureAwait(false); _ = lockEntry.WhenReleased().ContinueWith(_ => readerListToken.Dispose()); await Task.WhenAll(ReaderList).ConfigureAwait(false); ReaderList.Clear(); return(lockEntry); }
public IActionResult LockNewsItem([FromBody] LockEntry lockentry) { var Message = ""; var NewsLockEntry = _NewsDBcontext.FeedItemQueueLocks .Where(t => t.fkItemID == lockentry.IDFromWorkUnitsDBTable) .FirstOrDefault(); if (NewsLockEntry == null) { var MaxID = _NewsDBcontext.FeedItemQueueLocks.Max(x => x.ID); FeedItemQueueLocks newLock = new FeedItemQueueLocks(); newLock.ID = MaxID + 1; newLock.LockedByRecipientID = lockentry.AppUserID; newLock.DateTimeItemWasLocked = DateTime.UtcNow; newLock.fkItemID = lockentry.IDFromWorkUnitsDBTable; _NewsDBcontext.FeedItemQueueLocks.Add(newLock); try { _NewsDBcontext.SaveChanges(); return(Ok()); } catch (Exception e) { var logInfo = e.Message + " - " + e.InnerException; { return(BadRequest(e.Message)); } } } else { var thisUser = _context.AppUser .Where(t => t.AppUserID == NewsLockEntry.LockedByRecipientID) .FirstOrDefault(); if (thisUser != null) { Message = thisUser.AppUserName + " (" + thisUser.AppUserID + ")"; } else { Message = "User ID - " + NewsLockEntry.LockedByRecipientID.ToString(); } return(NotFound("This Record is locked to " + Message)); } }
public static void InitMisc() { if (ContainerSlotsWithBank != null) { return; } LockEntry.Initialize(); ContainerSlotsWithBank = new bool[118]; ContainerSlotsWithBank.Fill(true, 19, 22); ContainerSlotsWithBank.Fill(true, 67, 73); ContainerSlotsWithoutBank = new bool[118]; ContainerSlotsWithoutBank.Fill(true, 19, 22); ContainerBankSlots = new bool[118]; ContainerBankSlots.Fill(true, 67, 73); InitItemSlotHandlers(); }
public LockEntry UnLockNewsItem(LockEntry lockentry) { var NewsLockEntry = _newsfeedcontext.FeedItemQueueLocks.Where(t => t.fkItemID == lockentry.IDFromWorkUnitsDBTable).FirstOrDefault(); var AppUserId = lockentry.AppUserID; if (NewsLockEntry != null) { if (AppUserId == NewsLockEntry.LockedByRecipientID) { _newsfeedcontext.FeedItemQueueLocks.Remove(NewsLockEntry); _newsfeedcontext.SaveChanges(); return(lockentry); } } return(null); }
public IActionResult UnLockNewsItem([FromBody] LockEntry lockentry) { var Message = ""; var AppUserId = lockentry.AppUserID; var NewsLockEntry = _NewsDBcontext.FeedItemQueueLocks .Where(t => t.fkItemID == lockentry.IDFromWorkUnitsDBTable) .FirstOrDefault(); if (NewsLockEntry != null) { if (AppUserId == NewsLockEntry.LockedByRecipientID) { _NewsDBcontext.FeedItemQueueLocks.Remove(NewsLockEntry); try { _NewsDBcontext.SaveChanges(); return(Ok("Record unlocked")); } catch (Exception e) { var logInfo = e.Message + " - " + e.InnerException; { return(BadRequest(e.Message)); } } } else { var thisUser = _context.AppUser .Where(t => t.AppUserID == NewsLockEntry.LockedByRecipientID) .FirstOrDefault(); if (thisUser != null) { Message = thisUser.AppUserName + " (" + thisUser.AppUserID + ")"; } else { Message = "User ID - " + NewsLockEntry.LockedByRecipientID.ToString(); } return(BadRequest("This Record is locked to " + Message)); } } return(NotFound("Lock for News record not found")); }
public async Task <IActionResult> DeleteExternalLock(string category, string id, string token, string userIdentifier, bool appendProjectIdToKey = false) { if (!(await ValidateExternalAccess(category, id, token))) { return(NotFound()); } id = await AppendProjectIdIfRequired(id, appendProjectIdToKey); LockEntry existingLock = await _lockServiceDbAccess.GetResourceLockEntry(category, id); if (existingLock != null && existingLock.UserId == ExternalUserConstants.ExternalUserId && existingLock.ExternalUserId == userIdentifier) { await _lockServiceDbAccess.DeleteLockById(existingLock.Id); } return(Ok()); }
/// <summary> /// Sends the new state of the trading window to other party /// </summary> /// <param name="otherParty">Whether this is sending the own info to the other party (or, if false, to oneself)</param> /// <param name="client">receiving party</param> /// <param name="money">new amount of money</param> /// <param name="items">new items</param> public static void SendTradeUpdate(IPacketReceiver client, bool otherParty, uint money, Item[] items) { using (RealmPacketOut packet = new RealmPacketOut(RealmServerOpCode.SMSG_TRADE_STATUS_EXTENDED, 30 + 72 * items.Length)) { packet.Write(otherParty); packet.Write(0); packet.Write(items.Length); packet.Write(items.Length); packet.Write(money); packet.Write(0); for (int val = 0; val < items.Length; ++val) { packet.WriteByte(val); Item obj = items[val]; if (obj != null) { packet.Write(obj.EntryId); packet.Write(obj.Template.DisplayId); packet.Write(obj.Amount); packet.Write(0); packet.Write(obj.GiftCreator); ItemEnchantment enchantment = obj.GetEnchantment(EnchantSlot.Permanent); packet.Write(enchantment != null ? enchantment.Entry.Id : 0U); packet.Zero(12); packet.Write(obj.Creator); packet.Write(obj.SpellCharges); packet.Write(obj.Template.RandomSuffixFactor); packet.Write(obj.RandomPropertiesId); LockEntry lockEntry = obj.Lock; packet.Write(lockEntry != null ? lockEntry.Id : 0U); packet.Write(obj.MaxDurability); packet.Write(obj.Durability); } else { packet.Zero(72); } } client.Send(packet, false); } }
/// <summary> /// Enters the lock with concurrent access where all readers /// can execute concurrently with respect to each other. /// </summary> /// <returns>The token used to control the duration of entry.</returns> public async Task <IDisposable> EnterReadAsync() { LockEntry lockEntry = new LockEntry(); Task readerTask = lockEntry.WhenReleased(); // The exclusive lock must be obtained to update the reader list, // but it's also necessary so that the reader will wait on any // writers that entered before it using (await ReaderListLock.EnterAsync().ConfigureAwait(false)) ReaderList.Add(readerTask); // Prevent the reader list from growing indefinitely _ = readerTask.ContinueWith(async _ => { using (await ReaderListLock.EnterAsync().ConfigureAwait(false)) ReaderList.Remove(readerTask); }); return(lockEntry); }
public string Unlock(LockEntry thislock) { string Message = ""; var todelete = _context.RecordLocks .FirstOrDefault(t => t.WorkUnitTypeID == thislock.WorkUnitTypeID && t.IDFromWorkUnitsDBTable == thislock.IDFromWorkUnitsDBTable && t.AppUserID == thislock.AppUserID); if (todelete == null) { Message = "Record Not Found"; return(Message); } base.Delete(todelete); Message = "Record Unlocked"; return(Message); }
public static void InitMisc() { if (ContainerSlotsWithBank == null) { LockEntry.Initialize(); LoadDBCs(); LoadSets(); ContainerSlotsWithBank = new bool[(int)InventorySlot.Count]; ContainerSlotsWithBank.Fill(true, (int)InventorySlot.Bag1, (int)InventorySlot.BagLast); ContainerSlotsWithBank.Fill(true, (int)InventorySlot.BankBag1, (int)InventorySlot.BankBagLast); ContainerSlotsWithoutBank = new bool[(int)InventorySlot.Count]; ContainerSlotsWithoutBank.Fill(true, (int)InventorySlot.Bag1, (int)InventorySlot.BagLast); ContainerBankSlots = new bool[(int)InventorySlot.Count]; ContainerBankSlots.Fill(true, (int)InventorySlot.BankBag1, (int)InventorySlot.BankBagLast); InitItemSlotHandlers(); } }
/// <summary> /// Tries to use this Object and returns whether the user succeeded using it. /// </summary> public bool TryUse(Character user) { if (!CanBeUsedBy(user) || m_go.Flags.HasFlag(GameObjectFlags.InUse)) { return(false); } if (!m_go.Entry.AllowMounted) { user.Dismount(); } LockEntry lockEntry = m_go.Entry.Lock; if (lockEntry != null && !lockEntry.RequiresAttack && lockEntry.RequiresKneeling) { user.StandState = StandState.Kneeling; } if (m_go.CanOpen(user)) { return(DoUse(user)); } return(false); }
public void PasswordEntered() { string text = this.passwordInput.Text; if (text.Length != 4) { ConsoleSystem.Run("notice.popup 5 \"Password must be 4 digits.\"", false); return; } string str = text; for (int i = 0; i < str.Length; i++) { if (!char.IsDigit(str[i])) { ConsoleSystem.Run("notice.popup 5 \"Must be digits only.\"", false); return; } } ConsoleNetworker.SendCommandToServer(string.Concat("lockentry.passwordentry ", text, " ", (!this.changingEntry ? "false" : "true"))); LockEntry.Hide(); }
/// <summary>Enter the exclusive lock.</summary> /// <returns>An async task,</returns> public async Task<IDisposable> Enter() { #if NETFX_CORE LockEntry next = new LockEntry(this); #else LockEntry next = new LockEntry(this, new StackTrace()); #endif for (;;) { LockEntry current = this.currentEntry; if (current != null) { await current.Wait(); await Task.Yield(); } else if (null == Interlocked.CompareExchange(ref this.currentEntry, next, null)) { return next; } } }
public string Lock(LockEntry newlock) { string Message = ""; var existingLock = _context.RecordLocks .FirstOrDefault(x => (x.IDFromWorkUnitsDBTable == newlock.IDFromWorkUnitsDBTable && x.WorkUnitTypeID == newlock.WorkUnitTypeID)); if (existingLock != null) { Message = "Lock already exists for record"; return(Message); } RecordLocks thisLock = new RecordLocks { AppUserID = newlock.AppUserID, IDFromWorkUnitsDBTable = newlock.IDFromWorkUnitsDBTable, WorkUnitTypeID = newlock.WorkUnitTypeID, DateTimeItemWasLockedUTC = DateTime.UtcNow, CreatedBy = newlock.AppUserID.ToString(), DateCreatedUTC = DateTime.UtcNow, UpdatedBy = newlock.AppUserID.ToString(), LastUpdatedUTC = DateTime.UtcNow }; var result = base.Add(thisLock); if (result != null) { Message = "Record Locked"; return(Message); } return(Message); }
public LockEntry LockNewsItem(LockEntry lockentry) { var NewsLockEntry = _newsfeedcontext.FeedItemQueueLocks.Where(t => t.fkItemID == lockentry.IDFromWorkUnitsDBTable).FirstOrDefault(); if (NewsLockEntry == null) { var MaxID = _newsfeedcontext.FeedItemQueueLocks.Max(x => x.ID); FeedItemQueueLocks newLock = new FeedItemQueueLocks { ID = MaxID + 1, LockedByRecipientID = lockentry.AppUserID, DateTimeItemWasLocked = DateTime.UtcNow, fkItemID = lockentry.IDFromWorkUnitsDBTable }; _newsfeedcontext.FeedItemQueueLocks.Add(newLock); _newsfeedcontext.SaveChanges(); return(lockentry); } return(null); }
internal void InitializeTemplate() { if (Names == null) { Names = new string[(int)ClientLocale.End]; } if (Descriptions == null) { Descriptions = new string[(int)ClientLocale.End]; } if (DefaultDescription == null) { DefaultDescription = ""; } if (string.IsNullOrEmpty(DefaultName) || Id == 0) { // something's off with these entries return; } ItemId = (ItemId)Id; //Faction = (FactionId)Faction; // faction, 3.2.2 RequiredSkill = SkillHandler.Get(RequiredSkillId); Set = ItemMgr.GetSet(SetId); Lock = LockEntry.Entries.Get(LockId); RequiredFaction = FactionMgr.Get(RequiredFactionId); RequiredProfession = SpellHandler.Get(RequiredProfessionId); SubClassMask = (ItemSubClassMask)(1 << (int)SubClass); EquipmentSlots = ItemMgr.EquipmentSlotsByInvSlot.Get((uint)InventorySlotType); InventorySlotMask = (InventorySlotTypeMask)(1 << (int)InventorySlotType); IsAmmo = InventorySlotType == InventorySlotType.Ammo; IsKey = Class == ItemClass.Key; IsBag = InventorySlotType == InventorySlotType.Bag; IsContainer = Class == ItemClass.Container || Class == ItemClass.Quiver; // enchantables can't be stacked IsStackable = MaxAmount > 1 && RandomSuffixId == 0 && RandomPropertiesId == 0; IsTwoHandWeapon = InventorySlotType == InventorySlotType.TwoHandWeapon; SetIsWeapon(); if (ToolCategory != 0)// && TotemCategory != TotemCategory.SkinningKnife) { ItemMgr.FirstTotemsPerCat[(uint)ToolCategory] = this; } if (GemPropertiesId != 0) { GemProperties = EnchantMgr.GetGemproperties(GemPropertiesId); if (GemProperties != null) { GemProperties.Enchantment.GemTemplate = this; } } if (Sockets == null) { Sockets = new SocketInfo[ItemConstants.MaxSocketCount]; } else if (Sockets.Contains(sock => sock.Color != 0)) { HasSockets = true; } if (Damages == null) { Damages = DamageInfo.EmptyArray; } if (Resistances == null) { Resistances = new int[(int)DamageSchool.Count]; } if (SocketBonusEnchantId != 0) { SocketBonusEnchant = EnchantMgr.GetEnchantmentEntry(SocketBonusEnchantId); } switch (Class) { case ItemClass.Weapon: ItemProfession = ItemProfessions.WeaponSubClassProfessions.Get((uint)SubClass); break; case ItemClass.Armor: ItemProfession = ItemProfessions.ArmorSubClassProfessions.Get((uint)SubClass); break; } if (SheathType == SheathType.Undetermined) { // TODO: Read sheath-id from Item.dbc } // spells if (Spells != null) { ArrayUtil.Prune(ref Spells); for (int i = 0; i < 5; i++) { Spells[i].Index = (uint)i; Spells[i].FinalizeAfterLoad(); } } else { Spells = ItemSpell.EmptyArray; } UseSpell = Spells.Where(itemSpell => itemSpell.Trigger == ItemSpellTrigger.Use && itemSpell.Spell != null).FirstOrDefault(); if (UseSpell != null) { UseSpell.Spell.RequiredTargetType = RequiredTargetType; UseSpell.Spell.RequiredTargetId = RequiredTargetId; } EquipSpells = Spells.Where(spell => spell.Trigger == ItemSpellTrigger.Equip && spell.Spell != null).Select(itemSpell => itemSpell.Spell).ToArray(); SoulstoneSpell = Spells.Where(spell => spell.Trigger == ItemSpellTrigger.Soulstone && spell.Spell != null).Select(itemSpell => itemSpell.Spell).FirstOrDefault(); HitSpells = Spells.Where(spell => spell.Trigger == ItemSpellTrigger.ChanceOnHit && spell.Spell != null).Select(itemSpell => itemSpell.Spell).ToArray(); if (UseSpell != null && (UseSpell.Id == SpellId.Learning || UseSpell.Id == SpellId.Learning_2)) { // Teaching TeachSpell = Spells.Where(spell => spell.Trigger == ItemSpellTrigger.Consume).FirstOrDefault(); } ConsumesAmount = (Class == ItemClass.Consumable || Spells.Contains(spell => spell.Trigger == ItemSpellTrigger.Consume)) && (UseSpell == null || !UseSpell.HasCharges); IsHearthStone = UseSpell != null && UseSpell.Spell.IsHearthStoneSpell; IsInventory = InventorySlotType != InventorySlotType.None && InventorySlotType != InventorySlotType.Bag && InventorySlotType != InventorySlotType.Quiver && InventorySlotType != InventorySlotType.Relic; // find set if (SetId != 0) { var set = ItemMgr.Sets.Get((uint)SetId); if (set != null) { ArrayUtil.Add(ref set.Templates, this); } } // truncate arrays if (Mods != null) { ArrayUtil.TruncVals(ref Mods); } else { Mods = StatModifier.EmptyArray; } IsCharter = Flags.HasFlag(ItemFlags.Charter); RandomSuffixFactor = EnchantMgr.GetRandomSuffixFactor(this); if (IsCharter) { Creator = () => new PetitionCharter(); } else if (IsContainer) { Creator = () => new Container(); } else { Creator = () => new Item(); } }
public void Start() { LockEntry.singleton = this; LockEntry.Hide(); }