Exemple #1
0
 public static void SafeLaunchEvent <T1, T2, T3>(GenericEventHandler <T1, T2, T3> ev, object sender, T1 par1, T2 par2, T3 par3)
 {
     if (ev != null)
     {
         ev(sender, par1, par2, par3);
     }
 }
Exemple #2
0
        private IUnlaunchClient CreateUnlaunchClient()
        {
            var restWrapper = UnlaunchRestWrapper.Create(_sdkKey, _httpClientFactory.CreateClient(), _baseUrl, FlagApiPath, _connectionTimeout);
            var initialDownloadDoneEvent     = new CountdownEvent(1);
            var downloadSuccessful           = new AtomicBoolean(false);
            var s3BucketClient               = UnlaunchGenericRestWrapper.Create(_httpClientFactory.CreateClient(), _s3BucketUrl, _sdkKey, _connectionTimeout);
            var refreshableDataStoreProvider = new RefreshableDataStoreProvider(restWrapper, s3BucketClient,
                                                                                initialDownloadDoneEvent, downloadSuccessful, _pollingInterval);

            var dataStore = refreshableDataStoreProvider.GetNoOpDataStore();

            try
            {
                dataStore = refreshableDataStoreProvider.GetDataStore();
            }
            catch
            {
                Logger.Error("Unable to download features and init. Make sure you're using the " +
                             "correct SDK Key. We'll retry again but this error is usually not recoverable.");
            }

            var impressionApiRestClient = UnlaunchRestWrapper.Create(_sdkKey, _httpClientFactory.CreateClient(), _baseUrl, ImpressionApiPath, _connectionTimeout);
            var impressionsEventHandler = new GenericEventHandler("metrics-impressions", false, impressionApiRestClient, _metricsFlushInterval, _metricsQueueSize);

            var eventsApiRestClient         = UnlaunchRestWrapper.Create(_sdkKey, _httpClientFactory.CreateClient(), _baseUrl, EventApiPath, _connectionTimeout);
            var eventHandler                = new GenericEventHandler("generic", true, eventsApiRestClient, _eventsFlushInterval, _eventsQueueSize);
            var variationsCountEventHandler = new CountAggregatorEventHandler(eventHandler, _metricsFlushInterval);

            return(UnlaunchClient.Create(dataStore, eventHandler, variationsCountEventHandler, impressionsEventHandler,
                                         initialDownloadDoneEvent, downloadSuccessful));
        }
Exemple #3
0
        // static Logger _Logger = LogManager.GetCurrentClassLogger();

        public static void SafeLaunchEvent(GenericEventHandler ev, object sender)
        {
            if (ev != null)
            {
                ev(sender);
            }
        }
Exemple #4
0
 /// <summary>
 /// Raises events declared as <see cref="GenericEventHandler{TEventArgs, REventArgs}"/>
 /// </summary>
 public static void Raise <TEventArgs, REventArgs>(this GenericEventHandler <TEventArgs, REventArgs> handler, object sender, TEventArgs args1, REventArgs args2)
 {
     if (handler != null)
     {
         handler(sender, args1, args2);
     }
 }
Exemple #5
0
    static Boolean InvokeAllEventHandlers <TArgs>(this GenericEventHandler <TArgs> evt, TArgs args, out Exception[] occurredExceptions)
    {
        LinkedList <Exception> exceptions = null;
        var result = evt != null;

        if (result)
        {
            foreach (var handler in evt.GetInvocationList())
            {
                try
                {
                    ((GenericEventHandler <TArgs>)handler)?.Invoke(args);
                }
                catch (Exception exc)
                {
                    if (exceptions == null)
                    {
                        exceptions = new LinkedList <Exception>();
                    }
                    exceptions.AddLast(exc);
                }
            }
        }
        if (exceptions != null)
        {
            occurredExceptions = exceptions.ToArray();
        }
        else
        {
            occurredExceptions = Empty <Exception> .Array;
        }
        return(result);
    }
 public static void SafeLaunchEvent <T>(GenericEventHandler <T> ev, object sender, T msg)
 {
     if (ev != null)
     {
         ev(sender, msg);
     }
 }
Exemple #7
0
        internal void RegisterEventHandler(
            string eventName,
            Delegate handler,
            GenericEventHandler invoker,
            bool onCapturePhase = false,
            HtmlEventExtractor?eventExtractor = null,
            EventArgsParser payloadConverter  = null)
        {
            if (this.Log().IsEnabled(LogLevel.Debug))
            {
                this.Log().Debug($"Registering {eventName} on {this}.");
            }

            if (!_eventHandlers.TryGetValue(eventName, out var registration))
            {
                _eventHandlers[eventName] = registration = new EventRegistration(
                    this,
                    eventName,
                    onCapturePhase,
                    eventExtractor,
                    payloadConverter);
            }

            registration.Add(handler, invoker);
        }
