コード例 #1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="del">SignalDelegate listener to add.</param>
        /// <typeparam name="T">Must inherit from Signal class.</typeparam>
        public void AddListener <T>(SignalDelegate <T> del) where T : Signal
        {
            if (!delegateCache.ContainsKey(del))
            {
                delegateCache[del] = new List <DelegatePair>();
            }

            var delegateType = typeof(T);

            if (!delegates.ContainsKey(delegateType))
            {
                delegates[delegateType] = new List <SignalDelegate>();
            }

            //Do not add delegate if it is already subscribed
            SignalDelegate internalDelegate;

            if (TryGetInternalDelegate(delegateType, del, out internalDelegate))
            {
                return;
            }

            // Create a new non-generic delegate which calls our generic one.
            // This is the delegate we actually invoke.
            internalDelegate = e => del((T)e);
            var delegatePair = new DelegatePair
            {
                Type     = delegateType,
                Delegate = internalDelegate
            };

            delegateCache[del].Add(delegatePair);
            delegates[delegateType].Add(internalDelegate);
        }
コード例 #2
0
        public void WhenDispatchGuessResultSignal_UpdateGallowVisibilityViewModel()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <GuessResultSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var isEnabledObserver1 = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsGallowPartVisible.Clear();
            var gallowImageProperty1 = _inGameViewModel.SubscribeGallowImage();

            gallowImageProperty1.Subscribe(isEnabledObserver1);
            isEnabledObserver1.ClearReceivedCalls();
            var isEnabledObserver2   = Substitute.For <IObserver <bool> >();
            var gallowImageProperty2 = _inGameViewModel.SubscribeGallowImage();

            gallowImageProperty2.Subscribe(isEnabledObserver2);
            isEnabledObserver2.ClearReceivedCalls();
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            callback(new GuessResultSignal(_letterToGuess, "word", true));
            callback(new GuessResultSignal(_letterToGuess, "word", false));
            callback(new GuessResultSignal(_letterToGuess, "word", true));
            callback(new GuessResultSignal(_letterToGuess, "word", false));
            callback(new GuessResultSignal(_letterToGuess, "word", true));

            Received.InOrder(() =>
            {
                isEnabledObserver1.Received().OnNext(true);
                isEnabledObserver2.Received().OnNext(true);
            });
        }
コード例 #3
0
 /// <summary>
 /// Add a unique listener to the signal.
 /// </summary>
 public void AddListener(SignalDelegate listener)
 {
     if (SendSignal != null && SendSignal.GetInvocationList().Contains(listener))
     {
         Debug.LogWarning(string.Format("Signal already has registered the listener {0}", listener.Method.Name));
     }
     SendSignal += listener;
 }
コード例 #4
0
        public void Listen(SignalDelegate <TMessage> listener)
        {
            if (listener == null)
            {
                throw new ArgumentNullException(nameof(listener));
            }

            _listeners.Add(new WeakReference(listener));
        }
コード例 #5
0
        public void Unlisten(SignalDelegate <TMessage> listener)
        {
            if (listener == null)
            {
                throw new ArgumentNullException(nameof(listener));
            }

            _listeners.RemoveAll(t => t.Target == listener);
        }
コード例 #6
0
        private async void DrainDeferredEvents(SignalDelegate signal, CancellationToken token)
        {
            EventData data;

            while (_deferredEvents.TryGetEvent(out data) && !token.IsCancellationRequested)
            {
                await signal(data.Id, token, () => data);
            }
        }
コード例 #7
0
        public void Unsubscribe <T>(SignalDelegate callback) where T : ISignal
        {
            var type = typeof(T);

            if (_events.ContainsKey(type))
            {
                _events[type] -= callback;
            }
        }
コード例 #8
0
ファイル: Signal.cs プロジェクト: johans2/Runner
 /// <summary>
 /// Add a unique listener to the signal.
 /// </summary>
 public void AddListener(SignalDelegate listener)
 {
     if (SendSignal == null)
     {
         SendSignal += listener;
     }
     else if (!SendSignal.GetInvocationList().Contains(listener))
     {
         SendSignal += listener;
     }
 }
