Exemplo n.º 1
0
        public override void Dispose()
        {
            var client = StorageClient.Create();

            foreach (var bucket in _bucketsToDelete)
            {
                var objects = client.ListObjects(bucket, null, new ListObjectsOptions {
                    Versions = true
                }).ToList();
                foreach (var obj in objects)
                {
                    client.DeleteObject(obj, new DeleteObjectOptions {
                        Generation = obj.Generation
                    });
                }
                client.DeleteBucket(bucket);
                SleepAfterBucketCreateDelete();
            }
            foreach (var file in _localFilesToDelete)
            {
                File.Delete(file);
            }
            var publisherClient = PublisherClient.Create();

            _topicsToDelete.ForEach(topicName => publisherClient.DeleteTopic(topicName));
        }
        public void CreatePubSubTopic(TopicName topicName)
        {
            var publisher = PublisherClient.Create();

            try
            {
                publisher.CreateTopic(topicName);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                }
            Policy policy = new Policy
            {
                Bindings =
                {
                    new Binding {
                        Role    = "roles/pubsub.publisher",
                        Members ={ ServiceAccount   }
                    }
                }
            };
            SetIamPolicyRequest request = new SetIamPolicyRequest
            {
                Resource = $"projects/{ProjectId}/topics/{topicName.TopicId}",
                Policy   = policy
            };
            Policy response = publisher.SetIamPolicy(request);

            Console.WriteLine($"Topic IAM Policy updated: {response}");
        }
        public async Task ListTopicsAsync()
        {
            // Snippet: ListTopicsAsync(string,string,int?,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            string formattedProject = PublisherClient.FormatProjectName("[PROJECT]");
            // Make the request
            IPagedAsyncEnumerable <ListTopicsResponse, Topic> response =
                publisherClient.ListTopicsAsync(formattedProject);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((Topic item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;
            IAsyncEnumerable <FixedSizePage <Topic> > fixedSizePages = response.AsPages().WithFixedSize(pageSize);
            await fixedSizePages.ForEachAsync((FixedSizePage <Topic> page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (Topic item in page)
                {
                    Console.WriteLine(item);
                }
            });

            // End snippet
        }
Exemplo n.º 4
0
        public void WithFixedSize()
        {
            string projectId            = _fixture.ProjectId;
            string pageTokenFromRequest = "";

            // Sample: WithFixedSize
            PublisherClient client      = PublisherClient.Create();
            string          projectName = PublisherClient.FormatProjectName(projectId);
            IPagedEnumerable <ListTopicsResponse, Topic> topics = client.ListTopics(projectName, pageTokenFromRequest);

            IEnumerable <FixedSizePage <Topic> > fixedSizePages = topics.AsPages().WithFixedSize(3);
            // With fixed size pages, if there are no more resources, there are no more pages.
            FixedSizePage <Topic> nextPage = fixedSizePages.FirstOrDefault();

            if (nextPage != null)
            {
                // In a web application, this would be a matter of including the topics in the web page.
                foreach (Topic topic in nextPage)
                {
                    Console.WriteLine(topic.Name);
                }
                // ... and embedding the next page token into a "next page" link.
                Console.WriteLine($"Next page token: {nextPage.NextPageToken}");
            }
            // End sample
        }
Exemplo n.º 5
0
        public static object SetSubscriptionIamPolicy(string projectId,
                                                      string subscriptionId, string role, string member)
        {
            PublisherClient publisher             = PublisherClient.Create();
            string          roleToBeAddedToPolicy = $"roles/{role}";
            // [START pubsub_set_subscription_policy]
            Policy policy = new Policy
            {
                Bindings =
                {
                    new Binding {
                        Role    = roleToBeAddedToPolicy,
                        Members ={ member   }
                    }
                }
            };
            SetIamPolicyRequest request = new SetIamPolicyRequest
            {
                Resource = new SubscriptionName(projectId, subscriptionId).ToString(),
                Policy   = policy
            };
            Policy response = publisher.SetIamPolicy(request);

            Console.WriteLine($"Subscription IAM Policy updated: {response}");
            // [END pubsub_set_subscription_policy]
            return(0);
        }
        /// <summary>
        /// Initializes the pull worker.
        /// </summary>
        /// <returns></returns>
        public bool InitializePullWorker()
        {
            bool bStatus = false;

            _redis   = ConnectionMultiplexer.Connect(DefaultRedisServerAddress);
            _redisDB = _redis.GetDatabase();

            CurrentTopicName = new TopicName(DefaultProjectId, DefaultTopicName);
            _subscriber      = SubscriberClient.Create();
            //String  subscriptionId = "projects/pushnotificationpoc-19baf/subscriptions/myTestReader";

            _publisher        = PublisherClient.Create();
            _subscriptionName = new SubscriptionName(DefaultProjectId, DefaultSubscriptionId);
            String t = _subscriptionName.ToString();

            try
            {
                _subscriber.CreateSubscription(_subscriptionName, CurrentTopicName, pushConfig: null, ackDeadlineSeconds: 60);
            }
            catch (RpcException e)
            {
                if (e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                    _bSubscriptionAllreadyExists = true;
                }
            }

            return(bStatus);
        }
Exemplo n.º 7
0
        public static void Main(string[] args)
        {
            // Instantiates a client
            PublisherClient publisher = PublisherClient.Create();

            // Your Google Cloud Platform project ID
            string projectId = "YOUR-PROJECT-ID";

            // [END pubsub_quickstart]
            Debug.Assert(projectId != "YOUR-PROJECT" + "-ID",
                         "Edit Program.cs and replace YOUR-PROJECT-ID with your project id.");
            // [START pubsub_quickstart]

            // The name for the new topic
            var topicName = new TopicName(projectId, "my-new-topic");

            // Creates the new topic
            try
            {
                Topic topic = publisher.CreateTopic(topicName);
                Console.WriteLine($"Topic {topic.Name} created.");
            }
            catch (Grpc.Core.RpcException e)
                when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
                {
                    Console.WriteLine($"Topic {topicName} already exists.");
                }
        }
Exemplo n.º 8
0
        private void CheckTopic()
        {
            if (_publishers.ContainsKey(_topicName))
            {
                _publishers.TryGetValue(_topicName, out PublisherClient client);

                if (client == null)
                {
                    client = PublisherClient.Create(new TopicName(_options.ProjectId, _topicName), new[] { _serviceApiClient });

                    _publishers.Remove(_topicName);
                    _publishers.Add(_topicName, client);
                }
            }
            else
            {
                _topic = new TopicName(_options.ProjectId, _topicName);

                try
                {
                    _serviceApiClient.CreateTopic(_topic);
                    CheckSubscription();
                }
                catch (RpcException e)
                    when(e.Status.StatusCode == StatusCode.AlreadyExists)
                    {
                        //topico já existe
                    }

                var client = PublisherClient.Create(new TopicName(_options.ProjectId, _topicName), new[] { _serviceApiClient });

                _publishers.Add(_topicName, client);
            }
        }
Exemplo n.º 9
0
        private void DeletePubSubTopic(String name)
        {
            var publisher = PublisherClient.Create();
            var topicName = new TopicName(s_projectId, name);

            publisher.DeleteTopic(topicName);
        }
Exemplo n.º 10
0
        public void Publish()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Snippet: Publish(*,*,*)
            PublisherClient client = PublisherClient.Create();
            // Make sure we have a topic to publish to
            TopicName topicName = new TopicName(projectId, topicId);

            client.CreateTopic(topicName);

            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" }
                }
            };

            client.Publish(topicName, new[] { message });
            // End snippet
        }
        public async Task PublishAsync()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Snippet: PublishAsync(*,*,CallSettings)
            // Additional: PublishAsync(*,*,CancellationToken)
            PublisherClient client = PublisherClient.Create();
            // Make sure we have a topic to publish to
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);
            await client.CreateTopicAsync(topicName);

            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" }
                }
            };
            await client.PublishAsync(topicName, new[] { message });

            // End snippet
        }
        public void ListTopicSubscriptions()
        {
            // Snippet: ListTopicSubscriptions(string,string,int?,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            string formattedTopic = PublisherClient.FormatTopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            IPagedEnumerable <ListTopicSubscriptionsResponse, string> response =
                publisherClient.ListTopicSubscriptions(formattedTopic);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (string item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over fixed-sized pages, lazily performing RPCs as required
            int pageSize = 10;

            foreach (FixedSizePage <string> page in response.AsPages().WithFixedSize(pageSize))
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (string item in page)
                {
                    Console.WriteLine(item);
                }
            }
            // End snippet
        }
        public void CallSettings_Client()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: CallSettings_ClientWide
            // Create a default PublisherSettings, with a custom header for calls to all RPC methods.
            PublisherSettings publisherSettings = new PublisherSettings
            {
                CallSettings = new CallSettings
                {
                    Headers = new Metadata
                    {
                        { "ClientVersion", "1.0.0" }
                    },
                }
            };
            PublisherClient client = PublisherClient.Create(settings: publisherSettings);
            // Format topicName from the projectId and topicId.
            string topicName = PublisherClient.FormatTopicName(projectId, topicId);
            // The custom 'ClientVersion' header will be included in the RPC call, due to
            // the client being configured with 'publishersettings' above.
            Topic topic = client.CreateTopic(topicName);
            // End sample
        }