Exemple #8
0
 public static void SafeLaunchEvent <T1, T2, T3, T4, T5>(GenericEventHandler <T1, T2, T3, T4, T5> ev, object sender, T1 par1, T2 par2, T3 par3, T4 par4, T5 par5)
 {
     if (ev != null)
     {
         ev(sender, par1, par2, par3, par4, par5);
     }
 }
Exemple #9
0
 public static void SafeLaunchEvent <T>(GenericEventHandler <T> ev, object sender, T par)
 {
     // _Logger.Info("SafeLaunchEvent: {0}", par);
     if (ev != null)
     {
         ev(sender, par);
     }
 }
Exemple #10
0
 internal void PostCallback <A>(GenericEventHandler <A> handler, A args)
 {
     if (handler == null)
     {
         return;
     }
     Sync.Post(new SendOrPostCallback((state) => { handler(this, args); }), null);
 }
Exemple #11
0
        /// <summary>
        /// Connects to an active instance of skype
        /// </summary>
        public Task ConnectAsync()
        {
            if (_skypeWindowHandle != IntPtr.Zero)
            {
                throw new InvalidOperationException("This client is already connected to a Skype instance. Please disconnect first");
            }

            // If the skype client is in a NotAvailable state we need to throw an error and ask the user to wait until
            // the client becomes Available again before attempting a connection
            if (Status == SkypeStatus.NotAvailable)
            {
                throw new ServiceAccessException("The API is not available at the moment, possible explanation is that there is no user currently logged in. Please wait until the client updates its status to 'Available' before attempting to connect again");
            }

            // Begin by creating a handle for this class so that we can register for Messages
            // Is it better to force the re-creation of a handle?
            RecreateHandle();

            TaskCompletionSource <bool>       sSource     = new TaskCompletionSource <bool>();
            GenericEventHandler <SkypeStatus> taskHandler = null;

            taskHandler = (s, e) =>
            {
                Debug.Print("Task : " + e);
                if (e == SkypeStatus.Success)
                {
                    sSource.TrySetResult(true);

                    // Unsubscribe from this handler
                    this.StatusChanged -= taskHandler;
                }
                else if (e == SkypeStatus.Refused || e == SkypeStatus.NotAvailable || e == SkypeStatus.Unknown)
                {
                    sSource.TrySetException(new ServiceAccessException("Could not connect to an active skype instance. Skype response '" + e + "'"));

                    // Unsubscribe from this handler
                    this.StatusChanged -= taskHandler;
                }
            };
            this.StatusChanged += taskHandler;

            // Register for the window messages
            _skypeWindowMessageDiscoverId = Win32Api.RegisterWindowMessage(SkypeWindowMessageDiscover);
            _skypeWindowMessageAttachId   = Win32Api.RegisterWindowMessage(SkypeWindowMessageAttach);

            // Send the connect message to the Skype applications
            IntPtr result;
            IntPtr aRetVal = Win32Api.SendMessageTimeout(Win32Api.HWND_BROADCAST, _skypeWindowMessageDiscoverId, Handle, IntPtr.Zero, Win32Api.SendMessageTimeoutFlags.SMTO_NORMAL, 100, out result);

            // If the return value is the zero pointer then we couldn't connect to a skype application
            // maybe one isn't running at the moment
            if (aRetVal == IntPtr.Zero)
            {
                sSource.TrySetException(new ServiceAccessException("Could not connect to an active skype application (no response received). Make sure that at least one instance of Skype is running on your computer."));
            }

            return(sSource.Task);
        }
Exemple #12
0
        protected virtual void FireTimeout(string e)
        {
            GenericEventHandler <string> handler = Timeout;

            if (handler != null)
            {
                handler(this, e);
            }
        }
        /// <summary>
        /// Removes a change handler from the specified <see cref="DependencyProperty"/>.
        /// </summary>
        /// <param name="property">The <see cref="DependencyProperty"/> to remove the change handler from.</param>
        /// <param name="handler">The handler of the change event which should be removed.</param>
        public void RemoveChangeHandler(DependencyProperty property, GenericEventHandler <IDependencyObject, PropertyChangedEventArgs> handler)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            GetStorage(property, false, false)?.RemoveChangeHandler(handler);
        }
