示例#1
0
        public static object PullMessagesSync(string projectId,
                                              string subscriptionId, bool acknowledge)
        {
            // [START pubsub_subscriber_sync_pull]
            SubscriptionName subscriptionName = new SubscriptionName(projectId,
                                                                     subscriptionId);
            SubscriberServiceApiClient subscriberClient =
                SubscriberServiceApiClient.Create();
            // Pull messages from server,
            // allowing an immediate response if there are no messages.
            PullResponse response = subscriberClient.Pull(
                subscriptionName, returnImmediately: true, maxMessages: 20);

            // Print out each received message.
            foreach (ReceivedMessage msg in response.ReceivedMessages)
            {
                string text = Encoding.UTF8.GetString(msg.Message.Data.ToArray());
                Console.WriteLine($"Message {msg.Message.MessageId}: {text}");
            }
            // If acknowledgement required, send to server.
            if (acknowledge)
            {
                subscriberClient.Acknowledge(subscriptionName,
                                             response.ReceivedMessages.Select(msg => msg.AckId));
            }
            // [END pubsub_subscriber_sync_pull]
            return(0);
        }
示例#2
0
        private static PullResponse ShowMessagesForSubscription()
        {
            var subscriptionName = new SubscriptionName(ProjectId, SubscriptionId);

            var subscription = SubscriberServiceApiClient.Create();

            try
            {
                PullResponse response = subscription.Pull(subscriptionName, true, 2);

                var all = response.ReceivedMessages;
                Console.WriteLine("Inside subscription" + all.Count);
                foreach (ReceivedMessage message in all)
                {
                    string id          = message.Message.MessageId;
                    string publishDate = message.Message.PublishTime.ToDateTime().ToString("dd-M-yyyy HH:MM:ss");
                    string data        = message.Message.Data.ToStringUtf8();

                    Console.WriteLine($"{id} {publishDate} - {data}");

                    Console.Write("  Acknowledging...");
                    subscription.Acknowledge(subscriptionName, new string[] { message.AckId });
                    Console.WriteLine("done");
                }

                return(response);
            }
            catch (RpcException e)
            {
                Console.WriteLine("Something went wrong: {0}", e.Message);
                return(null);
            }
        }
示例#3
0
    public static async Task DeleteSubscription(string subscriptionId)
    {
        var subscriber = await SubscriberServiceApiClient.CreateAsync();

        var subscriptionName = SubscriptionName.FromProjectSubscription(ProjectId, subscriptionId);
        await subscriber.DeleteSubscriptionAsync(subscriptionName);
    }
示例#4
0
        public async Task SubscribeUserCreationAsync(Func <User, Task <SubscriberClient.Reply> > feedHandler, CancellationToken stoppingToken)
        {
            _logger.LogInformation($"Initializing subscription for {_pubSubCredentials} using { _userCreationSubscription }");
            SubscriberServiceApiClient subscriber = PubSubHelper.CreateSubscriber(_pubSubCredentials);

            await SubscribeAsync(subscriber, _userCreationSubscription, feedHandler, stoppingToken);
        }
示例#5
0
        public async Task <object> CreateSubscriber(TopicName topic)
        {
            SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(_projectId, "SubscriptionJ");

            var subscriptionCreated = subscriber.CreateSubscription(subscriptionName, topic, pushConfig: null, ackDeadlineSeconds: 60);

            SubscriberClient subscriberClient = await SubscriberClient.CreateAsync(subscriptionName);

            try
            {
                _ = subscriberClient.StartAsync(
                    async(PubsubMessage message, CancellationToken cancel) =>
                {
                    string text = Encoding.UTF8.GetString(message.Data.ToArray());

                    await Console.Out.WriteLineAsync($"Consumer {message.MessageId} => Message:{text}");

                    Console.WriteLine(message);

                    return(await Task.FromResult(SubscriberClient.Reply.Ack));
                });

                await Task.Delay(3000);

                await subscriberClient.StopAsync(CancellationToken.None);
            }
            catch (RpcException exception)
            {
            }

            return(0);
        }
示例#6
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
                    if (CanConnectToPubSub())
                    {
                        // Subscribe to the topic.
                        SubscriberServiceApiClient subscriber = CreateSubscriber();
                        var subscriptionName = new SubscriptionName(GCP_PROJECT, GCP_SUBSCRIBER);

                        PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 100);
                        foreach (ReceivedMessage received in response.ReceivedMessages)
                        {
                            PubsubMessage msg = received.Message;
                            _logger.LogInformation($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                            _logger.LogInformation($"Text: '{msg.Data.ToStringUtf8()}'");
                        }

                        if (response.ReceivedMessages.Any())
                        {
                            subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError($"{e.Message} - {e.StackTrace}");
                }

                await Task.Delay(5000, stoppingToken);
            }
        }
