public void TrackEvent(string str, string[] parameters, bool flush)
        {
            Dictionary <string, string> dr = new Dictionary <string, string>();

            for (int index = 0; index < parameters.GetLength(0); index += 2)
            {
                if (string.IsNullOrEmpty(parameters[index + 1]))
                {
                    continue;
                }
                dr.Add(parameters[index], parameters[index + 1]);
            }
            if (InnerClient == null)
            {
                return;
            }
            InnerClient.TrackEvent(str, dr);
            if (flush)
            {
                if (Count > 10)
                {
                    Task.Run(() => { InnerClient.Flush(); });
                    Count = 0;
                }
                else
                {
                    Count++;
                }
            }
        }
 public void Flush()
 {
     if (InnerClient != null)
     {
         InnerClient.Flush();
     }
 }
Exemplo n.º 3
0
        public void UpdateCommands()
        {
            if (BroadcastId == null)
            {
                return;
            }
            Task t = InnerClient.GetUpdatesAsync(0, 2, 0, new Telegram.Bot.Types.Enums.UpdateType[] { Telegram.Bot.Types.Enums.UpdateType.All }).ContinueWith(task => {
                foreach (Update upd in task.Result)
                {
                    if (upd.Message.Date <= LastCommandTime)
                    {
                        continue;
                    }
                    LastCommandTime = upd.Message.Date;
                    if (upd.Message.Chat.Id == BroadcastId.Identifier)
                    {
                        if (upd.Message.Text == "/stopit!")
                        {
                            IsActive = false;
                            InnerClient.SendTextMessageAsync(BroadcastId, "I am stopped!");
                        }
                        if (upd.Message.Text == "/startit")
                        {
                            IsActive = true;
                            InnerClient.SendTextMessageAsync(BroadcastId, "I am started!");
                        }
                        break;
                    }
                }
            });

            t.Wait(10000);
        }
Exemplo n.º 4
0
        public void SendMessage(MessageBase msg)
        {
            var om = InnerClient.CreateMessage();

            msg.Write(om);
            SendMessage(om);
        }
