/// <summary> /// VScan calls WCF service to complete data transfer on the server side. /// </summary> /// <param name="serverDirName"></param> /// <param name="countryId"></param> /// <param name="retailerId"></param> /// <param name="voucherId"></param> /// <param name="siteCode"></param> /// <param name="locationId"></param> /// <param name="userId"></param> public void CommitVoucherChanges(string serverDirName, int jobId, int countryId, int retailerId, int voucherId, int?folderId, string siteCode, string barCode, int locationId, int userId, string s1, string s2) { try { SecurityCheckThrow(s1, s2); RecordCallHistory("CommitVoucherChanges"); var uploadRootFolder = new DirectoryInfo(Global.Strings.UPLOADROOT); var directory = uploadRootFolder.Combine(serverDirName); if (directory.Exists) { var xmlName = directory.CombineFileName("data.xml"); ZipFileAccess.Instance.SaveVoucherXml(xmlName, jobId, countryId, retailerId, voucherId, folderId, siteCode, barCode, userId, locationId, serverDirName, typeId: 2); } } catch (Exception ex) { throw new FaultException <MyApplicationFault>(new MyApplicationFault(), ex.Message); } finally { FileLocks.Remove(serverDirName); } }
private void textEmp_KeyUp(object sender, KeyEventArgs e) { if (!keyLocker.Contains(e.KeyData)) { keyLocker.Add(e.KeyData); try { lastKeyData = e.KeyData; if (lastEmployeeText != textEmp.Text && !(textEmp.Text.Length == 1 && Regex.IsMatch(textEmp.Text, "[A-Za-z]"))) { buttonSelect.Text = label + "..."; if ((lastKeyData != Keys.Delete) && (lastKeyData != Keys.Back) && lastKeyData != Keys.Down && lastKeyData != Keys.Up) { ParseEmployee(false); } } else if ((textEmp.Text.Length == 1 && Regex.IsMatch(textEmp.Text, "[A-Za-z]")) || (textEmp.Text.Length == 0)) { buttonSelect.Text = label + "..."; } lastEmployeeText = textEmp.Text; } catch (Exception ex) { ErrorShower.OnShowError(null, ex.Message, ""); } finally { keyLocker.Remove(e.KeyData); } } }
public void UpdateTag(Tag newTag) { var previous = _tags.Single(x => x.Id == newTag.Id); if (previous != null) { _tags.Remove(previous); _tags.Add(newTag); } }
void OnTimerElapsed(object sender, ElapsedEventArgs arg) { while (true) { var item = m_CachedList.FirstOrDefault(i => i.ExpirationDate < arg.SignalTime); if (item == null) { break; } m_CachedList.Remove(item); } }
protected override void FileRemoved(string fullPath) { if (Path.GetExtension(fullPath).ToLowerInvariant() == ".xml") { _bMDXmlFiles.Remove(fullPath); foreach (Media fd in FindMediaList(f => (f is IngestMedia) && (f as IngestMedia).XmlFile == fullPath)) { ((IngestMedia)fd).XmlFile = string.Empty; } } else { base.FileRemoved(fullPath); } }
private bool RemoveItemFromList(ListBox2 parent, ListItem item) { bool b = (bool)m_list.Remove(item); RefreshParent(parent); return(b); }
public void Dispose() { if (observer != null && observers.Contains(observer)) { observers.Remove(observer); } }
private void text_KeyUp(object sender, KeyEventArgs e) { if (!keyLocker.Contains(e.KeyData)) { keyLocker.Add(e.KeyData); try { if (e.KeyData == Keys.Enter) { Parse(); if (ID > 0) { text.SelectAll(); } } else if (text.Text != lastText) { ID = 0; } lastText = text.Text; } catch (Exception ex) { Data.Env.WriteToLog(ex); } finally { keyLocker.Remove(e.KeyData); } } }
public void OnItemSaved(object sender, EventArgs args) { Item savedItem = null; ItemSavedRemoteEventArgs remoteArgs = args as ItemSavedRemoteEventArgs; ItemChanges savedItemChanges = null; //Thank you Mike Edwards! if (remoteArgs != null) { savedItem = remoteArgs.Item; savedItemChanges = remoteArgs.Changes; } else { savedItem = Event.ExtractParameter(args, 0) as Item; savedItemChanges = Event.ExtractParameter(args, 1) as ItemChanges; } if (savedItem != null && TemplateManager.IsFieldPartOfTemplate(SitecronConstants.SiteCronFieldIds.CronExpression, savedItem) && !StandardValuesManager.IsStandardValuesHolder(savedItem)) { if (savedItemChanges != null && !savedItemChanges.FieldChanges.ContainsAnyOf(SiteCronFieldIds.LastRunUTC, SiteCronFieldIds.NextRunUTC, SiteCronFieldIds.ExecutionTime, SiteCronFieldIds.LastRunLog) && !_inProcess.Contains(savedItem.ID)) { _inProcess.Add(savedItem.ID); Log.Info($"SiteCron based Item Saved/Created, reloading Jobs. {savedItem.Name} - {savedItem.ID.ToString()}", this); _scheduleManager.ScheduleAllJobs(); _inProcess.Remove(savedItem.ID); } else { Log.Info("SiteCron - Ignoring Saved Handler due to stats update.", this); } } else { try { string typeName = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronSavedHandlerType); if (!string.IsNullOrEmpty(typeName)) { Type type = Type.GetType(typeName); if (type != null) { object instance = Activator.CreateInstance(type); if (instance != null && instance is ISavedHandler) { MethodInfo method = type.GetMethod("OnItemSaved"); if (method != null) { method.Invoke(instance, new object[] { sender, args }); } } } } } catch (Exception ex) { Log.Error("SiteCron OnItemSaved Custom Type ERROR: " + ex.Message, ex, this); } } }
/// <summary> /// ”далить команды поворота изображени¤ /// </summary> public void RemoveFromStackRotateImage() { try { undoElements.ToList().RemoveAll(x => x.TypeString == "RotateCW" || x.TypeString == "RotateCCW"); undoElements.ToList().RemoveAll(x => x.TypeString == "RotateCW" || x.TypeString == "RotateCCW"); foreach (var item in undoElements.ToList()) { if (item.TypeString == "RotateCW" || item.TypeString == "RotateCCW") { undoElements.Remove(item); } } foreach (var item in redoElements.ToList()) { if (item.TypeString == "RotateCW" || item.TypeString == "RotateCCW") { redoElements.Remove(item); } } } catch (Exception ex) { Data.Env.WriteToLog(ex); } }
private void textBoxPerson_KeyUp(object sender, KeyEventArgs e) { if (!keyLocker.Contains(e.KeyData)) { keyLocker.Add(e.KeyData); try { if (e.KeyData == Keys.Enter && textBoxPerson.Text.Length > 0) { if (InvokeRequired) { BeginInvoke((MethodInvoker)(Find)); } else { Find(); } } } catch (Exception ex) { Data.Env.WriteToLog(ex); } finally { keyLocker.Remove(e.KeyData); } } }
public void Sync() { while (ObjectsForDeallocation.Count > 0) { foreach (var obj in ObjectsForDeallocation.ToArray()) { if (obj.RefCount == 0) { obj.VisitChilds <SceneObject>(obj => { if (obj.RefCount == 1) { obj.Deallocate(); } }, child => child.RefCount <= 1); } } foreach (var obj in ObjectsForDeallocation.ToArray()) { obj.DoDeallocation(); ObjectsForDeallocation.Remove(obj); } } foreach (var act in Actors.ToArray()) { act.SyncChanges(); } RenderContext.DeleteOrphaned(); }
/// <summary> /// 注册Ajax节点 /// </summary> /// <param name="node"></param> /// <param name="e"></param> private void AjaxMark(HtmlElement node, EventHandler e) { if (_ajaxSet == null) { _ajaxSet = new SynchronizedCollection <Tuple <HtmlElement, EventHandler> >(); _ajaxRaiser = new JobTimer(state => { foreach (var item in _ajaxSet.Where(p => p.Item1.GetAttribute(AjaxBlockEntity.AjaxBlock) == "0").ToArray()) { item.Item2(item.Item1, EventArgs.Empty); } }, Timeout.InfiniteTimeSpan) { AutoDispose = false }; } node.SetAttribute(AjaxBlockEntity.AjaxBlock, "0"); var q = from t in _ajaxSet where t.Item1 == node select t; var tuple = q.SingleOrDefault(); if (tuple != null) { _ajaxSet.Remove(tuple); } _ajaxSet.Add(Tuple.Create(node, e)); }
public static async void Block([NotNull] string key, [NotNull] Func <Task> taskFactory) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (taskFactory == null) { throw new ArgumentNullException(nameof(taskFactory)); } if (Running.Contains(key)) { // block if running return; } Running.Add(key); try { await taskFactory(); } finally { Running.Remove(key); } }
public T Get(string identifier) { lock (getLock) { // Check the cache var entry = _cache.Where(ce => ce.Identifier == identifier).SingleOrDefault(); // Remove entry if it's too old if (entry != null && entry.Expired) { _cache.Remove(entry); entry = null; } // If we still have a fresh entry, return it if (entry != null) { return(entry.Data); } else { // Otherwise, fetch it and cache it. T newData = default(T); newData = _onCacheMiss(identifier); _cache.Add(new CacheEntry <T> { Data = newData, Identifier = identifier, Expires = DateTime.Now.AddSeconds(_duration) }); return(newData); } } }
private void PingSource(CaseSource <T> caseSourceT) { while (!m_Shutdown) { try { caseSourceT.EndPoint.Ping(m_WSId); if (typeof(T) == typeof(WSCommEndpoint)) { Thread.Sleep(_wsCommPingTimeoutMsec); } else { Thread.Sleep(1000); } } catch (Exception) { break; } } m_PingThreads.Remove(Thread.CurrentThread); RemoveSource(caseSourceT); }
private static void MoveItemToState(Item item, String state) { if (inProcess.Contains(item.ID)) { return; } inProcess.Add(item.ID); try { Database db = Sitecore.Context.ContentDatabase; if (db != null && db.Name == "master") { Item project = db.GetItem(item[Data.ProjectFieldId]); if (project != null) { if (!item.Editing.IsEditing) { item.Editing.BeginEdit(); } item.Fields["__Workflow State"].Value = state; //final item.Editing.EndEdit(); } } } finally { inProcess.Remove(item.ID); } }
private static void UpdateRestrictionsOnVersion(Item item) { if (inProcess.Contains(item.ID)) { return; } inProcess.Add(item.ID); try { Database db = Sitecore.Context.ContentDatabase; if (db != null && db.Name == "master") { Item project = db.GetItem(item[Data.ProjectFieldId]); if (project != null) { if (!item.Editing.IsEditing) { item.Editing.BeginEdit(); } item.Publishing.ValidFrom = ((DateField)project.Fields[Data.ProjectDetailsReleaseDate]).DateTime; item.Editing.EndEdit(); } } } finally { inProcess.Remove(item.ID); } }
/// <summary> /// Removes reference to a vertex process /// </summary> /// <param name="processId">process id to forget</param> void IDryadVertexService.ReleaseProcess(int processId) { DryadLogger.LogMethodEntry(processId); VertexProcess vp = null; try { vp = FindByDryadId(processId); if (vp != null) { vertexProcessTable.Remove(vp); vp.Dispose(); } else { DryadLogger.LogWarning("Release Process", "Unknown process id {0}", processId); } } catch (Exception e) { DryadLogger.LogWarning("Release Process", "Operation threw exception: {0}", e.ToString()); } DryadLogger.LogMethodExit(); }
// This method is called for each NotificationRequests on each iteration of the polling loop. // It checks the capacity of the course in the request, and notifies the user if space is found. public async Task NotifyIfSpaceFound(NotificationRequest notificationRequest, SynchronizedCollection <NotificationRequest> notificationRequests) { // Fetch and log the capacity for the course. CourseCapacity capacity = await requests.GetCapacity(notificationRequest.RequestedCourse); logger.LogInformation($"Capacity for {notificationRequest.RequestedCourse.Term}|{notificationRequest.RequestedCourse.Subject}|{notificationRequest.RequestedCourse.Code}|{notificationRequest.RequestedCourse.Section} is {capacity.CurrentCapacity}"); // If we find capacity in the course, notify the user using their supplied contact method(s), logging any errors. if (capacity.CurrentCapacity > 0) { if (alertContact.SendNotification(notificationRequest)) { logger.LogInformation($"Space found in course {notificationRequest.RequestedCourse.Subject} {notificationRequest.RequestedCourse.Code} for user: {notificationRequest.Email} | {notificationRequest.Phone}"); // Remove the NotificationRequest from the in-memory collection, and repository. notificationRequests.Remove(notificationRequest); if (!repository.RemoveRequest(notificationRequest)) { logger.LogError($"Did not remove request from db: {notificationRequest.Email}|{notificationRequest.Phone}|{notificationRequest.RequestedCourse.Term}|{notificationRequest.RequestedCourse.Subject}|{notificationRequest.RequestedCourse.Code}|{notificationRequest.RequestedCourse.Section}"); } } else { logger.LogError($"Failed to send notification to user: {notificationRequest.Email}|{notificationRequest.Phone}|{notificationRequest.RequestedCourse.Term}|{notificationRequest.RequestedCourse.Subject}|{notificationRequest.RequestedCourse.Code}|{notificationRequest.RequestedCourse.Section}"); } } }
public void RecreateSingleTag(int?id) { Tag tag = _tags.Where(x => x.Id == id).SingleOrDefault(); if (tag != null) { lock (_locker) { var decisions = _decisions.ToList(); var existing = _decisionTags.Where(x => x.TagId == id); Parallel.ForEach(existing, existingTag => { _decisionTags.Remove(existingTag); }); Parallel.ForEach(_decisions, dec => { if (Regex.IsMatch(dec.Content, tag.RegExp, RegexOptions.IgnoreCase)) { DecisionTag dt = new DecisionTag() { DecisionId = dec.Id, TagId = tag.Id }; _decisionTags.Add(dt); } }); } } }
public void RemoveParserListener(IParserListener listener) { ParserListeners.Remove(listener); BeforeParsingStarted -= listener.OnBeforeParsingStarted; AfterParsingFinished -= listener.OnAfterParsingFinished; TrackChanged -= listener.OnTrackChanged; LayerChanged -= listener.OnLayerChanged; InstrumentParsed -= listener.OnInstrumentParsed; TempoChanged -= listener.OnTempoChanged; KeySignatureParsed -= listener.OnKeySignatureParsed; TimeSignatureParsed -= listener.OnTimeSignatureParsed; BarLineParsed -= listener.OnBarLineParsed; TrackBeatTimeBookmarked -= listener.OnTrackBeatTimeBookmarked; TrackBeatTimeBookmarkRequested -= listener.OnTrackBeatTimeBookmarkRequested; TrackBeatTimeRequested -= listener.OnTrackBeatTimeRequested; PitchWheelParsed -= listener.OnPitchWheelParsed; ChannelPressureParsed -= listener.OnChannelPressureParsed; PolyphonicPressureParsed -= listener.OnPolyphonicPressureParsed; SystemExclusiveParsed -= listener.OnSystemExclusiveParsed; ControllerEventParsed -= listener.OnControllerEventParsed; LyricParsed -= listener.OnLyricParsed; MarkerParsed -= listener.OnMarkerParsed; FunctionParsed -= listener.OnFunctionParsed; NotePressed -= listener.OnNotePressed; NoteReleased -= listener.OnNoteReleased; NoteParsed -= listener.OnNoteParsed; ChordParsed -= listener.OnChordParsed; }
/// <summary> /// Remove a controller from the server /// </summary> /// <param name="controller">the controller to remove</param> public void RemoveController(GraphQLController controller) { lock (_controllers.SyncRoot) { _controllers.Remove(controller); } }
public static void Unload(Sandboxer box) { if (box == null || box._Domain.IsDefaultAppDomain()) { return; } if (_boxes != null) { bool ok = _boxes.Remove(box); #if DEBUG App.LogInfo("Sandbox Ref Decrement {0} {1}", box.Name, ok); #endif } //AppDomain不能在IDisposable中卸载? //延迟卸载确保AppDomain内部执行完毕否则会引发AppDomainUnloadedException new JobTimer(state => { var b = (Sandboxer)state; try { #if DEBUG App.LogInfo("Sandbox Unload {0}", b.Name); #endif AppDomain.Unload(b._Domain); } catch (Exception ex) { App.LogError(ex, "Sandboxer Unload"); #if DEBUG throw; #endif } }, DateTime.Now.AddSeconds(16d)).Start(box); }
private void TaskCompleted(IAsyncResult ares) { if (ares != null) { AsyncResult aresult = (AsyncResult)ares; TaskItem task = (TaskItem)ares.AsyncState; Debug.Assert(task != null); Action <TaskItem> del = (Action <TaskItem>)aresult.AsyncDelegate; try { del.EndInvoke(ares); } finally { m_ActiveList.Remove(task); FireCompleted(task); m_ProcessedItems++; if (m_ActiveList.Count < m_MaxActiveTasks && m_ToDoList.Count > 0) { TaskItem task2 = null; lock (m_ToDoList.SyncRoot) { task2 = (TaskItem)m_ToDoList[0]; m_ToDoList.RemoveAt(0); } m_ActiveList.Add(task2); task2.Method.BeginInvoke(task2, new AsyncCallback(TaskCompleted), task2); } } } }
private void textEmp_KeyUp(object sender, KeyEventArgs e) { if (keyLocker.Contains(e.KeyData)) { return; } keyLocker.Add(e.KeyData); try { string txt = textEmp.Text.Trim(); lastKeyData = e.KeyData; if (lastEmployeeText != textEmp.Text && !(textEmp.Text.Length == 1 && Regex.IsMatch(textEmp.Text, "[A-Za-z]"))) { if (e.KeyData == Keys.Enter) { if (findEmployeeID > 0) { OnFindEmployee(findEmployeeID); } else { parser.Parse(ref txt); if (txt.Length > 0 && parser.CandidateCount > 0) { OnFindEmployee((int)parser.CandidateEmployees[0]["КодСотрудника"]); } } } if ((lastKeyData != Keys.Delete) && (lastKeyData != Keys.Back) && e.KeyData != Keys.Down && e.KeyData != Keys.Up && e.KeyData != Keys.Space) { ParseEmployee(false); } else if (lastKeyData == Keys.Delete || lastKeyData == Keys.Back) { findEmployeeID = 0; if (comboBoxEmp.DroppedDown) { comboBoxEmp.DroppedDown = false; } if (textEmp.Text.Trim().Length == 0) { OnFindEmployee(0); } } } lastEmployeeText = textEmp.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { keyLocker.Remove(e.KeyData); } }
public void Remove(Item item) { if (!m_ItemCollection.Remove(item)) { throw new Exception(item.ToString()); } FireItemRemoved(item); }
/// <summary> /// Removes a client from the internal list of connected clients. /// Should really only be called internally by the NetworkClient.Disconnect() /// method. /// </summary> /// <param name="Client">The client to remove.</param> public virtual void RemoveClient(NetworkClient Client) { m_LoginClients.Remove(Client); //TODO: Store session data for client... if (OnDisconnected != null) { OnDisconnected(Client); } }
public void RemoveDomain(AppDomain domain) { if (domain == null) { throw new ArgumentNullException("domain"); } domain.UnhandledException -= onException; domains.Remove(domain); }
/*public PhysicsWorld CreateWorld() { * PhysicsWorld world = new PhysicsWorld(new Vector2(0.0f, 9.82f)); * worlds.Add(world); * return world; * }*/ public void RemoveWorld(World world) { if (world == null) { throw new ArgumentNullException("world"); } lock (worldLock) { worlds.Remove(world); } }
private static void _runOperation(SynchronizedCollection<FileOperation> queue, ref bool queueRunningIndicator) { FileOperation op; lock (queue.SyncRoot) op = queue.FirstOrDefault(); while (op != null) { queue.Remove(op); if (!op.Aborted) { if (op.Do()) { if (OperationCompleted != null) OperationCompleted(op); if (op.SuccessCallback != null) op.SuccessCallback(); } else { if (op.TryCount > 0) { System.Threading.Thread.Sleep(500); queue.Add(op); } else { op.Fail(); if (OperationCompleted != null) OperationCompleted(op); } } } lock (queue.SyncRoot) op = queue.FirstOrDefault(); } lock (queue.SyncRoot) queueRunningIndicator = false; }
// This Unit test is based from full framework test public static void SynchronizedCollectionPublicMembersTest() { SynchronizedCollection<int> coll = new SynchronizedCollection<int>(); int size = 100; for (int i = 0; i < size; i++) coll.Add(i); Assert.True(coll.Count == size, string.Format("collection count was wrong! Expected: {0} got: {1}", size, coll.Count)); for (int i = 0; i < size; i++) { Assert.True(coll[i] == i, string.Format("coll element {0} was wrong! Expected: {1} got: {2} ", i, i, coll[i])); Assert.True(coll.IndexOf(i) == i, string.Format("coll IndexOf wasn't right! Expected: {0} got: {1}" , i, coll.IndexOf(i))); Assert.True(coll.Contains(i), string.Format("coll Contains failed to find the value {0}.", i)); } SynchronizedCollection<int> coll2 = new SynchronizedCollection<int>(new object(), new List<int>(coll)); for (int i = 0; i < size; i++) { Assert.True(coll2[i] == i, string.Format("coll2 element was wrong! expected: {0} got: {1} ", i, coll2[i])); } SynchronizedCollection<int> coll3 = new SynchronizedCollection<int>(new object(), 1, 2, 3, 4, 5 , 6); for (int i = 0; i < 5; i++) { Assert.True(coll3[i] == i + 1, string.Format("coll3 element {0} was wrong! expected: {1} got: {2}", i, i+1, coll3[i])); } int newValue = 80; coll3[5] = newValue; Assert.True(coll3[5] == newValue); IEnumerator <int> e = coll.GetEnumerator(); int n = 0; while (e.MoveNext()) { Assert.True(e.Current.Equals(n++), string.Format("Expected: {0}, got:{1}", n-1, e.Current)); } Assert.True(n == 100, string.Format("Expect number of elements: {0}, got:{1}", 100, n)); int[] array = new int[size + 1]; coll.CopyTo(array, 1); for (int i = 0; i < size; i++) { Assert.True(array[i + 1] == i, string.Format("After CopyTo, Element {0} was wrong! Expected: {1} got: {2}", i, i+1, array[i + 1])); } coll.Add(coll.Count); coll.Insert(0, -1); coll.RemoveAt(0); coll.Remove(coll.Count - 1); Assert.True(coll.Count == size, string.Format("Expect number of elements after modification: {0}, got: {1}", size, coll.Count)); for (int i = 0; i < size; i++) { Assert.True(coll[i] == i, string.Format("coll element was wrong after modification! Expected: {0} got: {1} ", i, coll[i])); } coll.Clear(); Assert.True(coll.Count == 0, string.Format("Clear operation failed!, expected: 0, actual {0}", coll.Count)); // Negative cases Assert.Throws<ArgumentNullException>("syncRoot", () => { new SynchronizedCollection<int>(null); }); Assert.Throws<ArgumentNullException>("list", () => { new SynchronizedCollection<int>(new object(), null); }); Assert.Throws<ArgumentNullException>("syncRoot", () => { new SynchronizedCollection<int>(null, new List<int>()); }); Assert.Throws<ArgumentNullException>("syncRoot", () => { new SynchronizedCollection<int>(null, 1, 2, 3, 4); }); Assert.Throws<ArgumentOutOfRangeException>(() => { coll[1000] = 5; }); Assert.Throws<ArgumentOutOfRangeException>(() => { coll[-1] = 5; }); Assert.Throws<ArgumentOutOfRangeException>(() => { coll.Insert(1000, 5); }); Assert.Throws<ArgumentOutOfRangeException>(() => { coll.Insert(-1, 5); }); Assert.False(coll.Remove(100000)); Assert.Throws<ArgumentOutOfRangeException>(() => { coll.RemoveAt(-1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { coll.RemoveAt(10000); }); }