Exemplo n.º 14
0
        public static int Main(string[] args)
        {
            // Read projectId from args
            if (args.Length != 1)
            {
                Console.WriteLine("Usage: Project ID must be passed as first argument.");
                Console.WriteLine();
                return(1);
            }
            string projectId = args[0];

            // Create client
            PublisherClient client = PublisherClient.Create();

            // Initialize request argument(s)
            ProjectName project = new ProjectName(projectId);

            // Call API method
            PagedEnumerable <ListTopicsResponse, Topic> pagedResponse = client.ListTopics(project);

            // Show the result
            foreach (var item in pagedResponse)
            {
                Console.WriteLine(item);
            }

            // Success
            Console.WriteLine("Smoke test passed OK");
            return(0);
        }
Exemplo n.º 15
0
        public PublisherClient CreatePublisherClient()
        {
            // [START create_publisher_client]
            PublisherClient publisher = PublisherClient.Create();

            // [END create_publisher_client]
            return(publisher);
        }
Exemplo n.º 16
0
        public void Overview()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

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

            publisher.CreateTopic(topicName);

            // Subscribe to the topic.
            SubscriberClient subscriber       = SubscriberClient.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"]);
        }
Exemplo n.º 17
0
        public static object GetTopic(string projectId, string topicId)
        {
            PublisherClient publisher = PublisherClient.Create();
            TopicName       topicName = new TopicName(projectId, topicId);
            Topic           topic     = publisher.GetTopic(topicName);

            Console.WriteLine($"Topic found: {topic.TopicName.ToString()}");
            return(0);
        }
