public void PublishTest1()
 {
     using (PublisherClient target = new PublisherClient())
     {
         string message = "Test message";
         string activityId = "Test activity";
         target.Publish(message, activityId);
     }
 }
        public BookDetailLookup(string projectId, Options options = null, ISimpleLogger logger = null)
        {
            options = options ?? new Options();

            _logger = logger ?? new DebugLogger();
            // [START pubsubpaths]
            _topicName = $"projects/{projectId}/topics/{options.TopicId}";
            _subscriptionName = $"projects/{projectId}/subscriptions/{options.SubscriptionId}";
            // [END pubsubpaths]
            _pub = PublisherClient.Create();
            _sub = SubscriberClient.Create();
        }
 // [END retry]
 public PubsubTest()
 {
     // [START create_publisher_client]
     // By default, the Google.Pubsub.V1 library client will authenticate
     // using the service account file (created in the Google Developers
     // Console) specified by the GOOGLE_APPLICATION_CREDENTIALS
     // environment variable and it will use the project specified by
     // the GOOGLE_PROJECT_ID environment variable. If you are running on
     // a Google Compute Engine VM, authentication is completely
     // automatic.
     _projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
     // [END create_publisher_client]
     _publisher = CreatePublisherClient();
     _subscriber = CreateSubscriberClient();
 }