Exemple #14
0
        public void EmitEvent(string name)
        {
            GenericEventHandler callback = eventsListener.GetEvent(name);

            if (callback != null)
            {
                Task.Run(() => callback(new GenericEventArgs()));
            }
        }
        public void Trigger <T>(Entity entity, T e) where T : EventArgs
        {
            GenericEventHandler handler = this.GenericEvent;

            if (handler != null)
            {
                handler(entity, typeof(T), e);
            }
        }
Exemple #16
0
 internal void UnregisterEventHandler(string eventName, Delegate handler, GenericEventHandler invoker)
 {
     if (_eventHandlers.TryGetValue(eventName, out var registration))
     {
         registration.Remove(handler, invoker);
     }
     else if (this.Log().IsEnabled(LogLevel.Debug))
     {
         this.Log().Debug(message: $"No handler registered for event {eventName}.");
     }
 }
 protected AbstractAsyncEnumerableObservable(
     TEnumerable source
     )
 {
     this._source      = ArgumentValidator.ValidateNotNull(nameof(source), source);
     this._beforeStart = (args) => this.BeforeEnumerationStart?.InvokeAllEventHandlers(args, throwExceptions: false);
     this._afterStart  = (args) => this.AfterEnumerationStart?.InvokeAllEventHandlers(args, throwExceptions: false);
     this._afterItem   = (args) => this.AfterEnumerationItemEncountered?.InvokeAllEventHandlers(args, throwExceptions: false);
     this._beforeEnd   = (args) => this.BeforeEnumerationEnd?.InvokeAllEventHandlers(args, throwExceptions: false);
     this._afterEnd    = (args) => this.AfterEnumerationEnd?.InvokeAllEventHandlers(args, throwExceptions: false);
 }
 public static void AsyncSafeLaunchEvent <T>(GenericEventHandler <T> ev, object sender, T msg)
 {
     if (ev != null)
     {
         GenericEventHandler <T> auxEv = delegate(object s, T m)
         {
             ev(s, m);
         };
         auxEv.BeginInvoke(sender, msg, AsyncSafeLaunchEventCallback, null);
     }
 }
Exemple #19
0
        protected virtual void OnChanged()
        {
            GenericEventHandler <IZetboxContext> temp = Changed;

            if (temp != null)
            {
                temp(this, new GenericEventArgs <IZetboxContext>()
                {
                    Data = this
                });
            }
        }
Exemple #20
0
        public void Dispose()
        {
            GenericEventHandler <IReadOnlyZetboxContext> temp = Disposing;

            if (temp != null)
            {
                temp(this, new GenericEventArgs <IReadOnlyZetboxContext>()
                {
                    Data = this
                });
            }
        }
Exemple #21
0
        /// <inheritdoc />
        public virtual void Dispose()
        {
            GenericEventHandler <IReadOnlyZetboxContext> temp = Disposing;

            if (temp != null)
            {
                temp(this, new GenericEventArgs <IReadOnlyZetboxContext>()
                {
                    Data = this
                });
            }
            // nothing to dispose
            IsDisposed = true;
        }
Exemple #22
0
        // TODO: implement proper IDisposable pattern
        public virtual void Dispose()
        {
            GenericEventHandler <IReadOnlyZetboxContext> temp = Disposing;

            if (temp != null)
            {
                temp(this, new GenericEventArgs <IReadOnlyZetboxContext>()
                {
                    Data = this
                });
            }
            GC.SuppressFinalize(this);
            IsDisposed = true;
        }
Exemple #23
0
        /// <summary>Reports a progress change.</summary>
        /// <param name="value">The value of the updated progress.</param>
        protected virtual void OnReport(T value)
        {
            // If there's no handler, don't bother going through the [....] context.
            // Inside the callback, we'll need to check again, in case
            // an event handler is removed between now and then.
            Action <T> handler = m_handler;
            GenericEventHandler <T> changedEvent = ProgressChanged;

            if (handler != null || changedEvent != null)
            {
                // Post the processing to the [....] context.
                // (If T is a value type, it will get boxed here.)
                m_synchronizationContext.Post(m_invokeHandlers, value);
            }
        }