コード例 #9
0
        public void Subscribe <T>(SignalDelegate callback) where T : ISignal
        {
            var type = typeof(T);

            if (!_events.ContainsKey(type))
            {
                _events.Add(type, null);
            }

            _events[type] += callback;
        }
コード例 #10
0
        public void Unsubscribe <T>(SignalDelegate <T> callback) where T : ISignal
        {
            Delegate strippedDelegate = Delegate.Remove(GetDelegate <T>(), callback);

            if (strippedDelegate == null)
            {
                subscriptions.Remove(typeof(T));
            }
            else
            {
                subscriptions[typeof(T)] = strippedDelegate;
            }
        }
コード例 #11
0
        internal static void MakeRouters(IApplicationBuilder app, KraftGlobalConfigurationSettings kraftGlobalConfigurationSettings)
        {
            RouteHandler routesHandler;
            ToolSettings tool = GetTool(kraftGlobalConfigurationSettings, "recorder"); //////////////////////////////Recorder/////////////////////////////

            if (tool != null && tool.Enabled)                                          //Recorder enabled from configuration
            {
                kraftGlobalConfigurationSettings.GeneralSettings.ToolsSettings.RequestRecorder.IsEnabled = tool.Enabled;
                routesHandler = new RouteHandler(RecorderDelegate.ExecutionDelegate(app, kraftGlobalConfigurationSettings));

                RouteBuilder routesBuilder = new RouteBuilder(app, routesHandler);

                //we expect the routing to be like this:
                //domain.com/recorder/0|1|2?lang=de
                routesBuilder.MapRoute(
                    name: "recorder",
                    template: tool.Url,
                    defaults: null,
                    constraints: null,
                    dataTokens: new { key = "recorder" }
                    );
                app.UseRouter(routesBuilder.Build());
            }
            tool = GetTool(kraftGlobalConfigurationSettings, "signals"); //////////////////////////////Signals/////////////////////////////
            if (tool != null && tool.Enabled)                            //Signals enabled from configuration
            {
                routesHandler = new RouteHandler(SignalDelegate.ExecutionDelegate(app, kraftGlobalConfigurationSettings));

                RouteBuilder routesBuilder = new RouteBuilder(app, routesHandler);

                //we expect the routing to be like this:
                //domain.com/signals/0|1|2?lang=de
                routesBuilder.MapRoute(
                    name: "signals",
                    template: tool.Url,
                    defaults: null,
                    constraints: null,
                    dataTokens: new { key = "signals" }
                    );
                app.UseRouter(routesBuilder.Build());
            }
            //tool = GetTool(kraftGlobalConfigurationSettings, "errors");//////////////////////////////Errors/////////////////////////////
            //if (tool != null && tool.Enabled)//Errors enabled from configuration
            //{
            //}
            tool = GetTool(kraftGlobalConfigurationSettings, "profiler"); //////////////////////////////Profiler/////////////////////////////
            if (tool != null && tool.Enabled)                             //Profiler enabled from configuration
            {
                app.UseBindKraftProfiler();
            }
        }
コード例 #12
0
        public void WhenDispatchGuessResultSignal_UpdateKeyButtonViewModel(bool isCorrect)
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <GuessResultSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            callback(new GuessResultSignal(_letterToGuess, "word", isCorrect));

            _colorObserver.Received().OnNext(isCorrect ? InGameViewModel.CorrectColor : InGameViewModel.IncorrectColor);
            _isKetEnabledObserver.Received().OnNext(false);
        }
コード例 #13
0
        private async void DrainMessages(SignalDelegate signal, CancellationToken token)
        {
            string message;

            while (_warningMessages.TryDequeue(out message) && !token.IsCancellationRequested)
            {
                await signal(Events.Warning, token, () => EventHelper.CreateLogEvent(message));
            }

            while (_debugMessages.TryDequeue(out message) && !token.IsCancellationRequested)
            {
                await signal(Events.Debug, token, () => EventHelper.CreateLogEvent(message));
            }
        }
