private async Task <PublisherClient> CreatePublisher(TopicName topicName)
 {
     // Publish a message to the topic using PublisherClient.
     return(string.IsNullOrEmpty(_pubsubEmulatorHost)
         ? await PublisherClient.CreateAsync(topicName)
         : await PublisherClient.CreateAsync(topicName, clientCreationSettings : new PublisherClient.ClientCreationSettings(credentials: ChannelCredentials.Insecure, serviceEndpoint: _pubsubEmulatorHost)));
 }
Exemplo n.º 2
0
        public void PublishMessage([FromBody] Message message)
        {
            var topicName = TopicName.FromProjectTopic(ProjectId, message.TopicId);
            var publisher = PublisherClient.CreateAsync(topicName).Result;

            publisher.PublishAsync(message.Text);
        }
Exemplo n.º 3
0
    public async Task PublishMessageWithRetrySettingsAsync(string projectId, string topicId, string messageText)
    {
        TopicName topicName = TopicName.FromProjectTopic(projectId, topicId);
        // Retry settings control how the publisher handles retry-able failures
        var maxAttempts       = 3;
        var initialBackoff    = TimeSpan.FromMilliseconds(110); // default: 100 ms
        var maxBackoff        = TimeSpan.FromSeconds(70);       // default : 60 seconds
        var backoffMultiplier = 1.3;                            // default: 1.0
        var totalTimeout      = TimeSpan.FromSeconds(100);      // default: 600 seconds

        var publisher = await PublisherClient.CreateAsync(topicName,
                                                          clientCreationSettings : new PublisherClient.ClientCreationSettings(
                                                              publisherServiceApiSettings: new PublisherServiceApiSettings
        {
            PublishSettings = CallSettings.FromRetry(RetrySettings.FromExponentialBackoff(
                                                         maxAttempts: maxAttempts,
                                                         initialBackoff: initialBackoff,
                                                         maxBackoff: maxBackoff,
                                                         backoffMultiplier: backoffMultiplier,
                                                         retryFilter: RetrySettings.FilterForStatusCodes(StatusCode.Unavailable)))
                              .WithTimeout(totalTimeout)
        }
                                                              )).ConfigureAwait(false);

        string message = await publisher.PublishAsync(messageText);

        Console.WriteLine($"Published message {message}");
    }
        public async Task <bool> PublishAsync(Event[] message, string topicName)
        {
            try{
                TopicName       topic = new TopicName(_busSettings.ProjectId, topicName);
                PublisherClient publisher;
                publisher = await PublisherClient.CreateAsync(topic);

                var pubSubMessage = new PubsubMessage {
                    Data = ByteString.CopyFrom(JsonConvert.SerializeObject(message), Encoding.UTF8)
                };
                if (_busSettings.Token != null && _busSettings.Token != "")
                {
                    pubSubMessage.Attributes["token"] = _busSettings.Token;
                }
                var result = await publisher.PublishAsync(pubSubMessage);

                if (result == "")
                {
                    return(false);
                }
                return(true);
            } catch (Exception ex) {
                return(false);
            }
        }
Exemplo n.º 5
0
        public async Task InitializeAsync(
            CancellationToken ct)
        {
            var topicName = new TopicName(options.ProjectId, $"{options.Prefix}{topicId}");

            publisherClient = await PublisherClient.CreateAsync(topicName);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Index(UploadViewModel model)
        {
            if (!ModelState.IsValid)
            {
                model.Errors = "All fields are required!";
                return(View(model));
            }

            var image = model.Image.OpenReadStream();

            var fighterType = await _imageDescriptor.GetFighterTypeAsync(image);

            if (!fighterType.HasValue)
            {
                model.Errors = "Please upload an image of either a dog or a cat";
                return(View(model));
            }

            var fighterId = await _dataService.SaveFighterAsync(new Fighter { Name = model.Name },
                                                                image, model.Image.ContentType, fighterType.Value);

            TopicName       topicName = new TopicName(_config.ProjectId, _config.Topic);
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            string messageId = await publisher.PublishAsync(fighterId);

            _logger.LogInformation($"Published message : {messageId}");

            return(View(new UploadViewModel {
                IsSuccess = true
            }));
        }
Exemplo n.º 7
0
        public async Task Initialize()
        {
            try
            {
                _publisher = await PublisherClient.CreateAsync(_customEndpoint);
            }
            catch (Exception e)
            {
                ReportErrorAndRethrow(e, "CreateAsync", GoogleErrorCode.Initializing);
            }

            bool didCreate = false;

            try
            {
                _topic = await _publisher.CreateTopicAsync(TopicName);

                didCreate = true;
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode != StatusCode.AlreadyExists)
                {
                    ReportErrorAndRethrow(e, "CreateTopicAsync", GoogleErrorCode.Initializing);
                }

                _topic = await _publisher.GetTopicAsync(TopicName);
            }

            _logger.LogInformation((int)GoogleErrorCode.Initializing, "{Verb} Google PubSub Topic {TopicId}", (didCreate ? "Created" : "Attached to"), TopicName.TopicId);

            didCreate = false;

            try
            {
                _subscriber = await SubscriberClient.CreateAsync(_customEndpoint);

                _subscription = await _subscriber.CreateSubscriptionAsync(SubscriptionName, TopicName, pushConfig : null,
                                                                          ackDeadlineSeconds : _deadline.HasValue?(int)_deadline.Value.TotalSeconds : 60);

                didCreate = true;
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode != StatusCode.AlreadyExists)
                {
                    ReportErrorAndRethrow(e, "CreateSubscriptionAsync", GoogleErrorCode.Initializing);
                }

                _subscription = await _subscriber.GetSubscriptionAsync(SubscriptionName);
            }

            _logger.LogInformation(
                (int)GoogleErrorCode.Initializing,
                "{Verb} Google PubSub Subscription {SubscriptionId} to Topic {TopicId}",
                (didCreate ? "Created" : "Attached to"),
                SubscriptionName.SubscriptionId,
                TopicName.TopicId);
        }
