public IActionResult Index(MessageForm messageForm) { var model = new MessageList(); if (!_options.HasGoodProjectId()) { model.MissingProjectId = true; return View(model); } if (!string.IsNullOrEmpty(messageForm.Message)) { // Publish the message. var topicName = new TopicName(_options.ProjectId, _options.TopicId); lock(s_lock) CreateTopicAndSubscriptionOnce(_publisher, topicName); var pubsubMessage = new PubsubMessage() { Data = ByteString.CopyFromUtf8(messageForm.Message) }; pubsubMessage.Attributes["token"] = _options.VerificationToken; _publisher.Publish(topicName, new[] { pubsubMessage }); model.PublishedMessage = messageForm.Message; } // Render the current list of messages. lock (s_lock) model.Messages = s_receivedMessages.ToArray(); return View(model); }
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 string topicName = PublisherClient.FormatTopicName(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 void PublishTest1() { using (PublisherClient target = new PublisherClient()) { string message = "Test message"; string activityId = "Test activity"; target.Publish(message, activityId); } }
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"]); }
// [END pullonce] /// <summary> /// Publish a message asking for a book to be processed. /// </summary> // [START enqueuebook] public void EnqueueBook(long bookId) { var message = new QueueMessage() { BookId = bookId }; var json = JsonConvert.SerializeObject(message); _pub.Publish(_topicName, new[] { new PubsubMessage() { Data = Google.Protobuf.ByteString.CopyFromUtf8(json) } }); }
private static void StartPublisherClient(CommandLineOptions opts) { Log.Info("Starting test client as Publisher"); var ipAddress = Dns.GetHostEntry(opts.Hostname).AddressList[0]; PublisherClient publisher = new PublisherClient(ipAddress, opts.Port); publisher.Connect(); publisher.Publish("test-channel"); Log.Info("Starting client publisher loop"); while (true) { var newLine = Console.ReadLine(); var newLineSplit = newLine.Split(' '); if (newLineSplit[0] == "dispose") { publisher.Dispose(); break; } else if (newLineSplit[0] == "publish" && newLineSplit.Length > 1) { publisher.Publish(newLineSplit[1]); } else if (newLineSplit[0] == "unpublish" && newLineSplit.Length > 1) { publisher.Unpublish(newLineSplit[1]); } else { publisher.Send(newLine); } } Log.Info("PublisherClient test program complete"); Console.ReadKey(); }
public void Publish() { // Snippet: Publish(TopicName,IEnumerable<PubsubMessage>,CallSettings) // Create client PublisherClient publisherClient = PublisherClient.Create(); // Initialize request argument(s) TopicName topic = new TopicName("[PROJECT]", "[TOPIC]"); IEnumerable <PubsubMessage> messages = new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8(""), }, }; // Make the request PublishResponse response = publisherClient.Publish(topic, messages); // End snippet }
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 }
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 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 }
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 }
public async Task CreateServerTestAsync() { var server = new Server(); server.StartListening(); var publisher = new PublisherClient(); publisher.Connect(); publisher.Publish("test-channel"); var subscriber = new SubscriberClient(); subscriber.Connect(); subscriber.Subscribe("test-channel"); var receiveTask = subscriber.MessageReceived.Take(1).ToTask(new CancellationTokenSource(5000).Token); publisher.Send("hello"); var result = await receiveTask; Assert.AreEqual("hello", result); }
public static object CreateTopicMessage(string projectId, string topicId, string messageText, string attributesKey = "description", string attributesValue = "") { PublisherClient publisher = PublisherClient.Create(); // [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(messageText), // The attributes provide metadata in a string-to-string // dictionary. Attributes = { { attributesKey, attributesValue } } }; publisher.Publish(topicName, new[] { message }); Console.WriteLine("Topic message created."); // [END publish_message] return(0); }
public async Task StreamingPull() { string projectId = _fixture.ProjectId; string topicId = _fixture.CreateTopicId(); string subscriptionId = _fixture.CreateSubscriptionId(); // Snippet: StreamingPull(*, *) PublisherClient publisher = PublisherClient.Create(); TopicName topicName = new TopicName(projectId, topicId); publisher.CreateTopic(topicName); SubscriberClient subscriber = SubscriberClient.Create(); SubscriptionName subscriptionName = new SubscriptionName(projectId, subscriptionId); subscriber.CreateSubscription(subscriptionName, topicName, null, 60); // If we don't see all the messages we expect in 10 seconds, we'll cancel the call. CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10)); CallSettings callSettings = CallSettings.FromCancellationToken(cancellationTokenSource.Token); SubscriberClient.StreamingPullStream stream = subscriber.StreamingPull(callSettings); // The first request must include the subscription name and the stream ack deadline await stream.WriteAsync(new StreamingPullRequest { SubscriptionAsSubscriptionName = subscriptionName, StreamAckDeadlineSeconds = 20 }); Task pullingTask = Task.Run(async() => { int messagesSeen = 0; IAsyncEnumerator <StreamingPullResponse> responseStream = stream.ResponseStream; // Handle responses as we see them. while (await responseStream.MoveNext()) { StreamingPullResponse response = responseStream.Current; Console.WriteLine("Received streaming response"); foreach (ReceivedMessage message in response.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 we've just seen await stream.WriteAsync(new StreamingPullRequest { AckIds = { response.ReceivedMessages.Select(rm => rm.AckId) } }); // If we've seen all the messages we expect, we can complete the streaming call, // and our next MoveNext call will return false. messagesSeen += response.ReceivedMessages.Count; if (messagesSeen == 3) { await stream.WriteCompleteAsync(); } } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 1") } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 2") } }); publisher.Publish(topicName, new[] { new PubsubMessage { Data = ByteString.CopyFromUtf8("Message 3") } }); await pullingTask; // End snippet }
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] }
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); } }
/// <summary> /// Publishes to pub sub TSK delegate. /// </summary> private static void PublishToPubSubTskDelegate(int numOfMsgToPublish, int numOfUsersIdPerMessage) { int totalSize = 0; int publishedMsgCount = 0; PublisherClient publisher = PublisherClient.Create(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); var listMessages = new List <PubsubMessage>(); int count = 0; long customerId = 0; while (publishedMsgCount < numOfMsgToPublish) { int tenantId = 1; customerId++; PushMessageData currPushMsg = null; lock (_processLock){ _publishedMsgCount = Interlocked.Increment(ref _publishedMsgCount); currPushMsg = new PushMessageData(tenantId, numOfUsersIdPerMessage, "Title Text The quick brown fox jumps over the lazy dog ", "Content text The quick brown fox jumps over the lazy dog", PushMessageDataPayloadTypeEnum.BigText, _publishedMsgCount); } String json = currPushMsg.GetFCMMessageJson(); // Publish a message to the topic. PubsubMessage message = new PubsubMessage { // The data is any arbitrary ByteString. Here, we're using text. Data = ByteString.CopyFromUtf8(json), // The attributes provide metadata in a string-to-string dictionary. Attributes = { { "description", "Simple text message" } } }; totalSize += message.CalculateSize(); listMessages.Add(message); //messages.SetValue(message, count); count++; publishedMsgCount++; } stopWatch.Start(); var response = publisher.Publish(CurrentTopicName, listMessages); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. // String result = String.Format("Publish " + numOfMsgToPublish + " Length in Bytes = " + totalSize + " Messages Time {0:00}:{1:00}:{2:00}.{3:00}", // ts.Hours, ts.Minutes, ts.Seconds, // ts.Milliseconds/10); // Console.WriteLine(result); Console.WriteLine("Publish Messages TimeMiliseconds = " + stopWatch.ElapsedMilliseconds); // Console.WriteLine("Publish Messages Time Tics = " + stopWatch.ElapsedTicks); }
public void PublishTest() { using (PublisherClient target = new PublisherClient()) { string message = "Test message"; target.Publish(message); } }