示例#4
0
 public void PublisherServicePublishAPackage()
 {
     File.Copy(@"Data\File1.xml", @"C:\MySynch.Source.Test.Root\File1.xml",true);
     IPublisherProxy publisherProxy = new PublisherClient();
     publisherProxy.InitiateUsingPort(8765);
     var publishedPackage = publisherProxy.PublishPackage();
     Assert.IsNotNull(publishedPackage);
     Assert.AreEqual("SCIENDO-LAPTOP",publishedPackage.Source);
     Assert.AreEqual(@"C:\MySynch.Source.Test.Root\", publishedPackage.SourceRootName);
     Assert.IsNotNull(publishedPackage.PackageId);
     Assert.IsNotNull( publishedPackage.ChangePushItems);
     Assert.AreEqual(1, publishedPackage.ChangePushItems.Count);
     Assert.AreEqual(@"C:\MySynch.Source.Test.Root\File1.xml", publishedPackage.ChangePushItems[0].AbsolutePath);
     Assert.AreEqual(OperationType.Update, publishedPackage.ChangePushItems[0].OperationType);
     publisherProxy.RemovePackage(publishedPackage);
 }
        public void CreateTopicMessage(string topicId, PublisherClient publisher)
        {
            // [START publish_message]
            TopicName     topicName = new TopicName(_projectId, topicId);
            PubsubMessage message   = new PubsubMessage
            {
                // The data is any arbitrary ByteString. Here, we're using text.
                Data = ByteString.CopyFromUtf8("Hello Cloud Pub/Sub!"),
                // The attributes provide metadata in a string-to-string
                // dictionary.
                Attributes =
                {
                    { "description", "Simple text message" }
                }
            };

            publisher.Publish(topicName, new[] { message });
            // [END publish_message]
        }
        public static async Task <object> PublishMessagesAsync(PublisherClient publisher,
                                                               IEnumerable <string> messageTexts)
        {
            // [START pubsub_quickstart_publisher]
            // [START pubsub_publisher_batch_settings]
            // PublisherClient collects messages into appropriately sized
            // batches.
            var publishTasks =
                messageTexts.Select(text => publisher.PublishAsync(text));

            foreach (Task <string> task in publishTasks)
            {
                string message = await task;
                await Console.Out.WriteLineAsync($"Published message {message}");
            }
            // [END pubsub_publisher_batch_settings]
            // [END pubsub_quickstart_publisher]
            return(0);
        }
示例#7
0
 public static void Main(string[] args)
 {
     Parser.Default.ParseArguments <
         CreateTopicOptions, CreateSubscriptionOptions,
         PublishMessageOptions, PullMessagesOptions,
         GetTopicOptions, GetSubscriptionOptions,
         GetTopicIamPolicyOptions, GetSubscriptionIamPolicyOptions,
         SetTopicIamPolicyOptions, SetSubscriptionIamPolicyOptions,
         ListProjectTopicsOptions, ListSubscriptionsOptions,
         DeleteSubscriptionOptions, DeleteTopicOptions
         >(args)
     .MapResult(
         (CreateTopicOptions opts) => CreateTopic(
             opts.projectId, opts.topicId),
         (CreateSubscriptionOptions opts) => CreateSubscription(opts.projectId,
                                                                opts.topicId, opts.subscriptionId),
         (PublishMessageOptions opts) => PublishMessages(opts.customBatchThresholds
             ? GetCustomPublisher(opts.projectId, opts.topicId)
             : GetSimplePublisher(opts.projectId, opts.topicId), opts.message),
         (PullMessagesOptions opts) => PullMessages(opts.customFlow
             ? GetCustomSubscriber(opts.projectId, opts.subscriptionId)
             : GetSimpleSubscriber(opts.projectId, opts.subscriptionId), opts.acknowledge),
         (GetTopicOptions opts) => GetTopic(opts.projectId, opts.topicId),
         (GetSubscriptionOptions opts) => GetSubscription(opts.projectId,
                                                          opts.subscriptionId),
         (GetTopicIamPolicyOptions opts) => GetTopicIamPolicy(opts.projectId, opts.topicId),
         (GetSubscriptionIamPolicyOptions opts) => GetSubscriptionIamPolicy(opts.projectId,
                                                                            opts.subscriptionId),
         (SetTopicIamPolicyOptions opts) => SetTopicIamPolicy(opts.projectId,
                                                              opts.topicId, opts.role, opts.member),
         (SetSubscriptionIamPolicyOptions opts) => SetSubscriptionIamPolicy(opts.projectId,
                                                                            opts.subscriptionId, opts.role, opts.member),
         (ListProjectTopicsOptions opts) => ListProjectTopics(
             string.IsNullOrWhiteSpace(opts.serviceCredentialsJson)
             ? PublisherClient.Create()
             : CreatePublisherWithServiceCredentials(opts.serviceCredentialsJson),
             opts.projectId),
         (ListSubscriptionsOptions opts) => ListSubscriptions(opts.projectId),
         (DeleteSubscriptionOptions opts) => DeleteSubscription(opts.projectId, opts.subscriptionId),
         (DeleteTopicOptions opts) => DeleteTopic(
             opts.projectId, opts.topicId),
         errs => 1);
 }
示例#8
0
    async Task SendMessage(MulticastTransportOperation transportOperation)
    {
        var generateRoutingKey = DefaultRoutingKeyConvention.GenerateRoutingKey(transportOperation.MessageType);
        var publisher          = await PublisherClient.CreateAsync();

        var message          = transportOperation.Message;
        var transportMessage = new PubsubMessage
        {
            MessageId = message.MessageId,
            Data      = ByteString.CopyFrom(message.Body)
        };

        transportMessage.Attributes.Add(message.Headers);
        await publisher.PublishAsync(new TopicName(projectId, generateRoutingKey), new[]
        {
            transportMessage
        })
        .ConfigureAwait(false);
    }
        public async Task PullAsync()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherClient publisher = PublisherClient.Create();
            string          topicName = PublisherClient.FormatTopicName(projectId, topicId);

            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage {
                Data = ByteString.CopyFromUtf8("Simple text")
            };

            SubscriberClient.Create().CreateSubscription(SubscriberClient.FormatSubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: PullAsync(string,*,*,CallSettings)
            // Additional: PullAsync(string,*,*,CancellationToken)
            SubscriberClient client = SubscriberClient.Create();

            // Alternative: use an existing subscription resource name:
            // "projects/{PROJECT_ID}/subscriptions/{SUBSCRIPTION_ID}"
            string subscriptionName = SubscriberClient.FormatSubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = await client.PullAsync(subscriptionName, returnImmediately : false, maxMessages : 100);

            foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
            {
                // Messages can contain any data. We'll assume that we know this
                // topic publishes UTF-8-encoded text.
                Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
            }

            // Acknowledge the messages after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);
            await client.AcknowledgeAsync(subscriptionName, ackIds);

            // End snippet
        }
示例#10
0
        /// <summary>Snippet for ListTopicSubscriptions</summary>
        public void ListTopicSubscriptions()
        {
            // Snippet: ListTopicSubscriptions(TopicName,string,int?,CallSettings)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            TopicName topic = new TopicName("[PROJECT]", "[TOPIC]");
            // Make the request
            PagedEnumerable <ListTopicSubscriptionsResponse, SubscriptionName> response =
                publisherClient.ListTopicSubscriptions(topic);

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

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListTopicSubscriptionsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (SubscriptionName item in page)
                {
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page <SubscriptionName> singlePage = response.ReadPage(pageSize);

            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (SubscriptionName item in singlePage)
            {
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
            // End snippet
        }
        public PubsubGameBoardQueue(
            IOptions <PubsubGameBoardQueueOptions> options,
            ILogger <PubsubGameBoardQueue> logger)
        {
            _options      = options;
            _logger       = logger;
            _publisherApi = PublisherServiceApiClient.Create();
            var subscriberApi = SubscriberServiceApiClient.Create();

            _publisherClient = PublisherClient.Create(MyTopic,
                                                      new[] { _publisherApi });
            _subscriberClient = SubscriberClient.Create(MySubscription,
                                                        new[] { subscriberApi }, new SubscriberClient.Settings()
            {
                StreamAckDeadline = TimeSpan.FromMinutes(1)
            });

            // Create the Topic and Subscription.
            try
            {
                _publisherApi.CreateTopic(MyTopic);
                _logger.LogInformation("Created {0}.", MyTopic.ToString());
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }

            try
            {
                subscriberApi.CreateSubscription(MySubscription, MyTopic,
                                                 pushConfig: null, ackDeadlineSeconds: 10);
                _logger.LogInformation("Created {0}.",
                                       MySubscription.ToString());
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
        }
        /*public Topic CreateTopic(string projectId, string topicId)
         * {
         *  var topicName = TopicName.FromProjectTopic(projectId, topicId);
         *  Topic topic = null;
         *
         *  try
         *  {
         *      topic = publisher.CreateTopic(topicName);
         *      Console.WriteLine($"Topic {topic.Name} created.");
         *  }
         *  catch (RpcException e) when (e.Status.StatusCode == StatusCode.AlreadyExists)
         *  {
         *      Console.WriteLine($"Topic {topicName} already exists.");
         *  }
         *  return topic;
         * }*/
        public async Task <int> PublishMessagesAsync(string topicId, string message)
        {
            TopicName       topicName = TopicName.FromProjectTopic(projectId, topicId);
            PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

            int publishedMessageCount = 0;

            try
            {
                string res = await publisher.PublishAsync(message);

                Console.WriteLine($"Published message {res}");
                Interlocked.Increment(ref publishedMessageCount);
            }
            catch (Exception exception)
            {
                Console.WriteLine($"An error ocurred when publishing message: {exception.Message}");
            }
            return(publishedMessageCount);
        }
示例#13
0
    public async Task PublishMessageWithCustomAttributesAsync(string projectId, string topicId, string messageText)
    {
        TopicName       topicName = TopicName.FromProjectTopic(projectId, topicId);
        PublisherClient publisher = await PublisherClient.CreateAsync(topicName);

        var pubsubMessage = new PubsubMessage
        {
            // The data is any arbitrary ByteString. Here, we're using text.
            Data = ByteString.CopyFromUtf8(messageText),
            // The attributes provide metadata in a string-to-string dictionary.
            Attributes =
            {
                { "year",   "2020"    },
                { "author", "unknown" }
            }
        };
        string message = await publisher.PublishAsync(pubsubMessage);

        Console.WriteLine($"Published message {message}");
    }
示例#14
0
        public async Task InitTopic(string topicID)
        {
            await Task.Run(() =>
            {
                _topicID          = topicID;
                _topicName        = new TopicName(_projectID, _topicID);
                _publisherService = PublisherServiceApiClient.Create();

                try
                {
                    _publisherService.CreateTopic(_topicName);
                }
                catch (Grpc.Core.RpcException e) when(e.Status.StatusCode == Grpc.Core.StatusCode.AlreadyExists)
                {
                    //Console.WriteLine("Topic existed.");
                    _logger.Debug($"[GCPFanout.InitTopic()] Topic: {_topicID} existed");
                }
                _publisher = PublisherClient.CreateAsync(_topicName).Result;
            });
        }
        public async Task PublishAsync()
        {
            // Snippet: PublishAsync(string,IEnumerable<PubsubMessage>,CallSettings)
            // Additional: PublishAsync(string,IEnumerable<PubsubMessage>,CancellationToken)
            // Create client
            PublisherClient publisherClient = PublisherClient.Create();
            // Initialize request argument(s)
            string formattedTopic = PublisherClient.FormatTopicName("[PROJECT]", "[TOPIC]");
            IEnumerable <PubsubMessage> messages = new[]
            {
                new PubsubMessage
                {
                    Data = ByteString.CopyFromUtf8(""),
                },
            };
            // Make the request
            PublishResponse response = await publisherClient.PublishAsync(formattedTopic, messages);

            // End snippet
        }
示例#16
0
        private static SimplePublisher GetGoogleBusWriter(Microsoft.Azure.WebJobs.ExecutionContext context)
        {
            string topicId   = ConfigurationManager.AppSettings["GoogleTopicId"];
            string projectId = ConfigurationManager.AppSettings["GoogleProjectId"];

            //Google credential expected to be a local file called googleCredential.json, copied to output

            TopicName topicName      = new TopicName(projectId, topicId);
            string    credentialPath = Path.Combine(context.FunctionDirectory, "..\\googleCredential.json");

            GoogleCredential credential = ReadGoogleCredentialFile(credentialPath);

            credential = credential.CreateScoped(PublisherClient.DefaultScopes);
            ClientCreationSettings clientSettings = new ClientCreationSettings(credentials: credential.ToChannelCredentials());

            Channel         channel = new Channel(PublisherClient.DefaultEndpoint.Host, PublisherClient.DefaultEndpoint.Port, credential.ToChannelCredentials());
            PublisherClient client  = PublisherClient.Create(channel);

            return(SimplePublisher.Create(topicName, new[] { client }));
        }
示例#17
0
        public async Task CreateSubscriptionAsync()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherClient.Create().CreateTopic(new TopicName(projectId, topicId));

            // Snippet: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CallSettings)
            // Additional: CreateSubscriptionAsync(SubscriptionName,TopicName,*,*,CancellationToken)
            SubscriberClient client = SubscriberClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);
            TopicName        topicName        = new TopicName(projectId, topicId);
            Subscription     subscription     = await client.CreateSubscriptionAsync(
                subscriptionName, topicName, pushConfig : null, ackDeadlineSeconds : 30);

            Console.WriteLine($"Created {subscription.Name} subscribed to {subscription.Topic}");
            // End snippet
        }
示例#18
0
        public static async Task <string> Publish(TopicName topicName, string message)
        {
            var publisher = await PublisherClient.CreateAsync(topicName);

            string messageId = null;

            try
            {
                messageId = await publisher.PublishAsync(message);

                Console.WriteLine($" => Publishing succeed. (Message: ({messageId}) {message}");
            }
            catch (Exception e)
            {
                Console.WriteLine($" => Publishing failed. Error: {e.Message}");
            }
            await publisher.ShutdownAsync(TimeSpan.FromSeconds(15));

            return(messageId);
        }
示例#19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });

                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.AddControllers().AddNewtonsoftJson();
            services.AddScoped <INotificationService, NotificationService>();
            services.AddDbContextPool <CroudPulseDbContext>(opts =>
            {
                opts.UseMySql(Configuration.GetConnectionString("CroudPulseDbContext"));
            });

            services.Configure <PubSubOptions>(
                Configuration.GetSection("Pubsub"));

            services.AddSingleton((provider) =>
            {
                var options = provider.GetService <IOptions <PubSubOptions> >()
                              .Value;
                var logger = provider.GetService <ILogger <Startup> >();
                // CreateTopicAndSubscription(options, logger);
                return(PublisherClient.CreateAsync(new TopicName(options.ProjectId
                                                                 , options.TopicId)).Result);
            });
        }
示例#20
0
        public void ReadPage()
        {
            string projectId            = _fixture.ProjectId;
            string pageTokenFromRequest = "";

            // Sample: ReadPage
            PublisherClient client      = PublisherClient.Create();
            ProjectName     projectName = new ProjectName(projectId);
            PagedEnumerable <ListTopicsResponse, Topic> topics = client.ListTopics(projectName, pageTokenFromRequest);

            Page <Topic> page = topics.ReadPage(3);

            // In a web application, this would be a matter of including the topics in the web page.
            foreach (Topic topic in page)
            {
                Console.WriteLine(topic.Name);
            }
            // ... and embedding the next page token into a "next page" link.
            Console.WriteLine($"Next page token: {page.NextPageToken}");
            // End sample
        }
示例#21
0
        public static object CreateTopic(string projectId, string topicId)
        {
            // [START create_publisher_client]
            PublisherClient publisher = PublisherClient.Create();
            // [END create_publisher_client]

            // [START create_topic]
            TopicName topicName = new TopicName(projectId, topicId);

            try
            {
                publisher.CreateTopic(topicName);
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            // [END create_topic]
            return(0);
        }
 public void Publish_RequestObject()
 {
     // Snippet: Publish(PublishRequest,CallSettings)
     // Create client
     PublisherClient publisherClient = PublisherClient.Create();
     // Initialize request argument(s)
     PublishRequest request = new PublishRequest
     {
         TopicAsTopicName = new TopicName("[PROJECT]", "[TOPIC]"),
         Messages         =
         {
             new PubsubMessage
             {
                 Data = ByteString.CopyFromUtf8(""),
             },
         },
     };
     // Make the request
     PublishResponse response = publisherClient.Publish(request);
     // End snippet
 }
示例#23
0
        internal bool RequestChain()
        {
            var   chainLoaded = false;
            var   knownNodes  = node.GetKnownNodes();
            Chain receivedChain;

            foreach (var n in knownNodes)
            {
                try
                {
                    receivedChain = new PublisherClient(n, serverSettings).RequestFullChain();

                    if (node.OnReceiveChain(receivedChain))
                    {
                        chainLoaded = true; //Continue to query other known nodes after this, in case newer version of chain is found
                    }
                } catch (RpcException) { }
            }

            return(chainLoaded);
        }
        public static object PublishMessages(PublisherClient publisher,
                                             IEnumerable <string> messageTexts)
        {
            // [START pubsub_quickstart_publisher]
            // [START pubsub_publisher_batch_settings]
            var publishTasks = new List <Task <string> >();

            // SimplePublisher collects messages into appropriately sized
            // batches.
            foreach (string text in messageTexts)
            {
                publishTasks.Add(publisher.PublishAsync(text));
            }
            foreach (var task in publishTasks)
            {
                Console.WriteLine("Published message {0}", task.Result);
            }
            // [END pubsub_publisher_batch_settings]
            // [END pubsub_quickstart_publisher]
            return(0);
        }
示例#25
0
        private async Task Run()
        {
            string CREDENTIAL_FILE_PKCS12       = "/path/to/your/cert/file.p12";
            string serviceAccountEmail          = "*****@*****.**";
            var    certificate                  = new X509Certificate2(CREDENTIAL_FILE_PKCS12, "notasecret", X509KeyStorageFlags.Exportable);
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                //Scopes = new[] { StorageService.Scope.DevstorageReadOnly, PublisherClient.DefaultScopes },
                Scopes            = PublisherClient.DefaultScopes.Append(StorageService.Scope.DevstorageReadOnly),
                HttpClientFactory = new ProxySupportedHttpClientFactory()
            }.FromCertificate(certificate));


            //GoogleCredential credential = await GoogleCredential.GetApplicationDefaultAsync();
            //StorageService service = StorageClient.Create(credential);

            StorageService service = new StorageService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = StorageClientImpl.ApplicationName,
                HttpClientFactory     = new ProxySupportedHttpClientFactory(),
            });
            var client = new StorageClientImpl(service, null);

            foreach (var b in client.ListBuckets(projectID))
            {
                Console.WriteLine(b.Name);
            }

            ChannelCredentials channelCredentials = credential.ToChannelCredentials();
            Channel            channel            = new Channel(PublisherClient.DefaultEndpoint.ToString(), channelCredentials);
            PublisherSettings  ps        = new PublisherSettings();
            PublisherClient    publisher = PublisherClient.Create(channel, ps);

            foreach (Topic t in publisher.ListTopics(new ProjectName(projectID)))
            {
                Console.WriteLine(t.Name);
            }
        }