Exemplo n.º 18
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     // Add framework services.
     services.AddOptions();
     services.Configure <PubsubOptions>(
         Configuration.GetSection("Pubsub"));
     services.AddMvc();
     services.AddSingleton((provider) => PublisherClient.Create());
     services.AddSingleton((provider) => SubscriberClient.Create());
 }
 public void CreateTopic()
 {
     // Snippet: CreateTopic(string,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     string formattedName = PublisherClient.FormatTopicName("[PROJECT]", "[TOPIC]");
     // Make the request
     Topic response = publisherClient.CreateTopic(formattedName);
     // End snippet
 }
Exemplo n.º 20
0
        public static SimplePublisher GetSimplePublisher(string projectId,
                                                         string topicId)
        {
            // [START publish_message]
            PublisherClient publisherClient = PublisherClient.Create();
            SimplePublisher publisher       = SimplePublisher.Create(
                new TopicName(projectId, topicId), new[] { publisherClient });

            // [END publish_message]
            return(publisher);
        }
Exemplo n.º 21
0
        public static PublisherClient GetPublisher(string projectId,
                                                   string topicId)
        {
            // [START pubsub_publish]
            PublisherServiceApiClient publisherClient = PublisherServiceApiClient.Create();
            PublisherClient           publisher       = PublisherClient.Create(
                new TopicName(projectId, topicId), new[] { publisherClient });

            // [END pubsub_publish]
            return(publisher);
        }
 public void GetIamPolicy()
 {
     // Snippet: GetIamPolicy(string,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     string formattedResource = new TopicName("[PROJECT]", "[TOPIC]").ToString();
     // Make the request
     Policy response = publisherClient.GetIamPolicy(formattedResource);
     // End snippet
 }
 public void CreateTopic()
 {
     // Snippet: CreateTopic(TopicName,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     TopicName name = new TopicName("[PROJECT]", "[TOPIC]");
     // Make the request
     Topic response = publisherClient.CreateTopic(name);
     // End snippet
 }