示例#7
0
        public async Task PurgeQueueAsync()
        {
            var topic = new TopicName(_projectId, _inputQueueName);

            try
            {
                var service = await GetPublisherServiceApiClientAsync();

                await service.DeleteTopicAsync(topic);

                Log.Info("Purged topic {topic} by deleting it", topic.ToString());
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.NotFound)
            {
                Log.Warn("Tried purging topic {topic} by deleting it, but it could not be found", topic.ToString());
            }

            _subscriptionName = SubscriptionName.FromProjectSubscription(_projectId, _inputQueueName);
            try
            {
                _subscriberClient = await GetSubscriberServiceApiClientAsync();

                await _subscriberClient.DeleteSubscriptionAsync(_subscriptionName);

                Log.Info("Purged subscription {subscriptionname} by deleting it", _subscriptionName.ToString());
            }
            catch (RpcException ex) when(ex.StatusCode == StatusCode.NotFound)
            {
                Log.Info("Tried purging subscription {subscriptionname} by deleting it, but it could not be found", _subscriptionName.ToString());
            }
        }
    public int PullMessagesSync(string projectId, string subscriptionId, bool acknowledge)
    {
        SubscriptionName           subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        SubscriberServiceApiClient subscriberClient = SubscriberServiceApiClient.Create();
        int messageCount = 0;

        try
        {
            // Pull messages from server,
            // allowing an immediate response if there are no messages.
            PullResponse response = subscriberClient.Pull(subscriptionName, returnImmediately: false, maxMessages: 20);
            // Print out each received message.
            foreach (ReceivedMessage msg in response.ReceivedMessages)
            {
                string text = System.Text.Encoding.UTF8.GetString(msg.Message.Data.ToArray());
                Console.WriteLine($"Message {msg.Message.MessageId}: {text}");
                Interlocked.Increment(ref messageCount);
            }
            // If acknowledgement required, send to server.
            if (acknowledge && messageCount > 0)
            {
                subscriberClient.Acknowledge(subscriptionName, response.ReceivedMessages.Select(msg => msg.AckId));
            }
        }
        catch (RpcException ex) when(ex.Status.StatusCode == StatusCode.Unavailable)
        {
            // UNAVAILABLE due to too many concurrent pull requests pending for the given subscription.
        }
        return(messageCount);
    }
示例#9
0
        static object PullMessagesAsync(string projectId,
                                        string subscriptionId, bool acknowledge)
        {
            // [START pubsub_subscriber_async_pull]
            SubscriptionName subscriptionName = new SubscriptionName(projectId,
                                                                     subscriptionId);
            SubscriberServiceApiClient subscriberClient = SubscriberServiceApiClient.Create();
            SubscriberClient           subscriber       = SubscriberClient.Create(
                subscriptionName, new[] { subscriberClient });

            // SubscriberClient runs your message handle function on multiple
            // threads to maximize throughput.
            subscriber.StartAsync(
                async(PubsubMessage message, CancellationToken cancel) =>
            {
                string text =
                    Encoding.UTF8.GetString(message.Data.ToArray());
                await Console.Out.WriteLineAsync(
                    $"Message {message.MessageId}: {text}");
                return(acknowledge ? SubscriberClient.Reply.Ack
                        : SubscriberClient.Reply.Nack);
            });
            // Run for 3 seconds.
            Thread.Sleep(3000);
            subscriber.StopAsync(CancellationToken.None).Wait();
            // [END pubsub_subscriber_async_pull]
            return(0);
        }