コード例 #14
0
ファイル: EventHelper.cs プロジェクト: zz562/azure-powershell
        /// <summary>
        /// Print event details to the provided stream
        /// </summary>
        /// <param name="getEventData">The event data to print</param>
        /// <param name="signal">The delegate for signaling events to the runtime</param>
        /// <param name="token">The cancellation token for the request</param>
        /// <param name="streamName">The name of the stream to print data to</param>
        /// <param name="eventName">The name of the event to be printed</param>
        public static async void Print(this GetEventData getEventData, SignalDelegate signal, CancellationToken token, string streamName, string eventName)
        {
            var eventDisplayName = SplitPascalCase(eventName).ToUpperInvariant();
            var data             = EventDataConverter.ConvertFrom(getEventData()); // also, we manually use our TypeConverter to return an appropriate type

            if (data.Id != "Verbose" && data.Id != "Warning" && data.Id != "Debug" && data.Id != "Information" && data.Id != "Error")
            {
                await signal(streamName, token, () => EventHelper.CreateLogEvent($"{eventDisplayName} The contents are '{data?.Id}' and '{data?.Message}'"));

                if (data != null)
                {
                    await signal(streamName, token, () => EventHelper.CreateLogEvent($"{eventDisplayName} Parameter: '{data.Parameter}'\n{eventDisplayName} RequestMessage '{data.RequestMessage}'\n{eventDisplayName} Response: '{data.ResponseMessage}'\n{eventDisplayName} Value: '{data.Value}'"));
                    await signal(streamName, token, () => EventHelper.CreateLogEvent($"{eventDisplayName} ExtendedData Type: '{data.ExtendedData?.GetType()}'\n{eventDisplayName} ExtendedData '{data.ExtendedData}'"));
                }
            }
        }
コード例 #15
0
        public void WhenDispatchNewWordSignal_UpdateTheVisibilityInViewModel()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <NewWordSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var observer = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsVisible.Subscribe(observer);
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            callback(new NewWordSignal("word"));

            observer.Received().OnNext(true);
        }
コード例 #16
0
        public void WhenDispatchNewWordSignal_UpdateTheWordInViewModel()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <NewWordSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var wordObserver = Substitute.For <IObserver <string> >();

            _inGameViewModel.CurrentWord.Subscribe(wordObserver);
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            callback(new NewWordSignal("word"));

            wordObserver.Received().OnNext("w o r d");
        }
コード例 #17
0
        public void WhenDispatchNewWordSignal_UpdateTheViewModel()
        {
            var            mainMenuViewModel      = Substitute.For <MainMenuViewModel>();
            var            eventDispatcherService = Substitute.For <IEventDispatcherService>();
            SignalDelegate callback = null;

            eventDispatcherService
            .When(service => service.Subscribe <NewWordSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var mainMenuPresenter = new MainMenuPresenter(mainMenuViewModel, eventDispatcherService);
            var observer          = Substitute.For <IObserver <bool> >();

            mainMenuViewModel.IsVisible.Subscribe(observer);

            callback(new NewWordSignal("word"));

            observer.Received().OnNext(false);
        }
コード例 #18
0
        public void WhenDispatchUpdateLoadingScreenSignal_UpdateTheViewModel()
        {
            var            loadingViewModel       = Substitute.For <LoadingViewModel>();
            var            eventDispatcherService = Substitute.For <IEventDispatcherService>();
            SignalDelegate callback = null;

            eventDispatcherService
            .When(service => service.Subscribe <UpdateLoadingScreenSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var loadingPresenter = new LoadingPresenter(loadingViewModel, eventDispatcherService);
            var observer         = Substitute.For <IObserver <bool> >();

            loadingViewModel.IsVisible.Subscribe(observer);

            callback(new UpdateLoadingScreenSignal(true));

            observer.Received().OnNext(false);
        }
コード例 #19
0
        private bool TryGetInternalDelegate(Type type, Delegate del, out SignalDelegate internalDelegate)
        {
            internalDelegate = null;
            if (!delegateCache.ContainsKey(del))
            {
                return(false);
            }

            for (var i = 0; i < delegateCache[del].Count; i++)
            {
                var pair = delegateCache[del][i];
                if (pair.Type == type)
                {
                    internalDelegate = pair.Delegate;
                    return(true);
                }
            }

            return(false);
        }
コード例 #20
0
        public void WhenDispatchRestartGameSignal_RestartKeyboard()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <RestartGameSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            _keyButtonViewModel.Color.Value     = "";
            _keyButtonViewModel.IsEnabled.Value = false;
            _colorObserver.ClearReceivedCalls();
            _isKetEnabledObserver.ClearReceivedCalls();

            Assert.AreNotEqual(InGameViewModel.DefaultColor, _keyButtonViewModel.Color.Value);
            Assert.AreNotEqual(true, _keyButtonViewModel.IsEnabled.Value);
            callback(new RestartGameSignal());

            _colorObserver.Received().OnNext(InGameViewModel.DefaultColor);
            _isKetEnabledObserver.Received().OnNext(true);
        }
コード例 #21
0
        /// <summary>
        /// Remove a listener from an signal type.
        /// </summary>
        /// <param name="del">SignalDelegate listener to remove.</param>
        /// <typeparam name="T">Must inherit from Signal class.</typeparam>
        public void RemoveListener <T>(SignalDelegate <T> del) where T : Signal
        {
            var            delegateType = typeof(T);
            SignalDelegate internalDelegate;

            if (!TryGetInternalDelegate(delegateType, del, out internalDelegate))
            {
                return;
            }

            if (delegates.ContainsKey(delegateType))
            {
                var i = delegates[delegateType].IndexOf(internalDelegate);
                if (i >= 0)
                {
                    delegates[delegateType][i] = null;
                }
                RemoveInternalDelegate(delegateType, del);

                RemoveAllNull(delegateType);
            }
        }
コード例 #22
0
        public void WhenDispatchRestartGameSignal_RestartEndGameVisibilityInViewModel()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <RestartGameSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var isEndGameVisibleObserver = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsEndGameVisible.Subscribe(isEndGameVisibleObserver);
            var isGameOverVisibleObserver = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsGameOverVisible.Subscribe(isGameOverVisibleObserver);
            var isVictoryVisibleObserver = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsVictoryVisible.Subscribe(isVictoryVisibleObserver);
            var inGamePresenter = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            callback(new RestartGameSignal());

            isEndGameVisibleObserver.Received().OnNext(false);
            isGameOverVisibleObserver.Received().OnNext(false);
            isVictoryVisibleObserver.Received().OnNext(false);
        }