示例#26
0
        public void Pull()
        {
            string projectId      = _fixture.ProjectId;
            string topicId        = _fixture.CreateTopicId();
            string subscriptionId = _fixture.CreateSubscriptionId();

            PublisherClient publisher = PublisherClient.Create();
            TopicName       topicName = new TopicName(projectId, topicId);

            publisher.CreateTopic(topicName);
            PubsubMessage newMessage = new PubsubMessage {
                Data = ByteString.CopyFromUtf8("Simple text")
            };

            SubscriberClient.Create().CreateSubscription(new SubscriptionName(projectId, subscriptionId), topicName, null, 60);
            publisher.Publish(topicName, new[] { newMessage });

            // Snippet: Pull(*,*,*,*)
            SubscriberClient client = SubscriberClient.Create();

            SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId);

            PullResponse pullResponse = client.Pull(subscriptionName, returnImmediately: false, maxMessages: 100);

            foreach (ReceivedMessage message in pullResponse.ReceivedMessages)
            {
                // Messages can contain any data. We'll assume that we know this
                // topic publishes UTF-8-encoded text.
                Console.WriteLine($"Message text: {message.Message.Data.ToStringUtf8()}");
            }

            // Acknowledge the messages after pulling them, so we don't pull them
            // a second time later. The ackDeadlineSeconds parameter specified when
            // the subscription is created determines how quickly you need to acknowledge
            // successfully-pulled messages before they will be redelivered.
            var ackIds = pullResponse.ReceivedMessages.Select(rm => rm.AckId);

            client.Acknowledge(subscriptionName, ackIds);
            // End snippet
        }