示例#10
0
    public Subscription CreateSubscriptionWithDeadLetterPolicy(string projectId, string subscriptionId, string topicId, string deadLetterTopicId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        // This is the subscription you want to create with a dead letter policy.
        var subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        // This is an existing topic that you want to attach the subscription with dead letter policy to.
        var topicName = TopicName.FromProjectTopic(projectId, topicId);
        // This is an existing topic that the subscription with dead letter policy forwards dead letter messages to.
        var deadLetterTopic     = TopicName.FromProjectTopic(projectId, deadLetterTopicId).ToString();
        var subscriptionRequest = new Subscription
        {
            SubscriptionName = subscriptionName,
            TopicAsTopicName = topicName,
            DeadLetterPolicy = new DeadLetterPolicy
            {
                DeadLetterTopic = deadLetterTopic,
                // The maximum number of times that the service attempts to deliver a
                // message before forwarding it to the dead letter topic. Must be [5-100].
                MaxDeliveryAttempts = 10
            },
            AckDeadlineSeconds = 30
        };

        var subscription = subscriber.CreateSubscription(subscriptionRequest);

        Console.WriteLine("Created subscription: " + subscription.SubscriptionName.SubscriptionId);
        Console.WriteLine($"It will forward dead letter messages to: {subscription.DeadLetterPolicy.DeadLetterTopic}");
        Console.WriteLine($"After {subscription.DeadLetterPolicy.MaxDeliveryAttempts} delivery attempts.");
        // Remember to attach a subscription to the dead letter topic because
        // messages published to a topic with no subscriptions are lost.
        return(subscription);
    }
        public void Delete(string id)
        {
            var subscriber       = SubscriberServiceApiClient.Create();
            var subscriptionName = SubscriptionName.FromProjectSubscription(ProjectId, id);

            subscriber.DeleteSubscription(subscriptionName);
        }
    public Subscription UpdateDeadLetterPolicy(string projectId, string topicId, string subscriptionId, string deadLetterTopicId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        // This is an existing topic that the subscription with dead letter policy is attached to.
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        // This is an existing subscription with a dead letter policy.
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);
        // This is an existing dead letter topic that the subscription with dead letter policy forwards
        // dead letter messages to.
        var deadLetterTopic = TopicName.FromProjectTopic(projectId, deadLetterTopicId).ToString();


        // Construct the subscription with the dead letter policy you expect to have after the update.
        // Here, values in the required fields (name, topic) help identify the subscription.
        var subscription = new Subscription
        {
            SubscriptionName = subscriptionName,
            TopicAsTopicName = topicName,
            DeadLetterPolicy = new DeadLetterPolicy
            {
                DeadLetterTopic = deadLetterTopic,
                MaxDeliveryAttempts = 20,
            }
        };

        var request = new UpdateSubscriptionRequest
        {
            Subscription = subscription,
            // Construct a field mask to indicate which field to update in the subscription.
            UpdateMask = new FieldMask { Paths = { "dead_letter_policy" } }
        };
        var updatedSubscription = subscriber.UpdateSubscription(request);
        return updatedSubscription;
    }
示例#13
0
    public Subscription RemoveDeadLetterPolicy(string projectId, string topicId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        // This is an existing topic that the subscription with dead letter policy is attached to.
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        // This is an existing subscription with dead letter policy.
        SubscriptionName subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        var subscription = new Subscription()
        {
            SubscriptionName = subscriptionName,
            TopicAsTopicName = topicName,
            DeadLetterPolicy = null
        };

        var request = new UpdateSubscriptionRequest
        {
            Subscription = subscription,
            UpdateMask   = new FieldMask {
                Paths = { "dead_letter_policy" }
            }
        };
        var updatedSubscription = subscriber.UpdateSubscription(request);

        return(updatedSubscription);
    }