Exemplo n.º 8
0
        public SpeedTestEvents(string projectId, string topicId)
        {
            var publisherClient = PublisherServiceApiClient.Create();

            _publisher = PublisherClient.CreateAsync(
                new TopicName(projectId, topicId))
                         .GetAwaiter().GetResult();
        }
Exemplo n.º 9
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddSingleton <FirestoreDb>(
         provider => FirestoreDb.Create(GetFirestoreProjectId()));
     services.AddSingleton <PublisherClient>(
         provider => PublisherClient.CreateAsync(new TopicName(
                                                     GetProjectId(), GetTopicName())).Result);
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 }
Exemplo n.º 10
0
        public async Task <int> PublishMessagesAsync(string projectId, string topicId, IEnumerable <string> messageTexts)
        {
            TopicName       topicName = TopicName.FromProjectTopic(projectId, topicId);
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName,
                                                                          new PublisherClient.ClientCreationSettings(credentials: this.channelCredentials));

            int publishedMessageCount = 0;
            var publishTasks          = messageTexts.Select(async text =>
            {
                try
                {
                    string message = await publisher.PublishAsync(text);
                    Console.WriteLine($"Published message {message}");
                    Interlocked.Increment(ref publishedMessageCount);
                }
                catch (Exception exception)
                {
                    Console.WriteLine($"An error ocurred when publishing message {text}: {exception.Message}");
                }
            });

            await Task.WhenAll(publishTasks);

            return(publishedMessageCount);



            //clientCreationSettings.Credentials
            //PublisherServiceApiSettings publisherServiceApiSettings = new PublisherServiceApiSettings();



            //clientCreationSettings.PublisherServiceApiSettings
            //clientCreationSettings.Credentials


            //Channel channel = new Channel(
            //    PublisherClient.DefaultEndpoint.Host,
            //    PublisherClient.DefaultEndpoint.Port,
            //    googleCredential.ToChannelCredentials());
            //PublisherClient publisher2 = await PublisherClient.CreateAsync(topicName, clientCreationSettings, settings);



            //PublisherServiceApiClientBuilder bld = new PublisherServiceApiClientBuilder();
            //var credential = GoogleCredential.FromJson(@"{""your_credentials_json_itself"":""here""}");
            //var channel = new Grpc.Core.Channel(PublisherServiceApiClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());

            //PublisherServiceApiClient.DefaultScopes

            //var publisher3 = bld.
            //PublisherServiceApiClientBuilder x = new PublisherServiceApiClientBuilder
            //{
            //    CredentialsPath = jsonPath
            //};
            //PublisherServiceApiClient client = x.Build();
        }
Exemplo n.º 11
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());
        }
Exemplo n.º 12
0
        static public async Task publishMessage(string company)
        {
            List <string> test = new List <string>();

            test.Add(company);
            Console.WriteLine("dit is in de payment service publishmessage:" + test[0]);
            publisherclient = await PublisherClient.CreateAsync(new TopicName("pts6-bijbaan", "paypal-generic"));

            await Domain.Publisher.PublishMessagesAsync(publisherclient, test);
        }
        public static async Task <PublisherClient> GetPublisherAsync(string projectId,
                                                                     string topicId)
        {
            // [START pubsub_publish]
            PublisherClient publisher = await PublisherClient.CreateAsync(
                new TopicName(projectId, topicId));

            // [END pubsub_publish]
            return(publisher);
        }