Exemple #24
0
        public void Create_Generic()
        {
            using (IZetboxContext ctx = GetContext())
            {
                bool hasCreated = false;
                GenericEventHandler <IPersistenceObject> createdHandler = new GenericEventHandler <IPersistenceObject>(delegate(object obj, GenericEventArgs <IPersistenceObject> e) { hasCreated = true; });
                ctx.ObjectCreated += createdHandler;

                TestObjClass newObj = ctx.Create <TestObjClass>();
                Assert.That(newObj, Is.Not.Null);
                Assert.That(newObj.Context, Is.Not.Null);
                Assert.That(hasCreated, Is.True);

                ctx.ObjectCreated -= createdHandler;
            }
        }
Exemple #25
0
        public void Create_Generic()
        {
            using (IZetboxContext ctx = GetContext())
            {
                bool hasCreated = false;
                GenericEventHandler<IPersistenceObject> createdHandler = new GenericEventHandler<IPersistenceObject>(delegate(object obj, GenericEventArgs<IPersistenceObject> e) { hasCreated = true; });
                ctx.ObjectCreated += createdHandler;

                TestObjClass newObj = ctx.Create<TestObjClass>();
                Assert.That(newObj, Is.Not.Null);
                Assert.That(newObj.Context, Is.Not.Null);
                Assert.That(hasCreated, Is.True);

                ctx.ObjectCreated -= createdHandler;
            }
        }
Exemple #26
0
            public void Remove(Delegate handler, GenericEventHandler invoker)
            {
                var invocationItem = new InvocationItem(handler, invoker);

                // Do not alter the invocation list while enumerating it (_isDispatching)
                var invocationList = _isDispatching
                                        ? _pendingInvocationList ?? (_pendingInvocationList = new List <InvocationItem>(_invocationList))
                                        : _invocationList;

                invocationList.Remove(invocationItem);

                // TODO: Removing handler in HTML not supported yet
                // var command = $"Uno.UI.WindowManager.current.unregisterEventOnView(\"{HtmlId}\", \"{eventName}\");";
                // WebAssemblyRuntime.InvokeJS(command);
                // _isSubscribed = false;
            }
Exemple #27
0
        /// <summary>Invokes the action and event callbacks.</summary>
        /// <param name="state">The progress value.</param>
        private void InvokeHandlers(object state)
        {
            T value = (T)state;

            Action <T> handler = m_handler;
            GenericEventHandler <T> changedEvent = ProgressChanged;

            if (handler != null)
            {
                handler(value);
            }
            if (changedEvent != null)
            {
                changedEvent(this, value);
            }
        }
Exemple #28
0
        /// <summary>
        /// Callback invoking the handlers.
        /// </summary>
        /// <param name="pState">The state.</param>
        private void InvokeHandlers(object pState)
        {
            TValue          lState   = (TValue)pState;
            Action <TValue> lHandler = this.mHandler;
            GenericEventHandler <TValue> lProgressChanged = this.ProgressChanged;

            if (lHandler != null)
            {
                lHandler(lState);
            }
            if (lProgressChanged == null)
            {
                return;
            }

            lProgressChanged((object)this, lState);
        }
Exemple #29
0
        /// <summary>
        /// Provides a bi-directional weak event handler management.
        /// </summary>
        /// <param name="list">A list of registrations to manage</param>
        /// <param name="handler">The actual handler to execute.</param>
        /// <param name="raise">The delegate used to raise <paramref name="handler"/> if it has not been collected.</param>
        /// <returns>A disposable that keeps the registration alive.</returns>
        /// <remarks>
        /// The bi-directional relation is defined by the fact that both the
        /// source and the target are weak. The source must be kept alive by
        /// another longer-lived reference, and the target is kept alive by the
        /// return disposable.
        ///
        /// If the returned disposable is collected, the handler will also be
        /// collected. Conversly, if the <paramref name="list"/> is collected
        /// raising the event will produce nothing.
        /// </remarks>
        internal static IDisposable RegisterEvent(IList <GenericEventHandler> list, Delegate handler, EventRaiseHandler raise)
        {
            var wr = new WeakReference(handler);

            GenericEventHandler genericHandler = null;

            // This weak reference ensure that the closure will not link
            // the caller and the callee, in the same way "newValueActionWeak"
            // does not link the callee to the caller.
            var instanceRef = new WeakReference <IList <GenericEventHandler> >(list);

            Action removeHandler = () =>
            {
                var thatList = instanceRef.GetTarget();

                if (thatList != null)
                {
                    thatList.Remove(genericHandler);
                }
            };

            genericHandler = (s, e) =>
            {
                var weakHandler = wr.Target as Delegate;

                if (weakHandler != null)
                {
                    raise(weakHandler, s, e);
                }
                else
                {
                    removeHandler();
                }
            };

            list.Add(genericHandler);

            return(Disposable.Create(() =>
            {
                removeHandler();

                // Force a closure on the callback, to make its lifetime as long
                // as the subscription being held by the callee.
                handler = null;
            }));
        }