示例#14
0
    public void DeleteSubscription(string projectId, string subscriptionId)
    {
        SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
        SubscriptionName           subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        subscriber.DeleteSubscription(subscriptionName);
    }
        private async Task CreateSubscription(SubscriptionName subscriptionName, TopicName topicName)
        {
            var subscriberServiceApiClient = string.IsNullOrEmpty(_pubsubEmulatorHost)
                    ? await SubscriberServiceApiClient.CreateAsync()
                    : await new SubscriberServiceApiClientBuilder
            {
                Endpoint = _pubsubEmulatorHost, ChannelCredentials = ChannelCredentials.Insecure
            }

            .BuildAsync();

            try
            {
                await subscriberServiceApiClient.CreateSubscriptionAsync(subscriptionName, topicName, pushConfig : null, ackDeadlineSeconds : 60);
            }
            catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
            {
                _logger.LogError(e, e.Message);
                ///await subscriberServiceApiClient.GetSubscriptionAsync(subscriptionName);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
示例#16
0
    public Subscription GetSubscription(string subscriptionId)
    {
        SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
        SubscriptionName           subscriptionName = SubscriptionName.FromProjectSubscription(ProjectId, subscriptionId);

        return(subscriber.GetSubscription(subscriptionName));
    }
示例#17
0
        static async Task Main(string[] args)
        {
            var projectId = "376558168506";

            AuthImplicit(projectId);

            SubscriberServiceApiClient subsClient = SubscriberServiceApiClient.Create();
            SubscriptionName           subsName   = new SubscriptionName(projectId, "westworldSubscription");
            SubscriberClient           einstein   = await SubscriberClient.CreateAsync(subsName);

            bool acknowledge = false;
            await einstein.StartAsync(
                async (PubsubMessage pubSubMessage, CancellationToken cancel) =>
            {
                string msg = Encoding.UTF8.GetString(pubSubMessage.Data.ToArray());


                await Console.Out.WriteLineAsync($"{pubSubMessage.MessageId}: {msg}");

                if (msg.Length > 1)
                {
                    acknowledge = true;
                }
                return(acknowledge ? SubscriberClient.Reply.Ack : SubscriberClient.Reply.Nack);
            });

            Thread.Sleep(5000);
            einstein.StopAsync(CancellationToken.None).Wait();
        }
示例#18
0
    public Subscription CreateSubscriptionWithOrdering(string projectId, string subscriptionId, string topicId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        var topicName        = TopicName.FromProjectTopic(projectId, topicId);
        var subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        var subscriptionRequest = new Subscription
        {
            SubscriptionName      = subscriptionName,
            TopicAsTopicName      = topicName,
            EnableMessageOrdering = true
        };

        Subscription subscription = null;

        try
        {
            subscription = subscriber.CreateSubscription(subscriptionRequest);
        }
        catch (RpcException e) when(e.Status.StatusCode == StatusCode.AlreadyExists)
        {
            // Already exists.  That's fine.
        }
        return(subscription);
    }
    public IEnumerable <Subscription> ListSubscriptions(string projectId)
    {
        SubscriberServiceApiClient subscriber = SubscriberServiceApiClient.Create();
        ProjectName projectName   = ProjectName.FromProject(projectId);
        var         subscriptions = subscriber.ListSubscriptions(projectName);

        return(subscriptions);
    }
        public IActionResult Get()
        {
            var subscriber    = SubscriberServiceApiClient.Create();
            var projectName   = ProjectName.FromProject(ProjectId);
            var subscriptions = subscriber.ListSubscriptions(projectName);

            return(Ok(subscriptions));
        }
        public IActionResult Get(string id)
        {
            var subscriber       = SubscriberServiceApiClient.Create();
            var subscriptionName = SubscriptionName.FromProjectSubscription(ProjectId, id);
            var subscription     = subscriber.GetSubscription(subscriptionName);

            return(Ok(subscription));
        }
示例#22
0
        private bool GetSubscriber(out SubscriberServiceApiClient APIClientVar, out SubscriptionName SubscriptionNameVar, string GoogleFriendlyTopicName, Action <string> _ErrorMessageAction = null)
        {
            lock (LockableSubscriberTopicListObject(GoogleFriendlyTopicName))
            {
                APIClientVar        = null;
                SubscriptionNameVar = null;

                var TopicInstance = new TopicName(ProjectID, GoogleFriendlyTopicName);

                if (!EnsureTopicExistence(TopicInstance, null, _ErrorMessageAction))
                {
                    return(false);
                }

                try
                {
                    APIClientVar = SubscriberServiceApiClient.Create(SubscribeChannel);
                }
                catch (Exception e)
                {
                    APIClientVar = null;
                    _ErrorMessageAction?.Invoke("BPubSubServiceGC->GetSubscriber: " + e.Message + ", Trace: " + e.StackTrace);
                    return(false);
                }

                string SubscriptionIDBase        = GoogleFriendlyTopicName + "-";
                int    SubscriptionIDIncrementer = 1;
                SubscriptionNameVar = new SubscriptionName(ProjectID, SubscriptionIDBase + SubscriptionIDIncrementer);

                bool bSubscriptionSuccess = false;
                while (!bSubscriptionSuccess)
                {
                    try
                    {
                        APIClientVar.CreateSubscription(SubscriptionNameVar, TopicInstance, null, 600);
                        bSubscriptionSuccess = true;
                    }
                    catch (Exception e)
                    {
                        if (e is RpcException && (e as RpcException).Status.StatusCode == StatusCode.AlreadyExists)
                        {
                            SubscriptionIDIncrementer++;
                            SubscriptionNameVar = new SubscriptionName(ProjectID, SubscriptionIDBase + SubscriptionIDIncrementer);
                        }
                        else
                        {
                            SubscriptionNameVar = null;
                            _ErrorMessageAction?.Invoke("BPubSubServiceGC->GetSubscriber: " + e.Message + ", Trace: " + e.StackTrace);
                            return(false);
                        }
                    }
                }

                SubscriberTopicList.Add(new BTuple <string, SubscriberServiceApiClient, SubscriptionName>(GoogleFriendlyTopicName, APIClientVar, SubscriptionNameVar));

                return(true);
            }
        }
        public void Post([FromBody] CreateTopicRequest request)
        {
            var subscriber = SubscriberServiceApiClient.Create();
            var topicName  = TopicName.FromProjectTopic(ProjectId, request.TopicId);

            var subscriptionName = SubscriptionName.FromProjectSubscription(ProjectId, request.SubscriptionId);

            subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);
        }
示例#24
0
        public void Overview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: Overview
            // First create a topic.
            PublisherServiceApiClient publisher = PublisherServiceApiClient.Create();
            TopicName topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
            SubscriptionName           subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriber.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic.
            PubsubMessage message = new PubsubMessage
            {
                // The data is any arbitrary ByteString. Here, we're using text.
                Data = ByteString.CopyFromUtf8("Hello, Pubsub"),
                // The attributes provide metadata in a string-to-string dictionary.
                Attributes =
                {
                    { "description", "Simple text message" }
                }
            };

            publisher.Publish(topicName, new[] { message });

            // Pull messages from the subscription. We're returning immediately, whether or not there
            // are messages; in other cases you'll want to allow the call to wait until a message arrives.
            PullResponse response = subscriber.Pull(subscriptionName, returnImmediately: true, maxMessages: 10);

            foreach (ReceivedMessage received in response.ReceivedMessages)
            {
                PubsubMessage msg = received.Message;
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
            }

            // Acknowledge that we've received the messages. If we don't do this within 60 seconds (as specified
            // when we created the subscription) we'll receive the messages again when we next pull.
            subscriber.Acknowledge(subscriptionName, response.ReceivedMessages.Select(m => m.AckId));

            // Tidy up by deleting the subscription and the topic.
            subscriber.DeleteSubscription(subscriptionName);
            publisher.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, response.ReceivedMessages.Count);
            Assert.Equal("Hello, Pubsub", response.ReceivedMessages[0].Message.Data.ToStringUtf8());
            Assert.Equal("Simple text message", response.ReceivedMessages[0].Message.Attributes["description"]);
        }