Exemplo n.º 14
0
        public async static Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Environment.SetEnvironmentVariable(
                "GOOGLE_APPLICATION_CREDENTIALS",
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "My First Project-065d320bab2e.json"));
            CompanyServiceClient companyServiceClient = CompanyServiceClient.Create();

            // GoogleCredential credential = GoogleCredential.GetApplicationDefault();
            Google.Cloud.Talent.V4Beta1.Company c = new Google.Cloud.Talent.V4Beta1.Company
            {
                Name        = "ADI",
                DisplayName = "ADI",

                ExternalId = "123"
            };
            Google.Cloud.Talent.V4Beta1.CreateCompanyRequest request = new Google.Cloud.Talent.V4Beta1.CreateCompanyRequest
            {
                Company = c
            };

            Google.Cloud.Talent.V4Beta1.Company response = companyServiceClient.CreateCompany(request);
            Console.WriteLine("Created Company");
            Console.WriteLine($"Name: {response.Name}");
            Console.WriteLine($"Display Name: {response.DisplayName}");
            Console.WriteLine($"External ID: {response.ExternalId}");

            //JobServiceClient jobServiceClient = JobServiceClient.Create();
            // TenantName tenantName = TenantName.FromProjectTenant(projectId, tenantId);
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName, null, null);

            var pubsubMessage = new PubsubMessage()
            {
                Data = ByteString.CopyFromUtf8("this is new  sample message")
            };
            string messageId = await publisher.PublishAsync(pubsubMessage);

            var subscriptionName = new SubscriptionName(ProjectId, SubscriptionId);
            var subscription     = await SubscriberClient.CreateAsync(subscriptionName);

            try
            {
                // PullResponse response = subscription.(subscriptionName, true, 10);
                await subscription.StartAsync((pubsubMessage, cancellationToken) =>
                {
                    // Process the message here.
                    var all = Task.FromResult(SubscriberClient.Reply.Ack);
                    return(all);
                });
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong: {0}", e.Message);
            }
        }
Exemplo n.º 15
0
        public async Task Write(string eventData, HttpContext context)
        {
            var topicName = new TopicName(_projectId, _topicId);

            _logger.LogInformation($"Publishing to topic '{_topicId}' with data '{eventData}");
            var publisher = await PublisherClient.CreateAsync(topicName);

            await publisher.PublishAsync(eventData);

            await publisher.ShutdownAsync(TimeSpan.FromSeconds(10));
        }
Exemplo n.º 16
0
 private void InitializeQueue(string topicName)
 {
     if (_publisher == null)
     {
         var googleCredential = GoogleCredential.FromFile(_queueSetting.CredentialFile);
         var createSettings   = new PublisherClient.ClientCreationSettings(credentials: googleCredential.ToChannelCredentials());
         var toppicName       = new TopicName(_queueSetting.ProjectId, topicName);
         var publisher        = PublisherClient.CreateAsync(toppicName, createSettings);
         _publisher = publisher.Result;
     }
 }
Exemplo n.º 17
0
        public async Task OnUserRegistered(UserDto user)
        {
            var tmp = new PublisherClient.ClientCreationSettings();

            var publisher = await PublisherClient.CreateAsync(topicName);

            var body = JsonSerializer.Serialize(user);

            string messageId = await publisher.PublishAsync(body);

            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));
        }
Exemplo n.º 18
0
        private async Task <PublisherClient> TryGetPublisherClient(string topic)
        {
            var topicName = new TopicName(m_projectId, topic);

            if (!m_publisherClients.TryGetValue(topicName, out PublisherClient client))
            {
                client = await PublisherClient.CreateAsync(topicName);

                m_publisherClients.Add(topicName, client);
            }

            return(client);
        }
        public async Task GetIamPolicyAsync()
        {
            // Snippet: GetIamPolicyAsync(string,CallSettings)
            // Additional: GetIamPolicyAsync(string,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
            // Make the request
            Policy response = await publisherClient.GetIamPolicyAsync(formattedResource);

            // End snippet
        }
Exemplo n.º 20
0
        private async Task <string> PublishAsync <T>(TopicName topicName, string emulatorHostAndPort, T message)
        {
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName,
                                                                          new PublisherClient.ClientCreationSettings(null, null, ChannelCredentials.Insecure, emulatorHostAndPort));

            // PublishAsync() has various overloads. Here we're using the string overload.
            string messageId = await publisher.PublishAsync(serializer(message), System.Text.Encoding.UTF8);

            // 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)); //?

            return(messageId);
        }
        public async Task DeleteTopicAsync()
        {
            // Snippet: DeleteTopicAsync(TopicName,CallSettings)
            // Additional: DeleteTopicAsync(TopicName,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            await publisherClient.DeleteTopicAsync(topic);

            // End snippet
        }
