public IActionResult Add(Event model) { if (SessionCheck() == 0) { return(RedirectToAction("Index", "User")); } if (ModelState.IsValid) { Event newEvent = new Event //create an event object called newEvent { Host = model.Host, Title = model.Title, Description = model.Description, Address = model.Address, Date = model.Date, UserId = (int)SessionCheck() }; _context.Add(newEvent); //add newEvent to DB _context.SaveChanges(); return(RedirectToAction("Dashboard", "Event")); } else { return(View("new")); } }
public async Task <IActionResult> Create([Bind("BuyerId,EventId,TesterKey,BuyerName")] Buyer buyer) { if (ModelState.IsValid) { _context.Add(buyer); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(buyer)); }
public async Task <IActionResult> Create([Bind("Id,EventNum,EventName,EventCode,IsQuiz,IsExam,GradePointsAvailable,ReqRunCheck")] Event @event) { if (ModelState.IsValid) { _context.Add(@event); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(@event)); }
public short Create(EventDetail eventDetail) { _eventContext.Add(eventDetail); _eventContext.SaveChanges(); _logger.LogInformation($"Evento {eventDetail.ID} foi salvo com sucesso"); return(eventDetail.ID); }
public IActionResult CreateEvent(NewEventViewModel model) { if (ModelState.IsValid) { Event NewEvent = new Event { Title = model.Title, EventDate = model.EventDate, EventTime = model.EventTime, Duration = model.Duration, DurationType = model.DurationType, Description = model.Description, CreatedById = (int)HttpContext.Session.GetInt32("UserId"), CreatedByFirstName = (string)HttpContext.Session.GetString("UserAlias"), CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, }; _context.Add(NewEvent); _context.SaveChanges(); return(RedirectToAction("Main", "Event")); } else { return(View("NewEvent")); } }
public IActionResult Register(UserViewModels model) { if (ModelState.IsValid) { User ExistingUser = _context.Users.SingleOrDefault(user => user.email == model.Reg.email); if (ExistingUser != null) { ModelState.AddModelError("Reg.Email", "An account with this email already exists!"); return(View("Index")); } PasswordHasher <UserViewModels> hasher = new PasswordHasher <UserViewModels>(); string hashed = hasher.HashPassword(model, model.Reg.password); User newUser = new User { firstname = model.Reg.firstname, lastname = model.Reg.lastname, email = model.Reg.email, password = hashed }; _context.Add(newUser); _context.SaveChanges(); newUser = _context.Users.SingleOrDefault(user => user.email == newUser.email); HttpContext.Session.SetInt32("UserId", newUser.UserId); HttpContext.Session.SetString("user", newUser.firstname); return(RedirectToAction("Dashboard", "Event")); } else { return(View("Index")); } }
public EventLog Save(EventLog eventLog) { var state = eventLog.EventID == 0 ? EntityState.Added : EntityState.Modified; eventcontext.Entry(eventLog).State = state; eventcontext.Add(eventLog); eventcontext.SaveChanges(); return(eventLog); }
public async Task <IActionResult> Create([Bind("Id,Name,DiscordText,Template,Emote,Filter,LeadTime")] Role role) { if (ModelState.IsValid) { _context.Add(role); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(role)); }
public async Task <IActionResult> Create([Bind("Id,Date,Source,Criticite,Description")] Event @event) { if (ModelState.IsValid) { _context.Add(@event); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(@event)); }
public async Task <IActionResult> Create([Bind("Id,BotToken,Name")] DiscordBot discordBot) { if (ModelState.IsValid) { _context.Add(discordBot); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(discordBot)); }
public async Task <IActionResult> Create([Bind("EventId,EventName,EventDate,Capacity,NumberOfRegistrations")] Event @event) { if (ModelState.IsValid) { _context.Add(@event); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(@event)); }
public async Task <IActionResult> Create([Bind("Id,Name,EventChannelName,CalendarUrl,Template")] GuildConfig guildConfig) { if (ModelState.IsValid) { _context.Add(guildConfig); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(guildConfig)); }
public async Task <IActionResult> Create([Bind("EventId,Name,TimeoutInSeconds")] Event @event) { if (ModelState.IsValid) { _context.Add(@event); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(@event)); }
public async Task <IActionResult> Create([Bind("ID,Name,Email,Phone,Details,Service,Location,Date")] EventRequest eventRequest) { if (ModelState.IsValid) { _context.Add(eventRequest); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(eventRequest)); }
public async Task <IActionResult> Create([Bind("Id,Name,Description,DurationInMinutes,Start,Finish")] Event @event) { if (ModelState.IsValid) { @event.Id = Guid.NewGuid(); _context.Add(@event); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(@event)); }
public async Task <IActionResult> Create(int eventId, [Bind("Id,EventId,FirstName,LastName,Email,Phone,Confirmed")] Attendee attendee) { if (ModelState.IsValid) { _context.Add(attendee); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index)); return(RedirectToAction("Details", "Events", new { id = attendee.EventId })); } return(View(attendee)); }
public IActionResult Add(Event model) { if (CheckSession() == 0) { return(RedirectToAction("Index", "User")); } if (ModelState.IsValid) { Event newEvent = new Event { Location = model.Location, Host = model.Host, Date = model.Date, Reason = model.Reason }; _context.Add(newEvent); _context.SaveChanges(); return(RedirectToAction("Dashboard")); } else { return(View("eventForm")); } }
// To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD public async Task <IActionResult> OnPostAsync() { if (ModelState.IsValid) { var user = await _userManager.GetUserAsync(User); Event.Organizer = user; _context.Add(Event); await _context.SaveChangesAsync(); TempData["Success"] = "The Event has been added!"; return(RedirectToPage("/Organizer/OrganizeEvents")); } return(Page()); }
public bool Save(User user) { User u = context.Users.Where(x => x.Email == user.Email).FirstOrDefault(); if (u != null) { throw new EmailAlreadyExistsException("Email já está em uso"); } // Encrypts user password user.Password = Md5Hash.Generate(user.Password); var state = user.Id == 0 ? EntityState.Added : EntityState.Modified; context.Entry(user).State = state; context.Add(user); context.SaveChanges(); return(true); }
private void PopulateContext() { var testInvitation = new Infrastructure.Entities.Invitation("testemail", eventTestGuid) { InvitationStatus = InvitationStatus.Accepted, Id = invitationTestGuid }; DateTime dateTime = DateTime.Now; Infrastructure.Entities.Event @event = new Infrastructure.Entities.Event("testeventname", "testeventdesc", dateTime); @event.Id = eventTestGuid; @event.SentInvitations.Add(testInvitation); _context.Add(@event); _context.SaveChanges(); }
//编辑保存 public ActionResult SaveEdit(ITC_Buttons_M model) { if (uifo.Exists(model.Buttons_ID)) { if (uifo.Update(model)) { EventContext.Add(MenuID, string.Format("修改:{0}", model.Buttons_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.Buttons_ID + "]不存在!")); } }
//删除 public ActionResult Delete(string ids) { int count = 0; foreach (string id in ids.Split(',')) { if (uifo.Delete(id)) { EventContext.Add(MenuID, string.Format("删除:{0}", id)); count++; } } if (count > 0) { return(Content("删除成功!")); } else { return(Content("删除失败!")); } }
//编辑保存 public ActionResult SaveEdit(ITC_Roles_M model) { if (uifo.Exists(model.Role_ID)) { model.Role_createdtime = DateTime.Now; model.Role_oprt = UserContext.UserName; if (uifo.Update(model)) { EventContext.Add(MenuID, string.Format("修改:{0}", model.Role_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.Role_ID + "]不存在!")); } }
//保存添加 public ActionResult SaveAdd(ITC_Position_M model) { if (!uifo.Exists(model.Position_ID)) { model.Position_createdtime = DateTime.Now; model.Position_Oprt = UserContext.UserName; if (uifo.Add(model)) { EventContext.Add(MenuID, string.Format("添加:{0}", model.Position_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.Position_ID + "]已存在!")); } }
//设置权限 public ActionResult SaveRight(FormCollection collection) { string roleid = Request["roleid"]; if (!string.IsNullOrEmpty(roleid)) { //删除菜单权限 操作权限 uifo.DeleteRoleRights(roleid); uifo.DeleteRoleOperator(roleid); if (collection.Count > 0) { string menuid = ""; string buttonid = ""; for (int i = 0; i < collection.Count; i++) { string key = collection.Keys[i]; string value = collection[i]; menuid = key.Split('|')[0]; buttonid = key.Split('|')[1]; //添加菜单权限 操作权限 if (value == "on") { uifo.AddRoleRights(roleid, menuid); uifo.AddRoleOperator(roleid, menuid, buttonid); } } } ITC_Roles_M model = uifo.GetModel(roleid); model.Role_oprt = UserContext.UserName; model.Role_createdtime = DateTime.Now; uifo.Update(model); EventContext.Add(MenuID, string.Format("设置权限:{0}", roleid)); return(Content("保存成功!")); } else { return(Content("参数错误!")); } }
//编辑保存 public ActionResult SaveEdit(ITC_Organization_M model) { model.Organization_createdtime = DateTime.Now; model.Organization_Oprt = UserContext.UserName; if (uifo.Exists(model.Orga_ID)) { if (uifo.Update(model)) { OrgaContext.InitCache(); EventContext.Add(MenuID, string.Format("修改:{0}", model.Orga_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.Orga_ID + "]不存在!")); } }
//保存用户角色 public ActionResult SaveRoles(FormCollection collection) { string userid = Request["userid"]; if (!string.IsNullOrEmpty(userid)) { //删除角色 部门范围 uifo.DeleteRoles(userid); uifo.DeleteRoleRange(userid); if (collection.Count > 0) { string roleid = ""; string orgaid = ""; for (int i = 0; i < collection.Count; i++) { string key = collection.Keys[i]; string value = collection[i]; roleid = key.Split('|')[0]; orgaid = key.Split('|')[1]; //添加角色 部门范围 if (value == "on") { uifo.AddRoles(userid, roleid); uifo.AddRoleRange(userid, roleid, orgaid); } } } ITC_Userinfo_M model = uifo.GetModel(userid); model.User_Oprt = Session["username"].ToString(); model.User_Createdtime = DateTime.Now; uifo.Update(model); EventContext.Add(MenuID, string.Format("分配角色:{0}", userid)); return(Content("保存成功!")); } else { return(Content("参数错误!")); } }
//编辑保存 public ActionResult SaveEdit(ITC_Userinfo_M model) { model.User_Createdtime = DateTime.Now; model.User_Account = model.User_ID.Trim(); model.User_Oprt = UserContext.UserName; if (uifo.Exists(model.User_ID)) { if (uifo.Update(model)) { EventContext.Add(MenuID, string.Format("修改:{0}", model.User_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.User_ID + "]不存在!")); } }
public IActionResult Register(UserViewModels model) //checking passed in model against UserViewModel validations { if (ModelState.IsValid) { User exist = _context.Users.SingleOrDefault(u => u.Email == model.Reg.Email); //query to set exist to check if email input already exists in db if (exist != null) { ModelState.AddModelError("Reg.Email", "That email already exists in the database."); return(View("Index")); } else { PasswordHasher <UserViewModels> hasher = new PasswordHasher <UserViewModels>(); string hashed = hasher.HashPassword(model, model.Reg.Password); User newUser = new User { First = model.Reg.First, Last = model.Reg.Last, Email = model.Reg.Email, Password = hashed, }; _context.Add(newUser); _context.SaveChanges(); User CurrUser = _context.Users.SingleOrDefault(user => user.Email == newUser.Email); //see the newly created object by grabbing email HttpContext.Session.SetInt32("userid", CurrUser.UserId); //setting session id HttpContext.Session.SetString("username", CurrUser.First); //seting username to first name of session user return(RedirectToAction("Success", "User")); } } else { return(View("Index")); } }
//添加保存 public ActionResult SaveAdd(ITC_Userinfo_M model) { model.User_Createdtime = DateTime.Now; model.User_Pwd = uifo.pwEcncrystr("123456");//加密 model.User_Account = model.User_ID.Trim(); model.User_Oprt = UserContext.UserName; if (!uifo.Exists(model.User_ID)) { if (uifo.Add(model)) { EventContext.Add(MenuID, string.Format("添加:{0}", model.User_ID)); return(Content("保存成功!")); } else { return(Content("保存失败!")); } } else { return(Content("保存失败! 编码[" + model.User_ID + "]已存在!")); } }
/// <summary> /// Removes key and value pairs from the cache. The keys are specified as parameter. /// Moreover it take a removal reason and a boolean specifying if a notification should /// be raised. /// </summary> /// <param name="keys">keys of the entry.</param> /// <param name="removalReason">reason for the removal.</param> /// <param name="notify">boolean specifying to raise the event.</param> /// <returns>list of removed keys</returns> public override Hashtable Remove(object[] keys, ItemRemoveReason removalReason, bool notify, bool isUserOperation, OperationContext operationContext) { Hashtable table = new Hashtable(); EventContext eventContext = null; EventId eventId = null; OperationID opId = operationContext.OperatoinID; for (int i = 0; i < keys.Length; i++) { try { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); if (notify) { //generate EventId eventId = new EventId(); eventId.EventUniqueID = opId.OperationId; eventId.OperationCounter = opId.OpCounter; eventId.EventCounter = i; eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); operationContext.Add(OperationContextFieldName.EventContext, eventContext); } CacheEntry e = Remove(keys[i], removalReason, notify, null, LockAccessType.IGNORE_LOCK, operationContext); if (e != null) { table[keys[i]] = e; } } catch (StateTransferException e) { table[keys[i]] = e; } finally { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); } } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return table; }
/// <summary> /// Adds key and value pairs to the cache. If any of the specified keys /// already exists in the cache; it is updated, otherwise a new item is /// added to the cache. /// </summary> /// <param name="keys">keys of the entries.</param> /// <param name="cacheEntry">the cache entries.</param> /// <returns>returns keys that are added or updated successfully and their status.</returns> public sealed override Hashtable Insert(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext) { Hashtable table = new Hashtable(); EventContext eventContext = null; EventId eventId = null; OperationID opId = operationContext.OperatoinID; for (int i = 0; i < keys.Length; i++) { try { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); if (notify) { //generate EventId eventId = new EventId(); eventId.EventUniqueID = opId.OperationId; eventId.OperationCounter = opId.OpCounter; eventId.EventCounter = i; eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); operationContext.Add(OperationContextFieldName.EventContext, eventContext); } CacheInsResultWithEntry result = Insert(keys[i], cacheEntries[i], notify, null, LockAccessType.IGNORE_LOCK, operationContext); table.Add(keys[i], result); } catch (Exception e) { table[keys[i]] = e; } finally { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); } } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return table; }
/// <summary> /// Adds key and value pairs to the cache. Throws an exception or returns the /// list of keys that failed to add in the cache. /// </summary> /// <param name="keys">keys of the entries.</param> /// <param name="cacheEntries">the cache entries.</param> /// <returns>List of keys that are added or that alredy exists in the cache and their status.</returns> public sealed override Hashtable Add(object[] keys, CacheEntry[] cacheEntries, bool notify, OperationContext operationContext) { Hashtable table = new Hashtable(); EventContext eventContext = null; EventId eventId = null; OperationID opId = operationContext.OperatoinID; for (int i = 0; i < keys.Length; i++) { try { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); if (notify) { //generate EventId eventId = new EventId(); eventId.EventUniqueID = opId.OperationId; eventId.OperationCounter = opId.OpCounter; eventId.EventCounter = i; eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); operationContext.Add(OperationContextFieldName.EventContext, eventContext); } CacheAddResult result = Add(keys[i], cacheEntries[i], notify, operationContext); table[keys[i]] = result; } catch (Exceptions.StateTransferException se) { table[keys[i]] = se; } catch (Exception inner) { table[keys[i]] = new OperationFailedException(inner.Message, inner); } finally { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); } } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return table; }
/// <summary> /// Retrieve the objects from the cache. /// An array of keys is passed as parameter. /// </summary> /// <param name="keys">keys of the entries.</param> /// <returns>key and entry pairs.</returns> public sealed override Hashtable Get(object[] keys, OperationContext operationContext) { Hashtable entries = new Hashtable(); CacheEntry e = null; for (int i = 0; i < keys.Length; i++) { try { if(operationContext != null) { operationContext.RemoveValueByField(OperationContextFieldName.EventContext); OperationID opId = operationContext.OperatoinID; //generate EventId EventId eventId = EventId.CreateEventId(opId); eventId.EventUniqueID = opId.OperationId; eventId.OperationCounter = opId.OpCounter; eventId.EventCounter = i; EventContext eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); operationContext.Add(OperationContextFieldName.EventContext, eventContext); } e = Get(keys[i], operationContext); if (e != null) { entries[keys[i]] = e; } } catch (StateTransferException se) { entries[keys[i]] = se; } } return entries; }
/// <summary> /// Adds a pair of key and value to the cache. If the specified key already exists /// in the cache; it is updated, otherwise a new item is added to the cache. /// </summary> /// <param name="key">key of the entry.</param> /// <param name="cacheEntry">the cache entry.</param> /// <returns>returns the result of operation.</returns> public sealed override CacheInsResultWithEntry Insert(object key, CacheEntry cacheEntry, bool notify, bool isUserOperation, object lockId, LockAccessType access, OperationContext operationContext) { CacheInsResultWithEntry result = new CacheInsResultWithEntry(); try { CacheEntry pe = null; CallbackEntry cbEtnry = null; OperationID opId = operationContext.OperatoinID; EventId eventId = null; EventContext eventContext = null; pe = GetInternal(key, false, operationContext); result.Entry = pe; if (pe != null && access != LockAccessType.IGNORE_LOCK) { { if (access == LockAccessType.RELEASE || access == LockAccessType.DONT_RELEASE) { if (pe.IsItemLocked() && !pe.CompareLock(lockId)) { result.Result = CacheInsResult.ItemLocked; result.Entry = null; return result; } } if (access == LockAccessType.DONT_RELEASE) { cacheEntry.CopyLock(pe.LockId, pe.LockDate, pe.LockExpiration); } else { cacheEntry.ReleaseLock(); } } } ExpirationHint peExh = pe == null ? null : pe.ExpirationHint; if (pe != null && pe.Value is CallbackEntry) { cbEtnry = pe.Value as CallbackEntry; cacheEntry = CacheHelper.MergeEntries(pe, cacheEntry); } result.Result = InsertInternal(key, cacheEntry, isUserOperation, pe, operationContext); if ((result.Result == CacheInsResult.Success || result.Result == CacheInsResult.SuccessNearEvicition) && _stateTransferKeyList != null && _stateTransferKeyList.ContainsKey(key)) { result.Result = result.Result == CacheInsResult.Success ? CacheInsResult.SuccessOverwrite : CacheInsResult.SuccessOverwriteNearEviction; } // Not enough space, evict and try again. if (result.Result == CacheInsResult.NeedsEviction || result.Result == CacheInsResult.SuccessNearEvicition || result.Result == CacheInsResult.SuccessOverwriteNearEviction) { Evict(); if (result.Result == CacheInsResult.SuccessNearEvicition) result.Result = CacheInsResult.Success; if (result.Result == CacheInsResult.SuccessOverwriteNearEviction) result.Result = CacheInsResult.SuccessOverwrite; } // Operation completed! if (result.Result == CacheInsResult.Success || result.Result == CacheInsResult.SuccessOverwrite) { // commented by muds //remove the old hint from expiry index. if (peExh != null) _context.ExpiryMgr.RemoveFromIndex(key); if (cacheEntry.ExpirationHint != null) { cacheEntry.ExpirationHint.CacheKey = (string)key; if (isUserOperation) { try { _context.ExpiryMgr.ResetHint(peExh, cacheEntry.ExpirationHint); } catch (Exception e) { RemoveInternal(key, ItemRemoveReason.Removed, false, operationContext); throw e; } } else { cacheEntry.ExpirationHint.ReInitializeHint(Context); } _context.ExpiryMgr.UpdateIndex(key, cacheEntry); } if (IsSelfInternal) { _context.PerfStatsColl.IncrementCountStats((long)Count); } } _stats.UpdateCount(this.Count); switch (result.Result) { case CacheInsResult.Success: break; case CacheInsResult.SuccessOverwrite: if (notify) { EventCacheEntry eventCacheEntry = CacheHelper.CreateCacheEventEntry(Runtime.Events.EventDataFilter.DataWithMetadata, cacheEntry); ; EventCacheEntry oldEventCacheEntry = CacheHelper.CreateCacheEventEntry(Runtime.Events.EventDataFilter.DataWithMetadata, pe); if (cbEtnry != null) { if (cbEtnry.ItemUpdateCallbackListener != null && cbEtnry.ItemUpdateCallbackListener.Count > 0) { if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations { eventId = EventId.CreateEventId(opId); eventContext = new EventContext(); } else //for bulk { eventId = ((EventContext)operationContext.GetValueByField(OperationContextFieldName.EventContext)).EventID; } eventContext = new EventContext(); eventId.EventType = EventType.ITEM_UPDATED_CALLBACK; eventContext.Add(EventContextFieldName.EventID, eventId); eventContext.Item = eventCacheEntry; eventContext.OldItem = oldEventCacheEntry; NotifyCustomUpdateCallback(key, cbEtnry.ItemUpdateCallbackListener, false, (OperationContext)operationContext.Clone(), eventContext); } } } break; } } finally { } if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return result; }
/// <summary> /// Reaises the custom item remove call baack. /// </summary> /// <param name="key"></param> /// <param name="cbEntry"></param> internal void RaiseCustomRemoveCalbackNotifier(object key, CacheEntry cacheEntry, ItemRemoveReason reason, bool async, OperationContext operationContext, EventContext eventContext) { ArrayList destinations = null; ArrayList nodes = null; Hashtable intendedNotifiers = new Hashtable(); CallbackEntry cbEntry = cacheEntry.Value as CallbackEntry; if (cbEntry != null && cbEntry.ItemRemoveCallbackListener.Count > 0) { if (_stats.Nodes != null) { nodes = _stats.Nodes.Clone() as ArrayList; destinations = new ArrayList(); foreach (CallbackInfo cbInfo in cbEntry.ItemRemoveCallbackListener) { if (reason == ItemRemoveReason.Expired && cbInfo != null && !cbInfo.NotifyOnExpiration) continue; int index = nodes.IndexOf(new NodeInfo(Cluster.LocalAddress)); if (index != -1 && ((NodeInfo)nodes[index]).ConnectedClients.Contains(cbInfo.Client)) { if (!destinations.Contains(Cluster.LocalAddress)) { destinations.Add(Cluster.LocalAddress); } intendedNotifiers[cbInfo] = Cluster.LocalAddress; continue; } else { foreach (NodeInfo nInfo in nodes) { if (nInfo.ConnectedClients != null && nInfo.ConnectedClients.Contains(cbInfo.Client)) { if (!destinations.Contains(nInfo.Address)) { destinations.Add(nInfo.Address); intendedNotifiers[cbInfo] = nInfo.Address; break; } } } } } } } if (destinations != null && destinations.Count > 0) { if (operationContext == null) operationContext = new OperationContext(); if (eventContext == null || !eventContext.HasEventID(EventContextOperationType.CacheOperation)) { eventContext = CreateEventContext(operationContext, Persistence.EventType.ITEM_REMOVED_CALLBACK); eventContext.Item = CacheHelper.CreateCacheEventEntry(cbEntry.ItemRemoveCallbackListener, cacheEntry); eventContext.Add(EventContextFieldName.ItemRemoveCallbackList, cbEntry.ItemRemoveCallbackListener.Clone()); } object[] packed = new object[] { key, reason, intendedNotifiers, operationContext, eventContext }; ///Incase of parition, there can be same clients connected ///to multiple server. therefore the destinations list will contain more then ///one servers. so the callback will be sent to the same client through different server ///to avoid this, we will check the list for local server. if client is connected with ///local node, then there is no need to send callback to all other nodes ///if there is no local node, then we select the first node in the list. RaiseCustomRemoveCalbackNotifier(destinations, packed, async); } }
/// <summary> /// Removes the object and key pair from the cache. The key is specified as parameter. /// Moreover it take a removal reason and a boolean specifying if a notification should /// be raised. /// </summary> /// <param name="key">key of the entry.</param> /// <param name="removalReason">reason for the removal.</param> /// <param name="notify">boolean specifying to raise the event.</param> /// <param name="isUserOperation"></param> /// <param name="lockId"></param> /// <param name="accessType"></param> /// <param name="operationContext"></param> /// <returns>item value</returns> public override CacheEntry Remove(object key, ItemRemoveReason removalReason, bool notify, bool isUserOperation, object lockId, LockAccessType accessType, OperationContext operationContext) { CacheEntry e = null; CacheEntry pe = null; { object actualKey = key; if (key is object[]) { actualKey = ((object[])key)[0]; } if (accessType != LockAccessType.IGNORE_LOCK) { pe = GetInternal(actualKey, false, operationContext); if (pe != null) { if (pe.IsItemLocked() && !pe.CompareLock(lockId)) { throw new LockingException("Item is locked."); } } } e = RemoveInternal(actualKey, removalReason, isUserOperation, operationContext); EventId eventId = null; EventContext eventContext = null; OperationID opId = operationContext.OperatoinID; if (e != null) { if (_stateTransferKeyList != null && _stateTransferKeyList.ContainsKey(key)) _stateTransferKeyList.Remove(key); // commented by muds try { if (e.ExpirationHint != null) { _context.ExpiryMgr.RemoveFromIndex(key); ((IDisposable)e.ExpirationHint).Dispose(); } } catch (Exception ex) { NCacheLog.Error("LocalCacheBase.Remove(object, ItemRemovedReason, bool):", ex.ToString()); } if (IsSelfInternal) { // Disposed the one and only cache entry. ((IDisposable)e).Dispose(); if (removalReason == ItemRemoveReason.Expired) { _context.PerfStatsColl.IncrementExpiryPerSecStats(); } else if (!_context.CacheImpl.IsEvictionAllowed && removalReason == ItemRemoveReason.Underused) { _context.PerfStatsColl.IncrementEvictPerSecStats(); } _context.PerfStatsColl.IncrementCountStats((long)Count); } if (notify) { CallbackEntry cbEtnry = e.Value as CallbackEntry;// e.DeflattedValue(_context.SerializationContext); if (cbEtnry != null && cbEtnry.ItemRemoveCallbackListener != null && cbEtnry.ItemRemoveCallbackListener.Count > 0) { //generate event id if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations { eventId = EventId.CreateEventId(opId); } else //for bulk { eventId = ((EventContext)operationContext.GetValueByField(OperationContextFieldName.EventContext)).EventID; } eventId.EventType = EventType.ITEM_REMOVED_CALLBACK; eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); EventCacheEntry eventCacheEntry = CacheHelper.CreateCacheEventEntry(cbEtnry.ItemRemoveCallbackListener, e); eventContext.Item = eventCacheEntry; eventContext.Add(EventContextFieldName.ItemRemoveCallbackList, cbEtnry.ItemRemoveCallbackListener.Clone()); //Will always reaise the whole entry for old clients NotifyCustomRemoveCallback(actualKey, e, removalReason, false, (OperationContext)operationContext.Clone(), eventContext); } } } else if (_stateTransferKeyList != null && _stateTransferKeyList.ContainsKey(key)) { _stateTransferKeyList.Remove(key); } } _stats.UpdateCount(this.Count); if (_context.PerfStatsColl != null) { _context.PerfStatsColl.SetCacheSize(Size); } return e; }
public override object RemoveSync(object[] keys, ItemRemoveReason reason, bool notify, OperationContext operationContext) { try { Hashtable totalRemovedItems = new Hashtable(); CacheEntry entry = null; IDictionaryEnumerator ide = null; if (NCacheLog.IsInfoEnabled) NCacheLog.Info("PartitionedCache.RemoveSync", "Keys = " + keys.Length.ToString()); for (int i = 0; i < keys.Length; i++) { try { if (keys[i] != null) entry = Local_Remove(keys[i], reason, null, null, false, null, LockAccessType.IGNORE_LOCK, operationContext); if (entry != null) { totalRemovedItems.Add(keys[i], entry); } } catch (Exception ex) { throw; } } ArrayList keysOfRemoveNotification = new ArrayList(); ArrayList entriesOfRemoveNotification = new ArrayList(); List<EventContext> eventContexts = new List<EventContext>(); int sizeThreshhold = 30*1024; int countThreshhold = 50; int size = 0; ide = totalRemovedItems.GetEnumerator(); while (ide.MoveNext()) { try { entry = ide.Value as CacheEntry; if (entry != null) { if (entry.Value is CallbackEntry) { EventId eventId = null; OperationID opId = operationContext.OperatoinID; CallbackEntry cbEtnry = (CallbackEntry) entry.Value; EventContext eventContext = null; if (cbEtnry != null && cbEtnry.ItemRemoveCallbackListener != null && cbEtnry.ItemRemoveCallbackListener.Count > 0) { //generate event id if (!operationContext.Contains(OperationContextFieldName.EventContext)) //for atomic operations { eventId = EventId.CreateEventId(opId); } else //for bulk { eventId = ((EventContext) operationContext.GetValueByField(OperationContextFieldName.EventContext)) .EventID; } eventId.EventType = Alachisoft.NCache.Persistence.EventType.ITEM_REMOVED_CALLBACK; eventContext = new EventContext(); eventContext.Add(EventContextFieldName.EventID, eventId); EventCacheEntry eventCacheEntry = CacheHelper.CreateCacheEventEntry(cbEtnry.ItemRemoveCallbackListener, entry); eventContext.Item = eventCacheEntry; eventContext.Add(EventContextFieldName.ItemRemoveCallbackList, cbEtnry.ItemRemoveCallbackListener.Clone()); RaiseAsyncCustomRemoveCalbackNotifier(ide.Key, entry, reason, operationContext, eventContext); } } } } catch (Exception) { } } } catch (Exception) { } return null; }