示例#25
0
        public async Task SimpleOverview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            // Sample: SimpleOverview
            // First create a topic.
            PublisherServiceApiClient publisherService = await PublisherServiceApiClient.CreateAsync();

            TopicName topicName = new TopicName(projectId, topicId);

            publisherService.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberServiceApiClient subscriberService = await SubscriberServiceApiClient.CreateAsync();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            subscriberService.CreateSubscription(subscriptionName, topicName, pushConfig: null, ackDeadlineSeconds: 60);

            // Publish a message to the topic using PublisherClient.
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync("Hello, Pubsub");

            // PublisherClient instance should be shutdown after use.
            // The TimeSpan specifies for how long to attempt to publish locally queued messages.
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

            // Pull messages from the subscription using SimpleSubscriber.
            SubscriberClient subscriber = await SubscriberClient.CreateAsync(subscriptionName);

            List <PubsubMessage> receivedMessages = new List <PubsubMessage>();
            // Start the subscriber listening for messages.
            await subscriber.StartAsync((msg, cancellationToken) =>
            {
                receivedMessages.Add(msg);
                Console.WriteLine($"Received message {msg.MessageId} published at {msg.PublishTime.ToDateTime()}");
                Console.WriteLine($"Text: '{msg.Data.ToStringUtf8()}'");
                // Stop this subscriber after one message is received.
                // This is non-blocking, and the returned Task may be awaited.
                subscriber.StopAsync(TimeSpan.FromSeconds(15));
                // Return Reply.Ack to indicate this message has been handled.
                return(Task.FromResult(SubscriberClient.Reply.Ack));
            });

            // Tidy up by deleting the subscription and the topic.
            subscriberService.DeleteSubscription(subscriptionName);
            publisherService.DeleteTopic(topicName);
            // End sample

            Assert.Equal(1, receivedMessages.Count);
            Assert.Equal("Hello, Pubsub", receivedMessages[0].Data.ToStringUtf8());
        }