示例#27
0
        public void Dispose()
        {
            var subscriber    = SubscriberClient.Create();
            var subscriptions = subscriber.ListSubscriptions(new ProjectName(ProjectId))
                                .Where(sub => sub.SubscriptionName.SubscriptionId.StartsWith(SubscriptionPrefix))
                                .ToList();

            foreach (var sub in subscriptions)
            {
                try
                {
                    subscriber.DeleteSubscription(sub.SubscriptionName);
                }
                catch (RpcException e) when(e.Status.StatusCode == StatusCode.NotFound)
                {
                    // There is a race condition such that if the test itself deletes a subscription
                    // it can still be returned from ListSubscriptions(), but be gone by the time
                    // DeleteSubscription() here is called.
                }
            }

            var publisher = PublisherClient.Create();
            var topics    = publisher.ListTopics(new ProjectName(ProjectId))
                            .Where(topic => topic.TopicName.TopicId.StartsWith(TopicPrefix))
                            .ToList();

            foreach (var topic in topics)
            {
                try
                {
                    publisher.DeleteTopic(topic.TopicName);
                }
                catch (RpcException e) when(e.Status.StatusCode == StatusCode.NotFound)
                {
                    // There is a race condition such that if the test itself deletes a topic
                    // it can still be returned from ListTopics(), but be gone by the time
                    // DeleteTopic() here is called.
                }
            }
        }
        public void CallSettings_ClientPerMethod()
        {
            string projectId = _fixture.ProjectId;
            string topicId   = _fixture.CreateTopicId();

            // Sample: CallSettings_ClientPerMethod
            // Create a default PublisherSettings, with a custom header for calls
            // to the CreateTopic RPC method.
            PublisherSettings publisherSettings = new PublisherSettings();

            publisherSettings.CreateTopicSettings.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
        }