Exemplo n.º 24
0
        public static object DeleteTopic(string projectId, string topicId)
        {
            PublisherClient publisher = PublisherClient.Create();
            // [START delete_topic]
            TopicName topicName = new TopicName(projectId, topicId);

            publisher.DeleteTopic(topicName);
            // [END delete_topic]
            Console.WriteLine("Topic deleted.");
            return(0);
        }
 public void SetIamPolicy()
 {
     // Snippet: SetIamPolicy(string,Policy,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     string formattedResource = PublisherClient.FormatTopicName("[PROJECT]", "[TOPIC]");
     Policy policy            = new Policy();
     // Make the request
     Policy response = publisherClient.SetIamPolicy(formattedResource, policy);
     // End snippet
 }
 public void TestIamPermissions()
 {
     // Snippet: TestIamPermissions(string,IEnumerable<string>,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     string formattedResource         = new TopicName("[PROJECT]", "[TOPIC]").ToString();
     IEnumerable <string> permissions = new List <string>();
     // Make the request
     TestIamPermissionsResponse response = publisherClient.TestIamPermissions(formattedResource, permissions);
     // End snippet
 }
        public void DeleteTopic()
        {
            // Snippet: DeleteTopic(TopicName,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");

            // Make the request
            publisherClient.DeleteTopic(topic);
            // End snippet
        }
Exemplo n.º 28
0
        public static object GetTopicIamPolicy(string projectId, string topicId)
        {
            PublisherClient publisher = PublisherClient.Create();
            // [START pubsub_get_topic_policy]
            TopicName topicName = new TopicName(projectId, topicId);
            Policy    policy    = publisher.GetIamPolicy(topicName.ToString());

            Console.WriteLine($"Topic IAM Policy found for {topicId}:");
            Console.WriteLine(policy.Bindings);
            // [END pubsub_get_topic_policy]
            return(0);
        }
        public BookDetailLookup(string projectId, Options options = null, ISimpleLogger logger = null)
        {
            options = options ?? new Options();

            _logger = logger ?? new DebugLogger();
            // [START pubsubpaths]
            _topicName        = new TopicName(projectId, options.TopicId);
            _subscriptionName = new SubscriptionName(projectId, options.SubscriptionId);
            // [END pubsubpaths]
            _pub = PublisherClient.Create();
            _sub = SubscriberClient.Create();
        }
        public void ListTopics()
        {
            // Sample: ListTopics
            var client = PublisherClient.Create();
            var topics = client.ListTopics("projects/petstore");

            foreach (Topic topic in topics)
            {
                // Output would include projects/petstore/topics/offers
                Console.WriteLine(topic.Name);
            }
            // End sample
        }