public virtual async Task EmitAsync(IOpenModComponent component, object sender, IEvent @event, EventExecutedCallback callback = null) { if (!component.IsComponentAlive) { return; } m_Logger.LogTrace($"Emitting event: {@event.Name}"); var eventSubscriptions = m_EventSubscriptions .Where(c => (c.EventType != null && c.EventType.IsInstanceOfType(@event)) || (@event.Name.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) && c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive)) .ToList(); void Complete() { m_Logger.LogTrace($"{@event.Name}: Finished."); callback?.Invoke(@event); } if (eventSubscriptions.Count == 0) { m_Logger?.LogTrace($"{@event.Name}: No listeners found."); Complete(); return; } var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst); eventSubscriptions.Sort((a, b) => comparer.Compare(a.EventListenerAttribute.Priority, b.EventListenerAttribute.Priority)); foreach (var group in eventSubscriptions.GroupBy(e => e.Scope)) { await using var newScope = group.Key.BeginLifetimeScope("AutofacWebRequest"); foreach (var subscription in group) { if (@event is ICancellableEvent cancellableEvent && cancellableEvent.IsCancelled && !subscription.EventListenerAttribute.IgnoreCancelled) { continue; } var serviceProvider = newScope.Resolve <IServiceProvider>(); try { await subscription.Callback.Invoke(serviceProvider, sender, @event); } catch (Exception ex) { m_Logger.LogError(ex, $"Exception occured during event {@event.Name}"); } } } Complete(); }
public void Should_return_0_for_other_case() { // Arrange var comparer = new PriorityComparer <GenericPriorityMessage <int> >(); var m1 = new GenericPriorityMessage <int>(1, 0); var m2 = new GenericPriorityMessage <int>(1, 0); // Action & Assert Assert.AreEqual(0, comparer.Compare(m2, m1)); }
public void Should_return_0_for_other_case() { // Arrange var comparer = new PriorityComparer<GenericPriorityMessage<int>>(); var m1 = new GenericPriorityMessage<int>(1, 0); var m2 = new GenericPriorityMessage<int>(1, 0); // Action & Assert Assert.AreEqual(0, comparer.Compare(m2, m1)); }
public void Should_return_minus_1_if_object_on_the_left_has_lower_priority_value() { // Arrange var comparer = new PriorityComparer <GenericPriorityMessage <int> >(); var m1 = new GenericPriorityMessage <int>(1, 10); var m2 = new GenericPriorityMessage <int>(1, 0); // Action & Assert Assert.AreEqual(-1, comparer.Compare(m2, m1)); }
public void Should_return_minus_1_if_object_on_the_left_has_lower_priority_value() { // Arrange var comparer = new PriorityComparer<GenericPriorityMessage<int>>(); var m1 = new GenericPriorityMessage<int>(1, 10); var m2 = new GenericPriorityMessage<int>(1, 0); // Action & Assert Assert.AreEqual(-1, comparer.Compare(m2, m1)); }
public virtual async Task EmitAsync(IOpenModComponent component, object sender, IEvent @event, EventExecutedCallback callback = null) { if (!component.IsComponentAlive) { return; } m_Logger.LogTrace($"Emitting event: {@event.Name}"); var eventSubscriptions = m_EventSubscriptions .Where(c => (c.EventType != null && c.EventType.IsInstanceOfType(@event)) || (@event.Name.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) && c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive)) .ToList(); void Complete() { m_Logger.LogTrace($"{@event.Name}: Finished."); callback?.Invoke(@event); } if (eventSubscriptions.Count == 0) { m_Logger?.LogTrace($"{@event.Name}: No listeners found."); Complete(); return; } var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst); eventSubscriptions.Sort((a, b) => comparer.Compare(a.EventListenerAttribute.Priority, b.EventListenerAttribute.Priority)); foreach (var subscription in eventSubscriptions) { var owner = subscription.Owner; if (!owner.IsAlive || !((IOpenModComponent)owner.Target).IsComponentAlive) { m_EventSubscriptions.Remove(subscription); continue; } if (@event is ICancellableEvent cancellableEvent && cancellableEvent.IsCancelled && !subscription.EventListenerAttribute.IgnoreCancelled) { continue; } var serviceProvider = subscription.Scope.Resolve <IServiceProvider>(); await subscription.Callback.Invoke(serviceProvider, sender, @event); } Complete(); }
public CommandStore(IOptions <CommandStoreOptions> options, IServiceProvider serviceProvider) { m_Comparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); m_CommandSources = options.Value.CreateCommandSources(serviceProvider); m_Options = options; m_ServiceProvider = serviceProvider; OnCommandSourcesChanged(); options.Value.OnCommandSourcesChanged += OnCommandSourcesChanged; }
public void Should_return_minus_1_if_object_on_the_left_is_younger_than_the_other_one() { // Arrange var comparer = new PriorityComparer<GenericPriorityMessage<int>>(); var m1 = new GenericPriorityMessage<int>(1, 0); System.Threading.Thread.Sleep(1); var m2 = new GenericPriorityMessage<int>(1, 0); // Action & Assert Assert.AreEqual(-1, comparer.Compare(m2, m1)); }
public void Should_return_minus_1_if_object_on_the_left_is_younger_than_the_other_one() { // Arrange var comparer = new PriorityComparer <GenericPriorityMessage <int> >(); var m1 = new GenericPriorityMessage <int>(1, 0); System.Threading.Thread.Sleep(1); var m2 = new GenericPriorityMessage <int>(1, 0); // Action & Assert Assert.AreEqual(-1, comparer.Compare(m2, m1)); }
public CommandStore(IOptions <CommandStoreOptions> options, IServiceProvider serviceProvider, IPermissionRegistry permissionRegistry, ICommandPermissionBuilder commandPermissionBuilder) { m_Comparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); m_CommandSources = options.Value.CreateCommandSources(serviceProvider); m_Options = options; m_ServiceProvider = serviceProvider; m_PermissionRegistry = permissionRegistry; m_CommandPermissionBuilder = commandPermissionBuilder; options.Value.OnCommandSourcesChanged += OnCommandSourcesChanged; OnCommandSourcesChanged(); }
private ProcessorSet(INMGenProcessor[] processors) { mProcessors = processors; PriorityComparer<INMGenProcessor> comp = new PriorityComparer<INMGenProcessor>(true); System.Array.Sort(mProcessors, comp); mIsThreadSafe = true; // This is correct. foreach (INMGenProcessor p in mProcessors) { mPreserveAssets |= p.PreserveAssets; if (!p.IsThreadSafe) mIsThreadSafe = false; } }
/// <summary> /// Sort a list of ProdutcBacklogItems in the same order as they are displayed in the GUI in the priority vuew /// </summary> /// <param name="project">The Project that the ProductBacklogItems belong to.</param> /// <param name="unsorted">The ProductBacklogItems that should be sorted.</param> /// <returns></returns> public static List <ProductBacklogItem> SortByPriority(Project project, List <ProductBacklogItem> unsorted) { List <ProductBacklogItem> sorted = new List <ProductBacklogItem>(); foreach (ProductBacklogItem anItem in unsorted) { if (anItem is ProductBacklogItemInSprint || anItem is ProductBacklogItemInSchedule) { sorted.Add((ProductBacklogItem)Task.GetTask(anItem.Session.TaskGetMainReference(anItem.UniqueTaskID))); } else { sorted.Add(anItem); } } List <HansoftItem> sortedBacklog = new List <HansoftItem>(); List <HansoftItem> allLeaves = project.ProductBacklog.DeepLeaves; ProductBacklogItem item = (ProductBacklogItem)allLeaves.Find(leaf => !allLeaves.Exists(prevLeaf => prevLeaf.Session.TaskRefGetPreviousWorkPriorityID(prevLeaf.UniqueID).m_ID == leaf.UniqueID.m_ID)); sortedBacklog.Add(item); HPMUniqueID nextId = item.Session.TaskRefGetPreviousWorkPriorityID(item.UniqueID); while (nextId != -2) { item = (ProductBacklogItem)Task.GetTask(nextId); sortedBacklog.Add(item); nextId = item.Session.TaskRefGetPreviousWorkPriorityID(item.UniqueID); } foreach (ProductBacklogItem aItem in sorted) { aItem.AbsolutePriority = sortedBacklog.FindIndex(ii => ii.UniqueID.m_ID == aItem.UniqueID.m_ID); } PriorityComparer comparer = new PriorityComparer(); sorted.Sort(comparer); sorted.Reverse(); return(sorted); }
private ProcessorSet(INMGenProcessor[] processors) { mProcessors = processors; PriorityComparer <INMGenProcessor> comp = new PriorityComparer <INMGenProcessor>(true); System.Array.Sort(mProcessors, comp); mIsThreadSafe = true; // This is correct. foreach (INMGenProcessor p in mProcessors) { mPreserveAssets |= p.PreserveAssets; if (!p.IsThreadSafe) { mIsThreadSafe = false; } } }
public CommandParameterResolverOptions() { m_CommandParameterResolveProviderTypes = new List <Type>(); m_PriorityComparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); }
public UserManagerOptions() { m_PriorityComparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); m_UserProviderTypes = new List <Type>(); }
/// <summary> /// writes a message in the Event Viewer by proving usefull infomration on what assemlbies have been loaded correctly /// </summary> private static void WriteFoundAssembliesInLog(List <Assembly> result) { if (result == null || result.Count == 0) { var messageToThrow = String.Format("Cannot configure ObjectFactory: no assembly is found with the search pattern {0}", ConfigurationManager.AppSettings[APP_SETTING_KEY_AUTO_LOAD_MODULE_PATTERN]); WriteEntryLog(messageToThrow, true); throw new DependencyInjectionException(messageToThrow); } var sb = new StringBuilder(); sb.AppendLine("###### The kernel's object factory has started using the auto module loading ######"); sb.AppendLine("The pattern defined in config for searching modules in assemblies is: "); sb.AppendLine(ConfigurationManager.AppSettings[APP_SETTING_KEY_AUTO_LOAD_MODULE_PATTERN]); sb.AppendLine("Assemblies that matched with selected pattern are listed below. Please note that lower the priority," + "earlier the module is loaded. "); foreach (var foundAssembly in result) { sb.AppendLine(string.Format("- {0} with module loading priority: {1} ", foundAssembly.FullName, PriorityComparer.ReadPriority(foundAssembly))); } WriteEntryLog(sb.ToString(), false); }
public PermissionCheckerOptions() { m_PermissionCheckProviderTypes = new List <Type>(); m_PermissionSourceTypes = new List <Type>(); m_PriorityComparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); }
public JobExecutorOptions() { m_PriorityComparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); m_JobExecutorTypes = new List <Type>(); }
/// <summary> /// sort list using custom comparer /// </summary> public void SortByPriority() { PriorityComparer pc = new PriorityComparer(PrioritySortField.PRIORITY_NAME); this.streamList.Sort(pc); }
private IEnumerable <Pupil> Assign(IEnumerable <Project> projects, IEnumerable <Pupil> pupils, Random random, bool preferation, out int[] grantedChoices, Parameter[] parameters = null) { List <Pupil> remaining = new List <Pupil>(); int choiceCount = 0; Parallel.ForEach(pupils, (Pupil pupil) => { if (pupil.Choices.Length <= 0) { throw new ArgumentException("The pupil " + pupil.ToString() + " does not have any choices."); } if (choiceCount == 0) { choiceCount = pupil.Choices.Length; } else if (pupil.Choices.Length != choiceCount) { throw new ArgumentException("The pupils have inconsistent numbers of choices."); } Project project = null; for (int i = choiceCount - 1; i >= 0; --i) { project = pupil.Choices[i]; if (project != null) { if ((parameters == null || project.Condition.DoesFulfill(pupil, parameters))) { lock (project) { if (project.InterestedCount == null) { project.InterestedCount = new int[choiceCount]; } project.InterestedCount[i]++; if (project.Interested == null) { project.Interested = new List <Pupil> [choiceCount]; for (int j = 0; j < choiceCount; j++) { project.Interested[j] = new List <Pupil>(); } } project.Interested[i].Add(pupil); } } else { pupil.Choices[i] = null; } } } for (int i = 0; i < choiceCount; i++) { } lock (remaining) { remaining.Add(pupil); } }); grantedChoices = new int[choiceCount]; int[] granted = new int[choiceCount]; Parallel.ForEach(projects, (Project project) => //foreach (var project in projects) { if (project.InterestedCount == null) { project.InterestedCount = new int[choiceCount]; } if (project.Interested == null) { project.Interested = new List <Pupil> [choiceCount]; for (int j = 0; j < choiceCount; j++) { project.Interested[j] = new List <Pupil>(); } } float interestValue = 0; for (int i = 0; i < choiceCount; i++) { interestValue += (float)(project.InterestedCount[i] / Math.Pow(2, i)); } project.Priority = interestValue - project.MaxMemberCount - Math.Max(0, project.MinMemberCount - interestValue); //project.Priority = Math.Max(0, interestValue - project.MaxMemberCount) - Math.Max(0, project.MinMemberCount - interestValue); }); //bool generalActivity; //do //{ Parallel.ForEach(remaining, (Pupil pupil) => { float pupilPriority = 0; for (int i = 0; i < choiceCount; i++) { if (pupil.Choices[i] == null) { pupilPriority += remaining.Count; } else { pupilPriority += (float)(pupil.Choices[i].Priority / Math.Pow(2, i)); } } if (preferation && (pupil.Name.Contains("Ehrmuth") || pupil.Name.Contains("Rostalski"))) { pupilPriority = float.MaxValue; } //else //pupilPriority /= choiceCount; pupil.ChoicePriority = pupilPriority; /* * for (int i = 0; i < choiceCount; i++) * { * project = projects[pupil.Choices[i]]; * if (pupilPriority >= project.Priority) * { * project.Members.Add(pupil); * break; * } * }*/ }); PriorityComparer comparer = new PriorityComparer(random, remaining.Count, preferation); //for (int choice = 0; choice < choiceCount; choice++) //{ // foreach (var project in projects) // { // foreach (Pupil pupil in PupilSort(temp, project, comparer)) // { // if (project.IsFull) // break; // if (remaining.Contains(pupil)) // { // project.Members.Add(pupil); // pupil.Project = project; // remaining.Remove(pupil); // grantedChoices[choice]++; // } // } // } //} bool generalActivity; do { Parallel.ForEach(projects, (Project project) => { for (int i = 0; i < choiceCount; i++) { project.Interested[i] = new List <Pupil>(project.Interested[i].OrderBy(pupil => pupil, comparer)); } }); //bool generalActivity; //do //{ generalActivity = false; for (int choice = 0; choice < choiceCount; choice++) { bool activity; do { activity = false; foreach (var project in projects) //Parallel.ForEach(projects, (Project project) => { int[] indicies = new int[choiceCount]; while (true) { List <Pupil> buffer = project.Interested[choice]; if (++indicies[0] > buffer.Count) { break; } Pupil pupil = buffer[buffer.Count - indicies[0]]; if (!remaining.Contains(pupil)) { buffer.RemoveAt(buffer.Count - 1); break; } int space = project.FreeSpace; for (int i = choice + 1; i < choiceCount; i++) { buffer = project.Interested[i]; while (buffer.Count > indicies[i] && pupil.GetPriority(remaining.Count, preferation) * (1 + 1 * i - 0 * i) < buffer[buffer.Count - 1 - indicies[i]].GetPriority(remaining.Count, preferation)) { indicies[i]++; } //space -= Math.Max(0, (int)(indicies[i] - 1 * i));// / Math.Round(Math.Pow(10, i))); space -= indicies[i]; } buffer = project.Interested[choice]; if (space > 0) { buffer.RemoveAt(buffer.Count - 1); project.Members.Add(pupil); pupil.Project = project; lock (remaining) { remaining.Remove(pupil); } granted[choice]++; activity = true; } else { break; } } }//); if (!generalActivity && activity) { generalActivity = true; } }while (activity); } }while (generalActivity); grantedChoices = granted; return(remaining); //if (remaining.Count > 0) // return false; //foreach (var project in projects.Values) //{ // if (project.IsUnderpopulated) // return false; //} //return true; }
public CommandStoreOptions() { m_CommandSourceTypes = new List <Type>(); m_CommandSources = new List <ICommandSource>(); m_PriorityComparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); }
public virtual async Task EmitAsync(IOpenModComponent component, object?sender, IEvent @event, EventExecutedCallback?callback = null) { if (component == null) { throw new ArgumentNullException(nameof(component)); } if (@event == null) { throw new ArgumentNullException(nameof(@event)); } if (!component.IsComponentAlive) { m_Logger.LogDebug($"EmitAsync called by {component.OpenModComponentId} for {@event.GetType().Name} but the component is not alive."); return; } var eventTypes = new List <Type>(); var currentType = @event.GetType(); while (currentType != null && typeof(IEvent).IsAssignableFrom(currentType)) { eventTypes.Add(currentType); currentType = currentType.BaseType; } eventTypes.AddRange(@event.GetType().GetInterfaces().Where(d => typeof(IEvent).IsAssignableFrom(d))); foreach (var eventType in eventTypes.Except(s_OmittedTypes)) { string eventName = GetEventName(eventType); m_Logger.LogTrace($"Emitting event: {eventName}"); var eventSubscriptions = m_EventSubscriptions .Where(c => (c.EventType != null && c.EventType == eventType) || (eventName.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) && c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive)) .ToList(); if (eventSubscriptions.Count == 0) { m_Logger.LogTrace($"No event subscriptions found for: {eventName}"); continue; } var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst); eventSubscriptions.Sort((a, b) => comparer.Compare( (Priority)a.EventListenerAttribute.Priority, (Priority)b.EventListenerAttribute.Priority) ); foreach (var group in eventSubscriptions.GroupBy(e => e.Scope)) { // Creates a new scope for the event. This is needed for scoped services so they share the same service instance // on each events. AutofacWebRequest makes it emulate a request for proper scopes. This tag is hardcoded by AutoFac. // Without this tag, services with the "Scope" lifetime will cause "DependencyResolutionException: // No scope with a Tag matching 'AutofacWebRequest' (...)". // // If you are here because of the following error: "System.ObjectDisposedException: Instances cannot // be resolved and nested lifetimes cannot be created from this LifetimeScope as it (or one of its parent scopes) // has already been disposed." It means you injected a service to an IEventHandler // that used the service *after* the event has finished (e.g. in a Task or by storing it somewhere). await using var newScope = group.Key.BeginLifetimeScopeEx("AutofacWebRequest"); foreach (var subscription in group) { var cancellableEvent = @event as ICancellableEvent; if (cancellableEvent != null && cancellableEvent.IsCancelled && !subscription.EventListenerAttribute.IgnoreCancelled) { continue; } var wasCancelled = false; if (cancellableEvent != null) { wasCancelled = cancellableEvent.IsCancelled; } var serviceProvider = newScope.Resolve <IServiceProvider>(); try { await subscription.Callback.Invoke(serviceProvider, sender, @event); // Ensure monitor event listeners can't cancel or uncancel events if (cancellableEvent != null && subscription.EventListenerAttribute.Priority == EventListenerPriority.Monitor) { if (cancellableEvent.IsCancelled != wasCancelled) { cancellableEvent.IsCancelled = wasCancelled; m_Logger.LogWarning( $"{((IOpenModComponent)@subscription.Owner.Target).OpenModComponentId} changed {@eventName} cancellation status with Monitor priority which is not permitted."); } } } catch (Exception ex) { m_Logger.LogError(ex, $"Exception occured during event {@eventName}"); } } } m_Logger.LogTrace($"{eventName}: Finished."); } callback?.Invoke(@event); }
/// <summary> /// sort list using name of original file /// </summary> public void SortByName() { PriorityComparer pc = new PriorityComparer(PrioritySortField.NAME); this.streamList.Sort(pc); }
public virtual async Task EmitAsync(IOpenModComponent component, object sender, IEvent @event, EventExecutedCallback callback = null) { if (!component.IsComponentAlive) { return; } var eventTypes = new List <Type>(); var currentType = @event.GetType(); while (currentType != null && typeof(IEvent).IsAssignableFrom(currentType)) { eventTypes.Add(currentType); currentType = currentType.BaseType; } eventTypes.AddRange(@event.GetType().GetInterfaces().Where(d => typeof(IEvent).IsAssignableFrom(d))); foreach (var eventType in eventTypes.Except(s_OmittedTypes)) { string eventName = GetEventName(eventType); m_Logger.LogTrace($"Emitting event: {eventName}"); var eventSubscriptions = m_EventSubscriptions .Where(c => (c.EventType != null && c.EventType == eventType) || (eventName.Equals(c.EventName, StringComparison.OrdinalIgnoreCase) && c.Owner.IsAlive && ((IOpenModComponent)c.Owner.Target).IsComponentAlive)) .ToList(); if (eventSubscriptions.Count == 0) { continue; } var comparer = new PriorityComparer(PriortyComparisonMode.LowestFirst); eventSubscriptions.Sort((a, b) => comparer.Compare( (Priority)a.EventListenerAttribute.Priority, (Priority)b.EventListenerAttribute.Priority) ); foreach (var group in eventSubscriptions.GroupBy(e => e.Scope)) { await using var newScope = group.Key.BeginLifetimeScope("AutofacWebRequest"); foreach (var subscription in group) { var cancellableEvent = @event as ICancellableEvent; if (cancellableEvent != null && cancellableEvent.IsCancelled && !subscription.EventListenerAttribute.IgnoreCancelled) { continue; } var wasCancelled = false; if (cancellableEvent != null) { wasCancelled = cancellableEvent.IsCancelled; } var serviceProvider = newScope.Resolve <IServiceProvider>(); try { await subscription.Callback.Invoke(serviceProvider, sender, @event); if (cancellableEvent != null && subscription.EventListenerAttribute.Priority == EventListenerPriority.Monitor) { if (cancellableEvent.IsCancelled != wasCancelled) { cancellableEvent.IsCancelled = wasCancelled; m_Logger.LogWarning( $"{((IOpenModComponent)@subscription.Owner.Target).OpenModComponentId} changed {@eventName} cancellation status with Monitor priority which is not permitted."); } } } catch (Exception ex) { m_Logger.LogError(ex, $"Exception occured during event {@eventName}"); } } } m_Logger.LogTrace($"{eventName}: Finished."); } callback?.Invoke(@event); }
public CommandStore(IOptions <CommandStoreOptions> options, IServiceProvider serviceProvider) { m_Comparer = new PriorityComparer(PriortyComparisonMode.HighestFirst); m_CommandSources = options.Value.CreateCommandSources(serviceProvider); }