示例#29
0
        public void Overrides()
        {
            string            projectId         = _fixture.ProjectId;
            string            topicId           = _fixture.CreateTopicId();
            DateTime          deadline          = DateTime.MaxValue;
            CancellationToken cancellationToken = new CancellationTokenSource().Token;

            // Sample: Overrides
            // Create a default PublisherSettings, with customizations for CreateTopic RPCs:
            // * A custom "ClientVersion" header.
            // * A custom 5-second timeout Timing.
            // * No cancellation token.
            PublisherSettings publisherSettings = new PublisherSettings();

            publisherSettings.CreateTopicSettings = publisherSettings.CreateTopicSettings
                                                    .WithCancellationToken(CancellationToken.None)
                                                    .WithCallTiming(CallTiming.FromTimeout(TimeSpan.FromSeconds(5)))
                                                    .WithHeader("ClientVersion", "1.0.0");

            // Override the above Timing and CancellationToken in the client-wide CallSettings;
            // the Headers are not overridden.
            publisherSettings.CallSettings = CallSettings
                                             .FromCallTiming(CallTiming.FromDeadline(deadline))
                                             .WithCancellationToken(CancellationToken.None);

            // Create the client with the configured publisherSettings
            PublisherClient client = PublisherClient.Create(settings: publisherSettings);

            // Create a topic name from the projectId and topicId.
            TopicName topicName = new TopicName(projectId, topicId);

            // Call CreateTopic(). Override only the CancellationToken, using a per-RPC-method CallSettings.
            // The CallSettings used during this RPC invocation is:
            // * A custom "ClientVersion" header.
            // * A Timing deadline of 'deadline' (*not* the overridden 5-second timeout).
            // * The CancellationToken 'cancellationToken' (*not* CancellationToken.None).
            Topic topic = client.CreateTopic(topicName, CallSettings.FromCancellationToken(cancellationToken));
            // End sample
        }