コード例 #23
0
        public void WhenDispatchRestartGameSignal_RestartGallow()
        {
            SignalDelegate callback = null;

            _eventDispatcherService
            .When(service => service.Subscribe <RestartGameSignal>(Arg.Any <SignalDelegate>()))
            .Do(info => callback = info.Arg <SignalDelegate>());
            var isEnabledObserver = Substitute.For <IObserver <bool> >();

            _inGameViewModel.IsGallowPartVisible.Clear();
            var gallowImageProperty = _inGameViewModel.SubscribeGallowImage();
            var inGamePresenter     = new InGamePresenter(_inGameViewModel, _eventDispatcherService);

            gallowImageProperty.Subscribe(isEnabledObserver);
            gallowImageProperty.Value             = true;
            _inGameViewModel.NextGallowPartToShow = 2;

            Assert.AreNotEqual(0, _inGameViewModel.NextGallowPartToShow);
            Assert.IsTrue(gallowImageProperty.Value);
            callback(new RestartGameSignal());

            Assert.AreEqual(0, _inGameViewModel.NextGallowPartToShow);
            isEnabledObserver.Received().OnNext(false);
        }
コード例 #24
0
 public EventedEventWaitHandleList(SignalDelegate Signal)
 {
     this.Signal = Signal;
 }
コード例 #25
0
        /// <summary>
        /// Pipeline delegate to add a unique id header to an outgoing request
        /// </summary>
        /// <param name="request">The outgpoing request</param>
        /// <param name="token">The cancellation token</param>
        /// <param name="cancel">Additional cancellation action if the operation is cancelled</param>
        /// <param name="signal">Signal delegate for logging events</param>
        /// <param name="next">The next setp in the pipeline</param>
        /// <returns>Amended pipeline for retrieving a response</returns>
        public Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token, Action cancel, SignalDelegate signal, NextDelegate next)
        {
            var userAgents = new ProductInfoHeaderValue[] { new ProductInfoHeaderValue("AzurePowerShell", $"Az4.0.0-preview") };

            // add user agent haeaders

            foreach (var userAgent in userAgents)
            {
                request.Headers.UserAgent.Add(userAgent);
            }

            // continue with pipeline.
            return(next(request, token, cancel, signal));
        }
