internal static void UserInputLoop(IHub hub) { string userInput; while (!string.IsNullOrEmpty((userInput = Console.ReadLine()))) { if (userInput.Equals("pose", StringComparison.OrdinalIgnoreCase)) { foreach (var myo in hub.Myos) { Console.WriteLine("Myo {0} in pose {1}.", myo.Handle, myo.Pose); } } else if (userInput.Equals("arm", StringComparison.OrdinalIgnoreCase)) { foreach (var myo in hub.Myos) { Console.WriteLine("Myo {0} is on {1} arm.", myo.Handle, myo.Arm.ToString().ToLower()); } } else if (userInput.Equals("count", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("There are {0} Myo(s) connected.", hub.Myos.Count); } } }
public void ProcessTurn(IHub services) { var personService = services.Resolve<IPersonService>(); var gameClockService = services.Resolve<IGameClockService>(); foreach(var person in personService.People.Where(p => !personService.IsRetired(p))) { if (person.RetirementDate > gameClockService.CurrentDate) { continue; } var currentWorkHistory = person.WorkHistory.FirstOrDefault(wh => !wh.EndDate.HasValue); if(currentWorkHistory != null) { var employee = currentWorkHistory.Company.GetEmployee(person.Id); if(!employee.IsFounder) { currentWorkHistory.EndDate = gameClockService.CurrentDate; currentWorkHistory.EndingSalary = employee.Salary; } } } }
public VoipChannel(IHub hub, CoreDispatcher dispatcher, VoipContext context) { _hub = hub; Dispatcher = dispatcher; Context = context; }
public HubInvokerContext(IHub hub, StateChangeTracker tracker, MethodDescriptor methodDescriptor, IList<object> args) { Hub = hub; MethodDescriptor = methodDescriptor; Args = args; StateTracker = tracker; }
public HubInvokerContext(IHub hub, TrackingDictionary state, MethodDescriptor methodDescriptor, object[] args) { Hub = hub; MethodDescriptor = methodDescriptor; Args = args; State = state; }
protected JiraServiceViewModel(IHub messageHub) { MessageHub = messageHub; SettingsCommand = new DelegateCommand(OpenSettings); SearchCommand = new DelegateCommand(ShowSearchPane); }
public void ProcessTurn(IHub services) { var companyService = services.Resolve<ICompanyService>(); var gameClockService = services.Resolve<IGameClockService>(); foreach(var company in companyService.Companies) { foreach(var project in company.Projects) { if (IsProjectComplete(project)) { CompleteProject(company, project); companyService.ProcessTransaction(company, TransactionType.Project, project.Value, $"Completed {project.Definition.Name} project."); } else { var deadline = project.ExtensionDeadline.HasValue ? project.ExtensionDeadline.Value : project.Deadline; if (gameClockService.CurrentDate >= deadline) { FailProject(company, project); } } } } }
public SearchResultsPageViewModel(ApplicationSettings settings, INavigationService navigationService, IImageSearchService imageSearchService, IHub hub, IAccelerometer accelerometer, IStatusService statusService, IShareDataRequestedPump shareMessagePump) { _settings = settings; _navigationService = navigationService; _imageSearchService = imageSearchService; _hub = hub; _accelerometer = accelerometer; _statusService = statusService; HomeCommand = _navigationService.GoBackCommand; ViewDetailsCommand = new DelegateCommand(ViewDetails, () => SelectedImage != null); LoadMoreCommand = new AsyncDelegateCommand(LoadMore); ThumbnailViewCommand = new DelegateCommand(ThumbnailView); ListViewCommand = new DelegateCommand(ListView); SplitViewCommand = new DelegateCommand(SplitView); SettingsCommand = new DelegateCommand(Settings); AddImages(_settings.SelectedInstance.Images); shareMessagePump.DataToShare = _settings.SelectedInstance.QueryLink; _statusService.Title = _settings.SelectedInstance.Query; _accelerometer.Shaken += accelerometer_Shaken; _navigationService.Navigating += NavigatingFrom; UpdateCurrentView(CurrentView); _hub.Send(new UpdateTileImageCollectionMessage(_settings.SelectedInstance)); }
protected override bool OnBeforeReconnect(IHub hub) { SignalRContext.ConnectionIdToSessionId[hub.Context.ConnectionId] = hub.GetSessionId(); Storage session = hub.GetSession(); session[InternalSessionKeys.DisconnectTimeKey] = null; return base.OnBeforeReconnect(hub); }
public override Task ActivateAsync() { hub = HubGateway.GetLocalHub(); buffer = new Queue<Notification>(); RegisterTimer(Flush, null, flushPeriod, flushPeriod); return TaskDone.Done; }
public AndroidMain() { _graphics = new GraphicsDeviceManager(this); _services = new Hub(); Content.RootDirectory = "Content"; }
protected override bool OnBeforeDisconnect(IHub hub, bool stopCalled) { if (stopCalled) { hub.ClearSession(); } return base.OnBeforeDisconnect(hub, stopCalled); }
public IssueViewModel(IHub messageHub, ISettings settings, IDialogService dialogService, IJiraService service) : base(messageHub) { _dialogService = dialogService; _settings = (ApplicationSettings)settings; _service = service; LoadIssueComments(); }
protected ServiceCore(IHub services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } _services = services; }
protected override void OnAfterDisconnect(IHub hub, bool stopCalled) { string sessionId; SignalRContext.ConnectionIdToSessionId.TryRemove(hub.Context.ConnectionId, out sessionId); Storage session = hub.GetSession(); session[InternalSessionKeys.DisconnectTimeKey] = DateTime.Now; base.OnAfterDisconnect(hub, stopCalled); }
public void ProcessTurn(IHub services) { var companyService = services.Resolve<ICompanyService>(); foreach(var company in companyService.Companies) { var accumulations = new Dictionary<int, decimal>(); foreach (var employee in company.Employees) { var allocations = company.Allocations.Where(a => a.Employee == employee); var skillValues = new Dictionary<int, decimal>(); var remainingSkillValues = new Dictionary<int, decimal>(); foreach (var skill in employee.Person.Skills) { var skillValue = CalculateEmployeeSkillValue(employee, skill); skillValues.Add(skill.SkillDefinition.Id, skillValue); remainingSkillValues.Add(skill.SkillDefinition.Id, skillValue); } foreach (var allocation in allocations) { foreach (var requirement in allocation.Project.Requirements) { if (skillValues.ContainsKey(requirement.SkillDefinition.Id)) { var value = allocation.Percent * skillValues[requirement.SkillDefinition.Id]; requirement.CurrentValue += value; remainingSkillValues[requirement.SkillDefinition.Id] -= value; } } } foreach (var skill in remainingSkillValues) { if (accumulations.ContainsKey(skill.Key)) { accumulations[skill.Key] += skill.Value; } else { accumulations.Add(skill.Key, skill.Value); } } } ProcessActionAccumulations(company, accumulations); } }
private static void UpdateMeetingStatusToClients(IHub hub) { var meetingStati = BuildMeetingsStatus(); Debug.WriteLine("Meeting Status Update:"); foreach (var m in meetingStati) { Debug.WriteLine("Meeting {0} [HAsAgent:{1}] [HasClient:{2}] [MeetingStarted:{3}]", m.MeetingId, m.AgentJoined, m.ClientJoined, m.MeetingStarted); } hub.Clients.All.meetingStatusUpdated(meetingStati); }
public override ActionExecutionInformation CanPerformEvent(Company company, IActionData eventData, IHub services) { var companyService = services.Resolve<ICompanyService>(); if (!companyService.CanPerformAction(company, Type)) { return new ActionExecutionInformation(false, $"Company {company.Id} cannot perform turn action {Type}.", company); } return new ActionExecutionInformation(true); }
public IssuesViewModel(IJiraService jiraService, IHub messageHub, ApplicationSettings settings, INavigationService navigationService) : base(messageHub) { NavigateToIssueCommand = new DelegateCommand(NavigateToIssue, () => SelectedIssue != null); SettingsCommand = new DelegateCommand(OpenSettings); _applicationSettings = settings; _navigationService = navigationService; _jiraService = jiraService; _applicationSettings.SelectedIssue = null; }
public ShellViewModel(AppName appName, ApplicationSettings settings, INavigationService navigationService, IHub hub) { _appName = appName; _settings = settings; _navigationService = navigationService; _hub = hub; Message = "Initializing..."; IsLoading = true; BackCommand = _navigationService.GoBackCommand; }
public OfferResponseReason? Evaluate(IHub services, Company company, Person person, decimal amount) { var personService = services.Resolve<IPersonService>(); var expectedCompensation = personService.CalculateCompensationValue(person); if(amount >= expectedCompensation) { return null; } return OfferResponseReason.OfferValue; }
public CredentialsViewModel(IHub messageHub, ApplicationSettings settings) { IsSaveEnabled = true; _settings = settings; _messageHub = messageHub; _serverUrl = settings.ServerUrl; _userName = settings.UserName; _password = settings.Password; SaveCredentialsCommand = new AsyncDelegateCommand(SaveCredentials); }
public FpsCounterState(IHub services) : base(services) { _previousTimeStamp = DateTime.Now; _text = new Text2D { IsVisible = true, Text = "EMPTY", Color = Color.Blue, Position = new Vector2(50, 50) }; }
public SearchHistoryPageViewModel(ApplicationSettings settings, INavigationService navigationService, IHub messageHub, IStatusService statusService) { _settings = settings; _navigationService = navigationService; _messageHub = messageHub; _statusService = statusService; _statusService.Title = "Searches"; _settings.SelectedInstance = null; SearchCommand = new DelegateCommand(Search); SettingsCommand = new DelegateCommand(Settings); SearchQueryCommand = new AsyncDelegateCommand<string>(SearchQuery); }
/// <summary> /// Initializes a new instance of the ProjectsViewModel class. /// </summary> public ProjectsViewModel(IHub messageHub, ApplicationSettings applicationSettings, IJiraService jiraService, INavigationService navigateService) : base(messageHub) { NavigateToProjectCommand = new DelegateCommand(NavigateToProject, () => SelectedItem != null); ReloadProjectsCommand = new DelegateCommand(LoadProjects); _applicationSettings = applicationSettings; _navigateService = navigateService; _jiraService = jiraService; LoadProjects(); }
public MyMyo(int sensors) { _channel = Channel.Create( ChannelDriver.Create(ChannelBridge.Create(), MyoErrorHandlerDriver.Create(MyoErrorHandlerBridge.Create()))); _hub = Hub.Create(_channel); _hub.MyoConnected += Hub_MyoConnected; _hub.MyoDisconnected += Hub_MyoDisconnected; _sensors = sensors; _pointPairs = new int[_sensors]; // start listening for Myo data _channel.StartListening(); }
public void ProcessTurn(IHub services) { var companyService = services.Resolve<ICompanyService>(); foreach(var company in companyService.Companies) { foreach(var employee in company.Employees) { if (!employee.IsFounder && employee.Salary != 0) { companyService.ProcessTransaction(company, TransactionType.Payroll, -employee.Salary, $"Paid {employee.Person.FirstName} {employee.Person.LastName} {employee.Salary:C}."); } } } }
public IEnumerable<IActionData> GenerateData(IHub services, Company company) { var actionData = new List<IActionData>(); var recruitAction = company.Actions.FirstOrDefault(a => a.Action.Id == (byte)ActionType.RecruitPerson); if (recruitAction.Count == 0) { return actionData; } var founder = company.Employees.FirstOrDefault(e => e.IsFounder); var configurationService = services.Resolve<IConfigurationService>(); var fastGrowth = configurationService.GetDecimalValue(ConfigurationKey.FastCompanyGrowthValue, ConfigurationFallbackValue.FastCompanyGrowthValue); var growthTarget = founder.Person.GetPersonalityValue(PersonalityAttributeId.DesiredCompanyGrowth); var growthImportance = founder.Person.GetPersonalityValue(PersonalityAttributeId.CompanyGrowthImportance); var targetNumberOfProspects = fastGrowth * growthTarget; var maxDifferential = fastGrowth * (1m - growthImportance); var differential = (int)(targetNumberOfProspects - company.Prospects.Count); if (differential <= maxDifferential) { return actionData; } var personService = services.Resolve<IPersonService>(); var recruitCount = recruitAction.Count; var recruitTargetCount = targetNumberOfProspects - maxDifferential; while (recruitCount-- > 0 && (company.Prospects.Count + actionData.Count) < recruitTargetCount) { var person = personService.GetUnemployedPerson(); actionData.Add(new RecruitPersonActionData(person.Id)); } return actionData; }
public void ProcessTurn(IHub services) { var companyService = services.Resolve<ICompanyService>(); foreach(var company in companyService.Companies) { foreach (var perk in company.Perks) { var cost = perk.Count * perk.Perk.RecurringCost; var message = $"Charged {cost:C} for {perk.Count} {perk.Perk.Name} perks."; companyService.ProcessTransaction(company, TransactionType.Perk, -cost, message); } } }
public VoipContext(IHub hub, CoreDispatcher dispatcher, Func<IVideoRenderHelper> renderResolver, IVoipCoordinator coordinator) { _hub = hub; _dispatcher = dispatcher; _renderResolver = renderResolver; _localSettings = ApplicationData.Current.LocalSettings; VoipCoordinator = coordinator; var idleState = new VoipState_Idle(); SwitchState(idleState).Wait(); ResetRenderers(); }
internal static Task Disconnect(IHub hub) { return(hub.OnDisconnected()); }
private Task InvokeHubPipeline(IRequest request, string connectionId, string data, HubRequest hubRequest, IJsonValue[] parameterValues, MethodDescriptor methodDescriptor, TrackingDictionary state, IHub hub) { var args = _binder.ResolveMethodParameters(methodDescriptor, parameterValues); var context = new HubInvokerContext(hub, state, methodDescriptor, args); // Invoke the pipeline return(_pipelineInvoker.Invoke(context) .ContinueWith(task => { if (task.IsFaulted) { return ProcessResponse(state, null, hubRequest, task.Exception); } else { return ProcessResponse(state, task.Result, hubRequest, null); } }) .FastUnwrap()); }
internal static IEnumerable <string> RejoiningGroups(IHub hub, IEnumerable <string> groups) { return(hub.RejoiningGroups(groups)); }
public CreateQuestionnaireHandler(ISave <Questionnaire> questionnaireSaver, IHub hub) { _questionnaireSaver = questionnaireSaver; _hub = hub; }
public object Execute(IHub hub, object[] parameters) { return(_executor(hub, parameters)); }
/// <summary> /// Starts a transaction. /// </summary> public static ITransaction StartTransaction(this IHub hub, ITransactionContext context) => hub.StartTransaction(context, new Dictionary <string, object?>());
public static void UnlockScope(this IHub hub) => hub.ConfigureScope(c => c.Locked = false);
// For testing internal static void UseHub(IHub hub) => _hub = hub;
public HubAdapterTests() { Hub = Substitute.For <IHub>(); _ = SentrySdk.UseHub(Hub); }
public SentrySqlListener(IHub hub, SentryOptions options) { _hub = hub; _options = options; }
public Task Disconnect(IHub hub) { return(Pipeline.Disconnect(hub)); }
public Task Reconnect(IHub hub) { return(Pipeline.Reconnect(hub)); }
/// <summary> /// Pushes a new scope while locking it which stop new scope creation. /// </summary> public static IDisposable PushAndLockScope(this IHub hub) => new LockedScope(hub);
/// <summary> /// Initializes an instance of <see cref="SentryHttpMessageHandler"/>. /// </summary> public SentryHttpMessageHandler(IHub hub) { _hub = hub; }
public static void LockScope(this IHub hub) => hub.ConfigureScope(c => c.Locked = true);
public CreateUserHandler(ISave <User> userSaver, IHasher hasher, IHub hub) { _userSaver = userSaver; _hub = hub; _hasher = hasher; }
public LockedScope(IHub hub) { _scope = hub.PushScope(); hub.LockScope(); }
public SearchUtils(IHub hub) { _hub = hub; }
/// <summary> /// Initializes an instance of <see cref="SentryHttpMessageHandler"/>. /// </summary> public SentryHttpMessageHandler(HttpMessageHandler innerHandler, IHub hub) : this(hub) { InnerHandler = innerHandler; }
protected virtual bool OnBeforeDisconnect(IHub hub) { return(true); }
protected virtual void OnAfterDisconnect(IHub hub) { }
public HomeController(IHub hub) { _hub = hub; }
protected override Task OnReceivedAsync(string connectionId, string data) { var hubRequest = _serializer.Deserialize <HubRequest>(data); // Create the hub IHub hub = _hubFactory.CreateHub(hubRequest.Hub); // Deserialize the parameter name value pairs so we can match it up with the method's parameters var parameters = hubRequest.Data; // Resolve the action ActionInfo actionInfo = _actionResolver.ResolveAction(hub.GetType(), hubRequest.Action, parameters); if (actionInfo == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "'{0}' could not be resolved.", hubRequest.Action)); } string hubName = hub.GetType().FullName; var state = new TrackingDictionary(hubRequest.State); hub.Context = new HubContext(connectionId, _cookies, _user); hub.Caller = new SignalAgent(Connection, connectionId, hubName, state); var agent = new ClientAgent(Connection, hubName); hub.Agent = agent; hub.GroupManager = agent; try { // Execute the method object result = actionInfo.Method.Invoke(hub, actionInfo.Arguments); Type returnType = result != null?result.GetType() : actionInfo.Method.ReturnType; if (typeof(Task).IsAssignableFrom(returnType)) { var task = (Task)result; if (!returnType.IsGenericType) { return(task.ContinueWith(t => ProcessResult(state, null, hubRequest, t.Exception))); } else { // Get the <T> in Task<T> Type resultType = returnType.GetGenericArguments().Single(); // Get the correct ContinueWith overload var continueWith = (from m in task.GetType().GetMethods() let methodParameters = m.GetParameters() where m.Name.Equals("ContinueWith", StringComparison.OrdinalIgnoreCase) && methodParameters.Length == 1 let parameter = methodParameters[0] where parameter.ParameterType.IsGenericType && typeof(Action <>) == parameter.ParameterType.GetGenericTypeDefinition() select new { Method = m, ArgType = parameter.ParameterType.GetGenericArguments()[0] }) .FirstOrDefault(); var taskParameter = Expression.Parameter(continueWith.ArgType); var processResultMethod = typeof(HubDispatcher).GetMethod("ProcessResult", BindingFlags.NonPublic | BindingFlags.Instance); var taskResult = Expression.Property(taskParameter, "Result"); var taskException = Expression.Property(taskParameter, "Exception"); var body = Expression.Call(Expression.Constant(this), processResultMethod, Expression.Constant(state), Expression.Convert(taskResult, typeof(object)), Expression.Constant(hubRequest), Expression.Convert(taskException, typeof(Exception))); var lambda = Expression.Lambda(body, taskParameter); var call = Expression.Call(Expression.Constant(task, continueWith.ArgType), continueWith.Method, lambda); return(Expression.Lambda <Func <Task> >(call).Compile()()); } } else { ProcessResult(state, result, hubRequest, null); } } catch (TargetInvocationException e) { ProcessResult(state, null, hubRequest, e); } return(base.OnReceivedAsync(connectionId, data)); }
public DisposeHandle(IHub hub) => _localHub = hub;
public static void ConfigureGlobalExceptionHandler(this IApplicationBuilder app, IHub sentryHub) { app.UseExceptionHandler(appError => { appError.Run(async context => { var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature?.Error != null) { context.Response.ContentType = "application/json"; ErrorModel errorModel; switch (contextFeature.Error) { case ValidationException validationException: context.Response.StatusCode = (int)validationException.StatusCode; errorModel = new ErrorModel <IEnumerable <string> > { Message = contextFeature.Error.Message, ErrorCode = validationException.ErrorCode, StatusCode = (int)validationException.StatusCode, Data = validationException.Errors }; break; case ErtisException ertisException: context.Response.StatusCode = (int)ertisException.StatusCode; errorModel = new ErrorModel { Message = contextFeature.Error.Message, ErrorCode = ertisException.ErrorCode, StatusCode = (int)ertisException.StatusCode }; break; case HttpStatusCodeException httpStatusCodeException: context.Response.StatusCode = (int)httpStatusCodeException.StatusCode; errorModel = new ErrorModel { Message = contextFeature.Error.Message, ErrorCode = httpStatusCodeException.HelpLink, StatusCode = (int)httpStatusCodeException.StatusCode }; break; default: context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; errorModel = new ErrorModel { Message = contextFeature.Error.Message, ErrorCode = "UndhandledExceptionError", StatusCode = 500 }; break; } sentryHub?.CaptureException(contextFeature.Error); var json = Newtonsoft.Json.JsonConvert.SerializeObject(errorModel); await context.Response.WriteAsync(json); } }); }); }
public ExceptionMiddlewareTests() { _loggerFactory = new NullLoggerFactory(); _hub = Substitute.For <IHub>(); }
internal static Task Disconnect(IHub hub, bool stopCalled) { return(hub.OnDisconnected(stopCalled)); }
internal static Task Reconnect(IHub hub) { return(hub.OnReconnected()); }
public Task Connect(IHub hub) { return(Pipeline.Connect(hub)); }
public AnswerController(IAnswerRepository repository, IHub dashboardHub) { _dashboardHub = dashboardHub; _repository = repository; }