示例#30
0
        public void Responses()
        {
            string projectId = _fixture.ProjectId;
            // Sample: Responses
            PublisherClient client      = PublisherClient.Create();
            ProjectName     projectName = new ProjectName(projectId);
            PagedEnumerable <ListTopicsResponse, Topic> topics         = client.ListTopics(projectName, pageSize: 3);
            IEnumerable <ListTopicsResponse>            topicResponses = topics.AsRawResponses();

            foreach (ListTopicsResponse response in topicResponses)
            {
                Console.WriteLine("Topics in response:");
                foreach (Topic topic in response.Topics)
                {
                    Console.WriteLine($"  {topic.Name}");
                }
                // If you were processing items in batches, you might wish to store this
                // in order to recover from failures. The page token can be passed into the ListTopics method.
                Console.WriteLine($"Next page token: {response.NextPageToken}");
            }
            // End sample
        }
        public void Dispose()
        {
            var subscriber    = SubscriberClient.Create();
            var subscriptions = subscriber.ListSubscriptions(SubscriberClient.FormatProjectName(ProjectId))
                                .Where(sub => SubscriberClient.SubscriptionTemplate.ParseName(sub.Name)[1].StartsWith(TopicPrefix))
                                .ToList();

            foreach (var sub in subscriptions)
            {
                subscriber.DeleteSubscription(sub.Name);
            }

            var publisher = PublisherClient.Create();
            var topics    = publisher.ListTopics(PublisherClient.FormatProjectName(ProjectId))
                            .Where(topic => PublisherClient.TopicTemplate.ParseName(topic.Name)[1].StartsWith(TopicPrefix))
                            .ToList();

            foreach (var topic in topics)
            {
                publisher.DeleteTopic(topic.Name);
            }
        }
示例#32
0
        public void SingleResponse()
        {
            string projectId = _fixture.ProjectId;
            // Sample: SingleResponse
            PublisherClient client      = PublisherClient.Create();
            ProjectName     projectName = new ProjectName(projectId);
            PagedEnumerable <ListTopicsResponse, Topic> topics         = client.ListTopics(projectName, pageSize: 3);
            IEnumerable <ListTopicsResponse>            topicResponses = topics.AsRawResponses();
            // This is just the regular LINQ First() method. The sequence of pages will never be empty,
            // but the page may have no resources.
            ListTopicsResponse firstResponse = topicResponses.First();

            Console.WriteLine("Topics in response:");
            foreach (Topic topic in firstResponse.Topics)
            {
                Console.WriteLine($"  {topic.Name}");
            }
            // If you were processing items in batches, you might wish to store this
            // in order to recover from failures. The page token can be passed into the ListTopics method.
            Console.WriteLine($"Next page token: {firstResponse.NextPageToken}");
            // End sample
        }