Exemple #30
0
 public void AddItem(string item)
 {
     if (InvokeRequired)
     {
         GenericEventHandler <string> setTextDel = delegate(string text)
         {
             base.Items.Add(text);
         };
         try
         {
             Invoke(setTextDel, new object[] { item });
         }
         catch {}
     }
     else
     {
         base.Items.Add(item);
     }
 }
Exemple #31
0
    static Boolean InvokeAllEventHandlers <TArgs>(this GenericEventHandler <TArgs> evt, TArgs args, Boolean throwExceptions = true)
    {
        LinkedList <Exception> exceptions = null;
        var result = evt != null;

        if (result)
        {
            var invocationList = evt.GetInvocationList();
            for (var i = 0; i < invocationList.Length; ++i)
            {
                try
                {
                    ((GenericEventHandler <TArgs>)invocationList[i])?.Invoke(args);
                }
                catch (Exception exc)
                {
                    if (throwExceptions)
                    {
                        if (exceptions == null)
                        {
                            // Just re-throw if this is last handler and first exception
                            if (i == invocationList.Length - 1)
                            {
                                throw;
                            }
                            else
                            {
                                exceptions = new LinkedList <Exception>();
                            }
                        }
                        exceptions.AddLast(exc);
                    }
                }
            }
        }

        if (exceptions != null)
        {
            throw new AggregateException(exceptions.ToArray());
        }

        return(result);
    }
Exemple #32
0
 /// <summary>
 /// Register the appender on trace events indicated on configuration object
 /// </summary>
 /// <param name="config">the appender configuration object</param>
 /// <exception cref="IntializatonException">When fail to initialize.</exception>
 public Appender(pt.sapo.gis.trace.configuration.appender config)
 {
     Properties = new AppenderConfigProperties(config.property);
     severities = config.events.Where(e => e.filters != null).ToDictionary(e => e.type, e => e.filters);
     foreach(@event evt in config.events){                
         switch(evt.type) {
             case eventType.entry:
                 if (evt.filters == null || evt.filters.Length == 0)
                     onEntry = e => OnEntry(e);                            
                 else 
                     onEntry = e => { if(evt.filters.Contains(e.Severity)) OnEntry(e); };
                 TraceManager.OnEntry += onEntry;
                 break;
             case eventType.trace:
                 if (evt.filters == null || evt.filters.Length == 0)
                     onTrace = t => OnTrace(t);
                 else 
                     onTrace = t => { if(t.GetSeverityTypes().Any(s => evt.filters.Contains(s))) OnTrace(t); };
                 TraceManager.OnTrace += onTrace;
                 break;
         }
     }
     
 }
Exemple #33
0
 /// <summary>
 /// Executes a delegate of type GenericEventHandler while providing thread afinity.
 /// </summary>
 /// <param name="eventHandler">Delegate method to Invoke.</param>
 public static void Fire(GenericEventHandler eventHandler)
 {
     SafeEventInvoke(eventHandler);
 }
Exemple #34
0
        public void Unsubscribe(EventType mask)
        {
            IPublisherEvents subscriber = OperationContext.Current.GetCallbackChannel<IPublisherEvents>();

            if ((mask & EventType.Event1) == EventType.Event1)
            { event1 -= subscriber.OnEvent1; }
            if ((mask & EventType.Event2) == EventType.Event2)
            { event2 -= subscriber.OnEvent2; }
            if ((mask & EventType.Event3) == EventType.Event3)
            { event3 -= subscriber.OnEvent3; }
        }
Exemple #35
0
        public void Delete_triggers_ObjectDeleted()
        {
            using (IZetboxContext ctx = GetContext())
            {
                bool hasDeleted = false;
                GenericEventHandler<IPersistenceObject> deletedHandler = new GenericEventHandler<IPersistenceObject>(
                    delegate(object obj, GenericEventArgs<IPersistenceObject> e)
                    {
                        hasDeleted = true;
                    });
                ctx.ObjectDeleted += deletedHandler;

                var result = ctx.GetQuery<TestObjClass>();
                Assert.That(result.ToList().Count, Is.GreaterThan(0));

                result.ForEach<TestObjClass>(
                    o => ctx.Delete(o));

                Assert.That(hasDeleted, Is.True);

                ctx.ObjectDeleted -= deletedHandler;
                ctx.SubmitChanges();
            }
        }