コード例 #26
0
        public static extern uint g_signal_connect_data(IntPtr obj, string name,
							     SignalDelegate cb, IntPtr data,
							     IntPtr p, int flags);
コード例 #27
0
        public Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken token, Action cancel, SignalDelegate signal, NextDelegate next)
        {
            request.Headers.Add("x-ms-client-request-id", processRecordId);
            request.Headers.Add("CommandName", invocationInfo?.InvocationName);
            request.Headers.Add("FullCommandName", invocationInfo?.MyCommand?.Name);
            request.Headers.Add("ParameterSetName", parameterSetName);

            // continue with pipeline.
            return(next(request, token, cancel, signal));
        }
コード例 #28
0
 public void Subscribe <T>(SignalDelegate <T> callback) where T : ISignal
 {
     subscriptions[typeof(T)] = Delegate.Combine(GetDelegate <T>(), callback);
 }
コード例 #29
0
        internal async Task OnBeforeCall(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, string processRecordId)
        {
            var data    = EventDataConverter.ConvertFrom(getEventData()); // also, we manually use our TypeConverter to return an appropriate type
            var request = data?.RequestMessage as HttpRequestMessage;

            if (request != null)
            {
                AzurePSQoSEvent      qos;
                IEnumerable <string> headerValues;
                if (_telemetry.TryGetValue(processRecordId, out qos))
                {
                    foreach (var headerName in ClientHeaders)
                    {
                        if (request.Headers.TryGetValues(headerName, out headerValues) && headerValues.Any())
                        {
                            qos.ClientRequestId = headerValues.First();
                            break;
                        }
                    }
                }

                /// Print formatted request message
                await signal(Events.Debug, cancellationToken,
                             () => EventHelper.CreateLogEvent(GeneralUtilities.GetLog(request)));
            }
        }
コード例 #30
0
        internal async Task OnCmdletEndProcessing(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, string processRecordId)
        {
            AzurePSQoSEvent qos;

            if (_telemetry.TryGetValue(processRecordId, out qos))
            {
                qos.IsSuccess = (qos.Exception == null);
                await signal(Events.Debug, cancellationToken,
                             () => EventHelper.CreateLogEvent($"[{id}]: Sending new QosEvent for command '{qos.CommandName}': {qos.ToString()}"));

                _telemetry.LogEvent(processRecordId);
                _previousEndTime = DateTimeOffset.Now;
            }
        }
コード例 #31
0
 internal async Task OnCmdletBeginProcessing(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, string processRecordId)
 {
     await signal(Events.Debug, cancellationToken,
                  () => EventHelper.CreateLogEvent($"[{id}]: Starting command"));
 }
コード例 #32
0
        internal async Task OnFinally(string id, CancellationToken cancellationToken, GetEventData getEventData, SignalDelegate signal, string processRecordId)
        {
            var data = EventDataConverter.ConvertFrom(getEventData());

            if (data?.ResponseMessage is HttpResponseMessage response)
            {
                AzurePSQoSEvent qos;
                if (_telemetry.TryGetValue(processRecordId, out qos))
                {
                    if (!response.IsSuccessStatusCode && qos.Exception == null)
                    {
                        // add "InternalException" as message because it is just for telemtry tracking.
                        AzPSCloudException ex = (response.StatusCode == HttpStatusCode.NotFound) ?
                                                new AzPSResourceNotFoundCloudException("InternalException") : new AzPSCloudException("InternalException");
                        try
                        {
                            string responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                            CloudError cloudError = SafeJsonConvert.DeserializeObject <CloudError>(responseContent, DeserializationSettings);
                            ex.Body = cloudError;
                            ex.Data[AzurePSErrorDataKeys.CloudErrorCodeKey] = cloudError.Code;
                        }
                        catch (Exception exception)
                        {
                            await signal(Events.Debug, cancellationToken,
                                         () => EventHelper.CreateLogEvent($"[{id}]: Cannot deserialize due to {exception.Message}"));
                        }
                        qos.Exception = ex;
                        await signal(Events.Debug, cancellationToken,
                                     () => EventHelper.CreateLogEvent($"[{id}]: Getting exception '{qos.Exception}' from response"));
                    }
                }
            }
        }