示例#26
0
        protected BaseSubscriber(IGCPConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            ProjectId  = configuration.ProjectId;
            Subscriber = SubscriberServiceApiClient.Create();
        }
        public void DownloadEmailFromQueueAndSend()
        {
            SubscriberServiceApiClient client = SubscriberServiceApiClient.Create();

            var s            = CreateGetSubscription();                  //This must be called before being able to read messages from Topic/Queue
            var pullResponse = client.Pull(s.SubscriptionName, true, 1); //Reading the message on top; You can read more than just 1 at a time

            if (pullResponse != null)
            {
                string  toDeserialize = pullResponse.ReceivedMessages[0].Message.Data.ToStringUtf8(); //extracting the first message since in the previous line it was specified to read one at a time. if you decide to read more then a loop is needed
                Product deserialized  = JsonSerializer.Deserialize <Product>(toDeserialize);          //Deserializing since when we published it we serialized it

                //MailMessage mm = new MailMessage();  //Message on queue/topic will consist of a ready made email with the desired content, you can upload anything which is serializable
                //mm.To.Add(deserialized.OwnerFK);
                //mm.From = new MailAddress("*****@*****.**");
                //mm.Subject = "New Product In Inventory";
                //mm.Body = $"Name:{deserialized.Name}; Price {deserialized.Price};";


                //SmtpClient mailserver = new SmtpClient("smtp.gmail.com", 587);
                //mailserver.Credentials =

                //mailserver.Send(mm);


                //Send Email with deserialized. Documentation: https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8
                MailMessage message = new MailMessage();
                SmtpClient  smtp    = new SmtpClient();
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress(deserialized.OwnerFK));
                message.Subject    = "New Product In Inventory";
                message.IsBodyHtml = true;     //to make message body as html

                var    cipher    = KeyRepository.Encrypt($"Name:{deserialized.Name}; File {deserialized.Name}; Link {deserialized.File}; ");
                string realvalue = KeyRepository.Decrypt(cipher);
                message.Body = realvalue;     //$"Name:{deserialized.Name}; File {deserialized.Name}; Link {deserialized.File}; ";

                smtp.Port                  = 587;
                smtp.Host                  = "smtp.gmail.com"; //for gmail host
                smtp.EnableSsl             = true;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new NetworkCredential("*****@*****.**", "PfcAssignment");

                //go on google while you are logged in in this account > search for lesssecureapps > turn it to on

                smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                smtp.Send(message);


                List <string> acksIds = new List <string>();
                acksIds.Add(pullResponse.ReceivedMessages[0].AckId); //after the email is sent successfully you acknolwedge the message so it is confirmed that it was processed

                client.Acknowledge(s.SubscriptionName, acksIds.AsEnumerable());
            }
        }
    public void UpdatePushConfiguration(string projectId, string subscriptionId, string pushEndpoint)
    {
        SubscriberServiceApiClient subscriber       = SubscriberServiceApiClient.Create();
        SubscriptionName           subscriptionName = SubscriptionName.FromProjectSubscription(projectId, subscriptionId);

        PushConfig pushConfig = new PushConfig {
            PushEndpoint = pushEndpoint
        };

        subscriber.ModifyPushConfig(subscriptionName, pushConfig);
    }
示例#29
0
        static SubscriberClient GetSubscriber(string projectId,
                                              string subscriptionId)
        {
            SubscriptionName subscriptionName = new SubscriptionName(projectId,
                                                                     subscriptionId);
            SubscriberServiceApiClient subscriberClient = SubscriberServiceApiClient.Create();
            SubscriberClient           subscriber       = SubscriberClient.Create(
                subscriptionName, new[] { subscriberClient });

            return(subscriber);
        }
示例#30
0
        private async Task CreateTopicAndSubscription(TopicName topicName, SubscriptionName subscriptionName)
        {
            // Create topic
            var publisherApi = await PublisherServiceApiClient.CreateAsync().ConfigureAwait(false);

            await publisherApi.CreateTopicAsync(topicName).ConfigureAwait(false);

            // Subscribe to the topic
            var subscriberApi = await SubscriberServiceApiClient.CreateAsync().ConfigureAwait(false);

            await subscriberApi.CreateSubscriptionAsync(subscriptionName, topicName, null, 60).ConfigureAwait(false);
        }