Exemplo n.º 5
0
        /// <summary>
        ///   Starts the partition pump.  In case it's already running, nothing happens.
        /// </summary>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public async Task StartAsync()
        {
            if (RunningTask == null)
            {
                await RunningTaskSemaphore.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (RunningTask == null)
                    {
                        RunningTaskTokenSource?.Cancel();
                        RunningTaskTokenSource = new CancellationTokenSource();

                        InnerConsumer = InnerClient.CreateConsumer(ConsumerGroup, PartitionId, Options.InitialEventPosition);

                        await PartitionProcessor.InitializeAsync().ConfigureAwait(false);

                        RunningTask = RunAsync(RunningTaskTokenSource.Token);
                    }
                }
                finally
                {
                    RunningTaskSemaphore.Release();
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///   Starts the partition pump.  In case it's already running, nothing happens.
        /// </summary>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public async Task StartAsync()
        {
            if (RunningTask == null)
            {
                await RunningTaskSemaphore.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (RunningTask == null)
                    {
                        // We expect the token source to be null, but we are playing safe.

                        RunningTaskTokenSource?.Cancel();
                        RunningTaskTokenSource = new CancellationTokenSource();

                        InnerConsumer = InnerClient.CreateConsumer(ConsumerGroup, Context.PartitionId, Options.InitialEventPosition);

                        // In case an exception is encountered while partition processor is initializing, don't catch it
                        // and let the event processor handle it.  The inner consumer hasn't connected to the service yet,
                        // so there's no need to close it.

                        await PartitionProcessor.InitializeAsync(Context).ConfigureAwait(false);

                        // Before closing, the running task will set the close reason in case of failure.  When something
                        // unexpected happens and it's not set, the default value (Unknown) is kept.

                        RunningTask = RunAsync(RunningTaskTokenSource.Token);
                    }
                }
                finally
                {
                    RunningTaskSemaphore.Release();
                }
            }
        }
Exemplo n.º 7
0
        private void RecivePacket(object peer)
        {
            NetIncomingMessage msg;

            while ((msg = InnerClient.ReadMessage()) != null)
            {
                switch (msg.MessageType)
                {
                case NetIncomingMessageType.DebugMessage:
                case NetIncomingMessageType.ErrorMessage:
                case NetIncomingMessageType.WarningMessage:
                case NetIncomingMessageType.VerboseDebugMessage:
                    break;

                case NetIncomingMessageType.DiscoveryResponse:
                    InnerClient.Connect(msg.SenderEndPoint);
                    break;

                case NetIncomingMessageType.StatusChanged:
                    OnStatusMessage(this, msg);
                    break;

                case NetIncomingMessageType.Data:
                    OnDataMessage(this, msg);
                    break;
                }
            }
        }
Exemplo n.º 8
0
 public void SendMessage(NetOutgoingMessage msg)
 {
     if (InnerClient.Status == NetPeerStatus.Running)
     {
         InnerClient.SendMessage(msg, NetDeliveryMethod.Unreliable);
     }
 }
Exemplo n.º 9
0
 public void DisConnect()
 {
     if (InnerClient.Status == NetPeerStatus.Running)
     {
         InnerClient.Disconnect("Disconnect");
         InnerClient.Shutdown("Shutdown");
     }
 }
Exemplo n.º 10
0
 public void Connect(String ip, int port)
 {
     if (InnerClient.Status != NetPeerStatus.Running)
     {
         InnerClient.Start();
         NetOutgoingMessage hail = InnerClient.CreateMessage("This is the hail message");
         InnerClient.Connect(ip, port, hail);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        ///   Creates an Event Hub producer responsible for publishing <see cref="EventData" /> to the
        ///   Event Hub, either as a single item or grouped together in batches.  Depending on the
        ///   <paramref name="producerOptions"/> specified, the producer may be created to allow event
        ///   data to be automatically routed to an available partition or specific to a partition.
        /// </summary>
        ///
        /// <param name="producerOptions">The set of options to apply when creating the producer.</param>
        ///
        /// <returns>An Event Hub producer configured in the requested manner.</returns>
        ///
        /// <remarks>
        ///   Allowing automatic routing of partitions is recommended when:
        ///   <para>- The publishing of events needs to be highly available.</para>
        ///   <para>- The event data should be evenly distributed among all available partitions.</para>
        ///
        ///   If no partition is specified, the following rules are used for automatically selecting one:
        ///   <para>- Distribute the events equally amongst all available partitions using a round-robin approach.</para>
        ///   <para>- If a partition becomes unavailable, the Event Hubs service will automatically detect it and forward the message to another available partition.</para>
        /// </remarks>
        ///
        public virtual EventHubProducer CreateProducer(EventHubProducerOptions producerOptions = default)
        {
            var options = producerOptions?.Clone() ?? new EventHubProducerOptions {
                Retry = null, Timeout = null
            };

            options.Retry   = options.Retry ?? ClientOptions.Retry.Clone();
            options.Timeout = options.TimeoutOrDefault ?? ClientOptions.DefaultTimeout;

            return(InnerClient.CreateProducer(options));
        }
Exemplo n.º 12
0
        public void AnnounceOfflineAsync(EndpointDiscoveryMetadata discoveryMetadata, object userState)
        {
            if (discoveryMetadata == null)
            {
                throw FxTrace.Exception.ArgumentNull("discoveryMetadata");
            }

            using (new AnnouncementOperationContextScope(InnerChannel))
            {
                InnerClient.ByeOperationAsync(discoveryMetadata, userState);
            }
        }
Exemplo n.º 13
0
        public IAsyncResult BeginAnnounceOffline(EndpointDiscoveryMetadata discoveryMetadata, AsyncCallback callback, object state)
        {
            if (discoveryMetadata == null)
            {
                throw FxTrace.Exception.ArgumentNull("discoveryMetadata");
            }

            using (new AnnouncementOperationContextScope(InnerChannel))
            {
                return(InnerClient.BeginByeOperation(discoveryMetadata, callback, state));
            }
        }
Exemplo n.º 14
0
        public void SendNotification(string text, long chatId)
        {
            TelegramClientInfo client = null;

            Clients.TryGetValue(chatId, out client);
            if (client == null || !client.Enabled)
            {
                return;
            }

            InnerClient.SendTextMessageAsync(client.ChatId, text, Telegram.Bot.Types.Enums.ParseMode.Html);
        }
Exemplo n.º 15
0
        public override void Dispose()
        {
            if (!IsDisposed)
            {
                if (InnerClient != null)
                {
                    InnerClient.Dispose();
                    InnerClient = null;
                }

                IsDisposed = true;
            }
        }
Exemplo n.º 16
0
        /// <summary>
        ///   Creates an event receiver responsible for reading <see cref="EventData" /> from a specific Event Hub partition,
        ///   and as a member of a specific consumer group.
        ///
        ///   A receiver may be exclusive, which asserts ownership over the partition for the consumer
        ///   group to ensure that only one receiver from that group is reading the from the partition.
        ///   These exclusive receivers are sometimes referred to as "Epoch Receivers."
        ///
        ///   A receiver may also be non-exclusive, allowing multiple receivers from the same consumer
        ///   group to be actively reading events from the partition.  These non-exclusive receivers are
        ///   sometimes referred to as "Non-epoch Receivers."
        ///
        ///   Designating a receiver as exclusive may be specified in the <paramref name="receiverOptions" />.
        ///   By default, receivers are created as non-exclusive.
        /// </summary>
        ///
        /// <param name="partitionId">The identifier of the Event Hub partition from which events will be received.</param>
        /// <param name="receiverOptions">The set of options to apply when creating the receiver.</param>
        ///
        /// <returns>An event receiver configured in the requested manner.</returns>
        ///
        /// <remarks>
        ///   If the starting event position is not specified in the <paramref name="receiverOptions"/>, the receiver will
        ///   default to ignoring events in the partition that were queued prior to the receiver being created and read only
        ///   events which appear after that point.
        /// </remarks>
        ///
        public virtual EventReceiver CreateReceiver(string partitionId,
                                                    EventReceiverOptions receiverOptions = default)
        {
            Guard.ArgumentNotNullOrEmpty(nameof(partitionId), partitionId);

            var options = receiverOptions?.Clone() ?? new EventReceiverOptions {
                Retry = null, DefaultMaximumReceiveWaitTime = null
            };

            options.Retry = options.Retry ?? ClientOptions.Retry.Clone();
            options.DefaultMaximumReceiveWaitTime = options.MaximumReceiveWaitTimeOrDefault ?? ClientOptions.DefaultTimeout;

            return(InnerClient.CreateReceiver(partitionId, options));
        }
Exemplo n.º 17
0
        private async Task <HttpResponseMessage> SendRequest(string url, HttpMethod method, HttpContent data, bool login)
        {
            if (method == null)
            {
                method = HttpMethod.Get;
            }
            var request = new HttpRequestMessage(method, url);

            if (data != null && method != HttpMethod.Get)
            {
                request.Content = data;
            }
            AddHeaders(request);
            return(await InnerClient.SendAsync(request));
        }
Exemplo n.º 18
0
 bool RegisterNewUsers(Update[] result)
 {
     foreach (Update upd in result)
     {
         if (upd.Message.Text.Trim() == "/regme " + RegistrationCode)
         {
             BroadcastId = upd.Message.Chat.Id;
             XtraMessageBox.Show("Telegram bot successfully registered!");
             InnerClient.SendTextMessageAsync(BroadcastId, "Hello my friend!");
             SettingsStore.Default.TelegramBotBroadcastId = BroadcastId.Identifier;
             IsActive = true;
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 19
0
        /// <summary>
        ///   Creates an Event Hub consumer responsible for reading <see cref="EventData" /> from a specific Event Hub partition,
        ///   in the context of a specific consumer group.
        ///
        ///   A consumer may be exclusive, which asserts ownership over the partition for the consumer
        ///   group to ensure that only one consumer from that group is reading the from the partition.
        ///   These exclusive consumers are sometimes referred to as "Epoch Consumers."
        ///
        ///   A consumer may also be non-exclusive, allowing multiple consumers from the same consumer
        ///   group to be actively reading events from the partition.  These non-exclusive consumers are
        ///   sometimes referred to as "Non-epoch Consumers."
        ///
        ///   Designating a consumer as exclusive may be specified in the <paramref name="consumerOptions" />.
        ///   By default, consumers are created as non-exclusive.
        /// </summary>
        ///
        /// <param name="consumerGroup">The name of the consumer group this consumer is associated with.  Events are read in the context of this group.</param>
        /// <param name="partitionId">The identifier of the Event Hub partition from which events will be received.</param>
        /// <param name="eventPosition">The position within the partition where the consumer should begin reading events.</param>
        /// <param name="consumerOptions">The set of options to apply when creating the consumer.</param>
        ///
        /// <returns>An Event Hub consumer configured in the requested manner.</returns>
        ///
        public virtual EventHubConsumer CreateConsumer(string consumerGroup,
                                                       string partitionId,
                                                       EventPosition eventPosition,
                                                       EventHubConsumerOptions consumerOptions = default)
        {
            Guard.ArgumentNotNullOrEmpty(nameof(partitionId), partitionId);
            Guard.ArgumentNotNull(nameof(eventPosition), eventPosition);

            var options = consumerOptions?.Clone() ?? new EventHubConsumerOptions {
                Retry = null, DefaultMaximumReceiveWaitTime = null
            };

            options.Retry = options.Retry ?? ClientOptions.Retry.Clone();
            options.DefaultMaximumReceiveWaitTime = options.MaximumReceiveWaitTimeOrDefault ?? ClientOptions.DefaultTimeout;

            return(InnerClient.CreateConsumer(consumerGroup, partitionId, eventPosition, options));
        }
Exemplo n.º 20
0
        private async Task <HttpResponseMessage> SendRequest(string url, CancellationToken token, HttpMethod method = null, HttpContent data = null, bool login = false)
        {
            if (method == null)
            {
                method = HttpMethod.Get;
            }
            var request = new HttpRequestMessage(method, url);

            if (data != null && method != HttpMethod.Get)
            {
                request.Content = data;
            }
            AddHeaders(request);
            if (!login)
            {
                AddAuth(request);
            }
            return(await InnerClient.SendAsync(request, token));
        }
Exemplo n.º 21
0
 public void Update()
 {
     InnerClient.GetMeAsync().ContinueWith(u => {
         Debug.Write(u.Result.Username);
     });
     InnerClient.GetUpdatesAsync().ContinueWith(task => {
         if (!string.IsNullOrEmpty(RegistrationCode))
         {
             if (task.IsFaulted)
             {
                 Telemetry.Default.TrackException(task.Exception);
             }
             else
             {
                 RegisterNewUsers(task.Result);
             }
         }
         RegistrationCode = string.Empty;
     });
 }
Exemplo n.º 22
0
        /// <summary>
        ///   Starts the event processor.  In case it's already running, nothing happens.
        /// </summary>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        ///
        public async Task StartAsync()
        {
            if (RunningTask == null)
            {
                await RunningTaskSemaphore.WaitAsync().ConfigureAwait(false);

                try
                {
                    if (RunningTask == null)
                    {
                        RunningTaskTokenSource?.Cancel();
                        RunningTaskTokenSource = new CancellationTokenSource();

                        PartitionPumps.Clear();

                        var partitionIds = await InnerClient.GetPartitionIdsAsync().ConfigureAwait(false);

                        await Task.WhenAll(partitionIds
                                           .Select(partitionId =>
                        {
                            var partitionContext  = new PartitionContext(InnerClient.EventHubName, ConsumerGroup, partitionId);
                            var checkpointManager = new CheckpointManager(partitionContext, Manager, Identifier);

                            var partitionProcessor = PartitionProcessorFactory(partitionContext, checkpointManager);

                            var partitionPump = new PartitionPump(InnerClient, ConsumerGroup, partitionId, partitionProcessor, Options);
                            PartitionPumps.TryAdd(partitionId, partitionPump);

                            return(partitionPump.StartAsync());
                        })).ConfigureAwait(false);

                        RunningTask = RunAsync(RunningTaskTokenSource.Token);
                    }
                }
                finally
                {
                    RunningTaskSemaphore.Release();
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        ///   Finds and tries to claim an ownership if this <see cref="EventProcessor{T}" /> instance is eligible to increase its ownership
        ///   list.
        /// </summary>
        ///
        /// <param name="completeOwnershipEnumerable">A complete enumerable of ownership obtained from the stored service provided by the user.</param>
        /// <param name="activeOwnership">The set of ownership that are still active.</param>
        ///
        /// <returns>The claimed ownership. <c>null</c> if this instance is not eligible, if no claimable ownership was found or if the claim attempt failed.</returns>
        ///
        private async Task <PartitionOwnership> FindAndClaimOwnershipAsync(IEnumerable <PartitionOwnership> completeOwnershipEnumerable,
                                                                           IEnumerable <PartitionOwnership> activeOwnership)
        {
            // Get a complete list of the partition ids present in the Event Hub.  This should be immutable for the time being, but
            // it may change in the future.

            var partitionIds = await InnerClient.GetPartitionIdsAsync().ConfigureAwait(false);

            // Create a partition distribution dictionary from the active ownership list we have, mapping an owner's identifier to the amount of
            // partitions it owns.  When an event processor goes down and it has only expired ownership, it will not be taken into consideration
            // by others.

            var partitionDistribution = new Dictionary <string, int>
            {
                { Identifier, 0 }
            };

            foreach (var ownership in activeOwnership)
            {
                if (partitionDistribution.TryGetValue(ownership.OwnerIdentifier, out var value))
                {
                    partitionDistribution[ownership.OwnerIdentifier] = value + 1;
                }
                else
                {
                    partitionDistribution[ownership.OwnerIdentifier] = 1;
                }
            }

            // The minimum owned partitions count is the minimum amount of partitions every event processor needs to own when the distribution
            // is balanced.  If n = minimumOwnedPartitionsCount, a balanced distribution will only have processors that own n or n + 1 partitions
            // each.  We can guarantee the partition distribution has at least one key, which corresponds to this event processor instance, even
            // if it owns no partitions.

            var minimumOwnedPartitionsCount = partitionIds.Length / partitionDistribution.Keys.Count;
            var ownedPartitionsCount        = partitionDistribution[Identifier];

            // There are two possible situations in which we may need to claim a partition ownership.
            //
            // The first one is when we are below the minimum amount of owned partitions.  There's nothing more to check, as we need to claim more
            // partitions to enforce balancing.
            //
            // The second case is a bit tricky.  Sometimes the claim must be performed by an event processor that already has reached the minimum
            // amount of ownership.  This may happen, for instance, when we have 13 partitions and 3 processors, each of them owning 4 partitions.
            // The minimum amount of partitions per processor is, in fact, 4, but in this example we still have 1 orphan partition to claim.  To
            // avoid overlooking this kind of situation, we may want to claim an ownership when we have exactly the minimum amount of ownership,
            // but we are making sure there are no better candidates among the other event processors.

            if (ownedPartitionsCount < minimumOwnedPartitionsCount ||
                ownedPartitionsCount == minimumOwnedPartitionsCount && !partitionDistribution.Values.Any(partitions => partitions < minimumOwnedPartitionsCount))
            {
                // Look for unclaimed partitions.  If any, randomly pick one of them to claim.

                var unclaimedPartitions = partitionIds
                                          .Except(activeOwnership.Select(ownership => ownership.PartitionId));

                if (unclaimedPartitions.Any())
                {
                    var index = RandomNumberGenerator.Value.Next(unclaimedPartitions.Count());

                    return(await ClaimOwnershipAsync(unclaimedPartitions.ElementAt(index), completeOwnershipEnumerable).ConfigureAwait(false));
                }

                // Only try to steal partitions if there are no unclaimed partitions left.  At first, only processors that have exceeded the
                // maximum owned partition count should be targeted.

                var maximumOwnedPartitionsCount = minimumOwnedPartitionsCount + 1;

                var stealablePartitions = activeOwnership
                                          .Where(ownership => partitionDistribution[ownership.OwnerIdentifier] > maximumOwnedPartitionsCount)
                                          .Select(ownership => ownership.PartitionId);

                // Here's the important part.  If there are no processors that have exceeded the maximum owned partition count allowed, we may
                // need to steal from the processors that have exactly the maximum amount.  If this instance is below the minimum count, then
                // we have no choice as we need to enforce balancing.  Otherwise, leave it as it is because the distribution wouldn't change.

                if (!stealablePartitions.Any() && ownedPartitionsCount < minimumOwnedPartitionsCount)
                {
                    stealablePartitions = activeOwnership
                                          .Where(ownership => partitionDistribution[ownership.OwnerIdentifier] == maximumOwnedPartitionsCount)
                                          .Select(ownership => ownership.PartitionId);
                }

                // If any stealable partitions were found, randomly pick one of them to claim.

                if (stealablePartitions.Any())
                {
                    var index = RandomNumberGenerator.Value.Next(stealablePartitions.Count());

                    return(await ClaimOwnershipAsync(stealablePartitions.ElementAt(index), completeOwnershipEnumerable).ConfigureAwait(false));
                }
            }

            // No ownership was claimed.

            return(null);
        }
Exemplo n.º 24
0
 public void EndAnnounceOnline(IAsyncResult result)
 {
     InnerClient.EndHelloOperation(result);
 }
Exemplo n.º 25
0
 public override void RefreshPool()
 {
     ThrowIfDisposed();
     InnerClient.RefreshPool();
 }
Exemplo n.º 26
0
 public void EndAnnounceOffline(IAsyncResult result)
 {
     InnerClient.EndByeOperation(result);
 }
Exemplo n.º 27
0
 public void Flush()
 {
     InnerClient.Flush();
 }
Exemplo n.º 28
0
 /// <summary>
 ///   Retrieves information about an Event Hub, including the number of partitions present
 ///   and their identifiers.
 /// </summary>
 ///
 /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
 ///
 /// <returns>The set of information for the Event Hub that this client is associated with.</returns>
 ///
 public virtual Task <EventHubProperties> GetPropertiesAsync(CancellationToken cancellationToken = default) => InnerClient.GetPropertiesAsync(cancellationToken);
Exemplo n.º 29
0
 /// <summary>
 ///   Closes the connection to the Event Hub instance.
 /// </summary>
 ///
 /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
 ///
 /// <returns>A task to be resolved on when the operation has completed.</returns>
 ///
 public virtual Task CloseAsync(CancellationToken cancellationToken = default) => InnerClient.CloseAsync(cancellationToken);
Exemplo n.º 30
0
 /// <summary>
 ///   Retrieves information about a specific partiton for an Event Hub, including elements that describe the available
 ///   events in the partition event stream.
 /// </summary>
 ///
 /// <param name="partitionId">The unique identifier of a partition associated with the Event Hub.</param>
 /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
 ///
 /// <returns>The set of information for the requested partition under the Event Hub this client is associated with.</returns>
 ///
 public virtual Task <PartitionProperties> GetPartitionPropertiesAsync(string partitionId,
                                                                       CancellationToken cancellationToken = default) => InnerClient.GetPartitionPropertiesAsync(partitionId, cancellationToken);