Exemplo n.º 22
0
    public async Task CreateQueueIfNecessary(QueueBindings queueBindings, string identity)
    {
        var client = await PublisherClient.CreateAsync()
                     .ConfigureAwait(false);

        var addresses = queueBindings.ReceivingAddresses.Concat(queueBindings.SendingAddresses).ToArray();
        var tasks     = new List <Task>(addresses.Length);

        foreach (var address in addresses)
        {
            tasks.Add(CreateTopic(client, projectId, address));
        }
        await Task.WhenAll(tasks)
        .ConfigureAwait(false);
    }
        public async Task TestIamPermissionsAsync()
        {
            // Snippet: TestIamPermissionsAsync(string,IEnumerable<string>,CallSettings)
            // Additional: TestIamPermissionsAsync(string,IEnumerable<string>,CancellationToken)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            string formattedResource         = new TopicName("[PROJECT]", "[TOPIC]").ToString();
            IEnumerable <string> permissions = new List <string>();
            // Make the request
            TestIamPermissionsResponse response = await publisherClient.TestIamPermissionsAsync(formattedResource, permissions);

            // End snippet
        }
Exemplo n.º 24
0
        public void PublishMessage(string message)
        {
            try
            {
                var topicName = new TopicName(EnvResources.ProjectId, EnvResources.TopicId);
                var publisher = PublisherClient.CreateAsync(topicName).Result;
                var messageId = publisher.PublishAsync(message).Result;

                publisher.ShutdownAsync(TimeSpan.FromSeconds(15));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Exemplo n.º 25
0
        public async void PublishAuthor(Author author)
        {
            var topicName = new TopicName(_pubsubSettings.Value.ProjectId, _pubsubSettings.Value.PushTopicId);

            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            var json    = JsonConvert.SerializeObject(author);
            var message = new PubsubMessage()
            {
                Data = ByteString.CopyFromUtf8(json)
            };

            // Publish it
            var response = publisher.PublishAsync(message);
        }
Exemplo n.º 26
0
        private async Task RunPublisherAsync()
        {
            // The GOOGLE_APPLICATION_CREDENTIALS environment variable contains the path to the
            // key json file.
            // string value = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
            // var credential = await GoogleCredential.GetApplicationDefaultAsync();

            // Make sure you topicId doesn't contain '/' symbols.
            var projectId = "{YOUR-PROJECT-ID}";
            var topicId   = "{YOUR-TOPIC-ID}";
            var topicName = new TopicName(projectId, topicId);
            var topic     = await PublisherClient.CreateAsync(topicName);

            var pubSubMessage = CreatePubSubMessage("Hello Ilya! This is my first message.");
            await topic.PublishAsync(pubSubMessage);
        }
        public async Task OversizedMessage()
        {
            var topicId = _fixture.CreateTopicId();
            // Create topic
            var topicName = new TopicName(_fixture.ProjectId, topicId);
            var publisher = await PublisherClient.CreateAsync().ConfigureAwait(false);

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

            // Create SimplePublisher
            var simplePublisher = await SimplePublisher.CreateAsync(topicName).ConfigureAwait(false);

            // Create oversized message
            Random rnd = new Random(1234);

            byte[] msg = new byte[10_000_001];
        public async Task GetIamPolicyAsync_RequestObject()
        {
            // Snippet: GetIamPolicyAsync(GetIamPolicyRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            GetIamPolicyRequest request = new GetIamPolicyRequest
            {
                Resource = new TopicName("[PROJECT]", "[TOPIC]").ToString(),
            };
            // Make the request
            Policy response = await publisherClient.GetIamPolicyAsync(request);

            // End snippet
        }
        public async Task DeleteTopicAsync_RequestObject()
        {
            // Snippet: DeleteTopicAsync(DeleteTopicRequest,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            DeleteTopicRequest request = new DeleteTopicRequest
            {
                TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            await publisherClient.DeleteTopicAsync(request);

            // End snippet
        }
        public async Task CreateTopicAsync_RequestObject()
        {
            // Snippet: CreateTopicAsync(Topic,CallSettings)
            // Create client
            PublisherClient publisherClient = await PublisherClient.CreateAsync();

            // Initialize request argument(s)
            Topic request = new Topic
            {
                TopicName = new TopicName("[PROJECT]", "[TOPIC]"),
            };
            // Make the request
            Topic response = await publisherClient.CreateTopicAsync(request);

            // End snippet
        }