示例#33
0
        // [START retry]
        public void RpcRetry(string topicId, string subscriptionId,
                             PublisherClient publisher, SubscriberClient subscriber)
        {
            string topicName = PublisherClient.FormatTopicName(_projectId,
                                                               topicId);
            string subscriptionName =
                // Create Subscription.
                SubscriberClient.FormatSubscriptionName(_projectId, subscriptionId);

            // Create Topic
            try
            {
                // This may fail if the Topic already exists.
                // Don't retry in that case.
                publisher.CreateTopic(topicName, newRetryCallSettings(3,
                                                                      StatusCode.AlreadyExists));
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
            try
            {
                // Subscribe to Topic
                // This may fail if the Subscription already exists or
                // the Topic has not yet been created.  In those cases, don't
                // retry, because a retry would fail the same way.
                subscriber.CreateSubscription(subscriptionName, topicName,
                                              pushConfig: null, ackDeadlineSeconds: 60,
                                              callSettings: newRetryCallSettings(3, StatusCode.AlreadyExists,
                                                                                 StatusCode.NotFound));
            }
            catch (RpcException e)
                when(e.Status.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  That's fine.
                }
        }
示例#34
0
        public void Dispose()
        {
            var subscriber    = SubscriberClient.Create();
            var subscriptions = subscriber.ListSubscriptions(new ProjectName(ProjectId))
                                .Where(sub => sub.SubscriptionName.SubscriptionId.StartsWith(SubscriptionPrefix))
                                .ToList();

            foreach (var sub in subscriptions)
            {
                subscriber.DeleteSubscription(sub.SubscriptionName);
            }

            var publisher = PublisherClient.Create();
            var topics    = publisher.ListTopics(new ProjectName(ProjectId))
                            .Where(topic => topic.TopicName.TopicId.StartsWith(TopicPrefix))
                            .ToList();

            foreach (var topic in topics)
            {
                publisher.DeleteTopic(topic.TopicName);
            }
        }
示例#35
0
 public void PublisherServiceUpAndAccessible()
 {
     IPublisherProxy publisherProxy = new PublisherClient();
     publisherProxy.InitiateUsingPort(8765);
     var publishedPackage = publisherProxy.PublishPackage();
     Assert.IsNull(publishedPackage);
 }
        public void ShouldPublishToPublisherAndGetNotificationBack()
        {
            ServiceHost hostDefault = new
   ServiceHost(typeof(Subscriber));

            TimeSpan closeTimeout = hostDefault.CloseTimeout;

            TimeSpan openTimeout = hostDefault.OpenTimeout;


            ServiceAuthorizationBehavior authorization =
                hostDefault.Authorization;

            ServiceCredentials credentials =
                            hostDefault.Credentials;

            ServiceDescription description =
                    hostDefault.Description;


            int manualFlowControlLimit =
                    hostDefault.ManualFlowControlLimit;


            NetTcpBinding portsharingBinding = new NetTcpBinding();
            hostDefault.AddServiceEndpoint(
          typeof(ISubscriber),
          portsharingBinding,
          "net.tcp://localhost/MyService");


            int newLimit = hostDefault.IncrementManualFlowControlLimit(100);

            using (ServiceHost serviceHost = new ServiceHost(typeof(Subscriber)))
            {
                try
                {
                    // Open the ServiceHost to start listening for messages.
                    serviceHost.Open();
                    // The service can now be accessed.
                    Console.WriteLine("The service is ready.");
                    Console.WriteLine("Press <ENTER> to terminate service.");
                    Console.ReadLine();

                    // Close the ServiceHost.
                    serviceHost.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    Console.ReadLine();
                    throw ex;
                }
            }

            using (PublisherClient target = new PublisherClient())
            {
                string message = "Test message";
                string activityId = "Test activity";
                target.Publish(message, activityId);
            }
        }
 public void AddSubscriberTest()
 {
     PublisherClient target = new PublisherClient();
     SubscriberData subscriber = new SubscriberData { Name = "Test subscriber", Url = "http://localhost:8002/Subscriber" };
     target.AddSubscriber(subscriber);
 }
 public void CreateTopicMessage(string topicId, PublisherClient publisher)
 {
     // [START publish_message]
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     PubsubMessage message = new PubsubMessage
     {
         // The data is any arbitrary ByteString. Here, we're using text.
         Data = ByteString.CopyFromUtf8("Hello Cloud Pub/Sub!"),
         // The attributes provide metadata in a string-to-string
         // dictionary.
         Attributes =
         {
             { "description", "Simple text message" }
         }
     };
     publisher.Publish(topicName, new[] { message });
     // [END publish_message]
 }
示例#39
0
 public void PublisherStartsWithoutABackupFile()
 {
     if (File.Exists(@"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml"))
         File.Delete(@"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml");
     IPublisherProxy publisherProxy = new PublisherClient();
     publisherProxy.InitiateUsingPort(8765);
     var publishedPackage = publisherProxy.PublishPackage();
     Assert.IsNull(publishedPackage);
 }
 public void GetNameTest()
 {
     using (PublisherClient target = new PublisherClient())
     {
         Assert.IsTrue(!String.IsNullOrEmpty(target.GetName()), "Not null name is expected as a return from the publisher's GetName call");
     }
 }
 // [START retry]
 public void RpcRetry(string topicId, string subscriptionId,
     PublisherClient publisher, SubscriberClient subscriber)
 {
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     string subscriptionName =
     // Create Subscription.
     SubscriberClient.FormatSubscriptionName(_projectId, subscriptionId);
     // Create Topic
     try
     {
         // This may fail if the Topic already exists.
         // Don't retry in that case.
         publisher.CreateTopic(topicName, newRetryCallSettings(3,
             StatusCode.AlreadyExists));
     }
     catch (RpcException e)
     when (e.Status.StatusCode == StatusCode.AlreadyExists)
     {
         // Already exists.  That's fine.
     }
     try
     {
         // Subscribe to Topic
         // This may fail if the Subscription already exists or
         // the Topic has not yet been created.  In those cases, don't
         // retry, because a retry would fail the same way.
         subscriber.CreateSubscription(subscriptionName, topicName,
             pushConfig: null, ackDeadlineSeconds: 60,
             callSettings: newRetryCallSettings(3, StatusCode.AlreadyExists,
                 StatusCode.NotFound));
     }
     catch (RpcException e)
     when (e.Status.StatusCode == StatusCode.AlreadyExists)
     {
         // Already exists.  That's fine.
     }
 }
 public IEnumerable<Topic> ListProjectTopics(PublisherClient publisher)
 {
     // [START list_topics]
     string projectName = PublisherClient.FormatProjectName(_projectId);
     IEnumerable<Topic> topics = publisher.ListTopics(projectName);
     // [END list_topics]
     return topics;
 }
 public Topic GetTopic(string topicId, PublisherClient publisher)
 {
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     Topic topic = _publisher.GetTopic(topicName);
     return topic;
 }
 public void DeleteTopic(string topicId, PublisherClient publisher)
 {
     // [START delete_topic]
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     publisher.DeleteTopic(topicName);
     // [END delete_topic]
 }
 public void PublisherClientConstructorTest2()
 {
     PublisherClient target = new PublisherClient();
 }
 public void PublishTest()
 {
     using (PublisherClient target = new PublisherClient())
     {
         string message = "Test message";
         target.Publish(message);
     }
 }
 public void CreateTopic(string topicId, PublisherClient publisher)
 {
     // [START create_topic]
     string topicName = PublisherClient.FormatTopicName(_projectId,
         topicId);
     try
     {
         publisher.CreateTopic(topicName);
     }
     catch (RpcException e)
     when (e.Status.StatusCode == StatusCode.AlreadyExists)
     {
         // Already exists.  That's fine.
     }
     // [END create_topic]
 }
        //*******************************************************************
        //      CONSTRUCTOR
        //*******************************************************************

        #region
        private GoogleCloudPubSubSinkState(GoogleCloudPubSubSinkOptions options, RollingFileSink errorsRollingFileSink)
        {
            //--- Mandatory options validations --------------------
            if (options.BatchPostingLimit < 1 ) throw new ArgumentException("batchPostingLimit must be >= 1");
            if (string.IsNullOrWhiteSpace(options.ProjectId)) throw new ArgumentException("options.ProjectId");
            if (string.IsNullOrWhiteSpace(options.TopicId)) throw new ArgumentException("options.TopicId");

            //---
            // All is ok ...

            this._options = options;
            this._errorsRollingFileSink = errorsRollingFileSink;

            this._periodicBatchingFormatter = options.CustomFormatter ?? new GoogleCloudPubSubRawFormatter();
            this._durableFormatter = options.CustomFormatter ?? new GoogleCloudPubSubRawFormatter();

            this._topic = PublisherClient.FormatTopicName(options.ProjectId, options.TopicId);
            this._client = PublisherClient.Create();

            //---

            try
            {
                if (!string.IsNullOrWhiteSpace(this.Options.EventFieldSeparator) && !string.IsNullOrWhiteSpace(this.Options.MessageAttrMinValue))
                {
                    string[] auxArray = this.Options.MessageAttrMinValue.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                    if (auxArray.Length == 2)
                    {
                        this._attrMinPosition = Int32.Parse(auxArray[0]);
                        this._attrMinName = auxArray[1];
                        this._attrMinCreate = true;
                    }
                }
            }
            catch
            {
                this._attrMinCreate = false;
            }
        }
示例#49
0
        public void PublisherStartsWithABackupFile()
        {
            ServiceController serviceController = new ServiceController("MySynch.Publisher.Debug");
            serviceController.Stop();
            serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));

            File.Copy(@"Data\XMLFile2.xml", @"C:\MySynch.Source.Test.Root\XMLFile2.xml", true);

            File.Copy(@"Data\backup.xml", @"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml", true);
            serviceController.Start();
            serviceController.WaitForStatus(ServiceControllerStatus.Running,TimeSpan.FromSeconds(10));

            IPublisherProxy publisherProxy = new PublisherClient();
            publisherProxy.InitiateUsingPort(8765);
            var publishedPackage = publisherProxy.PublishPackage();
            Assert.IsNotNull(publishedPackage);
            Assert.AreEqual(5,publishedPackage.ChangePushItems.Count);
            Assert.AreEqual(1,
                            publishedPackage.ChangePushItems.Count(
                                i =>
                                i.OperationType == OperationType.Update &&
                                i.AbsolutePath == @"C:\MySynch.Source.Test.Root\abc\abc def\def feg\abc cba.txt"));
            Assert.AreEqual(1,
                            publishedPackage.ChangePushItems.Count(
                                i =>
                                i.OperationType == OperationType.Insert &&
                                i.AbsolutePath == @"C:\MySynch.Source.Test.Root\XMLFile2.xml"));

            serviceController.Stop();
            serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10));
            File.Delete(@"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml");
            File.Delete(@"C:\MySynch.Source.Test.Root\XMLFile2.xml");
        }