Skip to content

Commit bebca28

Browse files
committed
Added dotnet getting started guide
1 parent d1058e7 commit bebca28

2 files changed

Lines changed: 243 additions & 0 deletions

File tree

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,237 @@
1+
---
2+
title: "Getting started: Pub/Sub in C# .NET"
3+
meta_description: "A getting started guide for Ably Pub/Sub C# .NET that steps through some of the key features using C# and .NET."
4+
meta_keywords: "Pub/Sub C# .NET, C# .NET PubSub, Ably C# .NET SDK, realtime messaging C# .NET, publish subscribe C# .NET, Ably Pub/Sub guide, C# .NET realtime communication, Ably tutorial C# .NET, C# .NET message history, presence API C# .NET, Ably Pub/Sub example, realtime Pub/Sub C# .NET, subscribe to channel C# .NET, publish message C# .NET, Ably CLI Pub/Sub"
5+
languages:
6+
- csharp
7+
---
8+
9+
This guide will get you started with Ably Pub/Sub in C# .NET.
10+
11+
It will take you through the following steps:
12+
13+
* Create a client and establish a realtime connection to Ably.
14+
* Attach to a channel and subscribe to its messages.
15+
* Publish a message to the channel for your client to receive.
16+
* Join and subscribe to the presence set of the channel.
17+
* Retrieve the messages you sent in the guide from history.
18+
* Close a connection to Ably when it is no longer needed.
19+
20+
h2(#prerequisites). Prerequisites
21+
22+
* "Sign up":https://ably.com/sign-up for an Ably account.
23+
** Create a new app and get your API key from the "dashboard":https://ably.com/dashboard.
24+
** Your API key will need the @publish@, @subscribe@, @presence@ and @history@ "capabilities":/docs/auth/capabilities.
25+
26+
* Install the Ably CLI:
27+
28+
```[sh]
29+
npm install -g @ably/cli
30+
```
31+
32+
* Run the following to log in to your Ably account and set the default app and API key:
33+
34+
```[sh]
35+
ably login
36+
37+
ably apps switch
38+
ably auth keys switch
39+
```
40+
41+
* Install ".NET SDK":https://dotnet.microsoft.com/download (version 6.0 or later).
42+
* Create a new C# console application:
43+
44+
```[sh]
45+
dotnet new console -n AblyGettingStarted
46+
cd AblyGettingStarted
47+
```
48+
49+
* Add the Ably "Pub/Sub .NET SDK":https://github.com/ably/ably-dotnet package:
50+
51+
```[sh]
52+
dotnet add package ably.io
53+
```
54+
55+
<aside data-type='note'>
56+
<p>The code examples in this guide include a demo API key. If you wish to interact with the Ably CLI and view outputs within your Ably account, ensure that you replace them with your own API key.</p>
57+
</aside>
58+
59+
h2(#step-1). Step 1: Connect to Ably
60+
61+
Clients establish a connection with Ably when they instantiate an SDK instance. This enables them to send and receive messages in realtime across channels.
62+
63+
* Open up the "dev console":https://ably.com/accounts/any/apps/any/console of your first app before instantiating your client so that you can see what happens.
64+
65+
* Replace the contents of your @Program.cs@ file with functionality to instantiate the SDK and establish a connection to Ably. At the minimum you need to provide an authentication mechanism. Use an API key for simplicity, but you should use token authentication in a production app. A @clientId@ ensures the client is identified, which is required to use certain features, such as presence:
66+
67+
```[csharp]
68+
using System;
69+
using IO.Ably;
70+
using IO.Ably.Realtime;
71+
72+
class Program
73+
{
74+
static async Task Main(string[] args)
75+
{
76+
// Initialize the Ably Realtime client
77+
var clientOptions = new ClientOptions("{{API_KEY}}")
78+
{
79+
ClientId = "my-first-client"
80+
};
81+
var realtime = new AblyRealtime(clientOptions);
82+
83+
// Wait for the connection to be established
84+
realtime.Connection.On(ConnectionEvent.Connected, args => {
85+
Console.WriteLine("Made my first connection!");
86+
});
87+
88+
// Keep the program running
89+
Console.WriteLine("Press any key to exit...");
90+
Console.ReadKey();
91+
}
92+
}
93+
```
94+
95+
You can monitor the lifecycle of clients' connections by registering a listener that will emit an event every time the connection state changes. For now, run the program with @dotnet run@ to log a message to the console to know that the connection attempt was successful. You'll see the message printed to your console, and you can also inspect the connection event in the dev console of your app.
96+
97+
h2(#step-2). Step 2: Subscribe to a channel and publish a message
98+
99+
Messages contain the data that a client is communicating, such as a short 'hello' from a colleague, or a financial update being broadcast to subscribers from a server. Ably uses channels to separate messages into different topics, so that clients only ever receive messages on the channels they are subscribed to.
100+
101+
* Add the following lines to your @Main@ method, above the line @// Keep the program running@, to create a channel instance and register a listener to subscribe to the channel:
102+
103+
```[csharp]
104+
// Get a channel instance
105+
var channel = realtime.Channels.Get("my-first-channel");
106+
107+
// Subscribe to messages on the channel
108+
channel.Subscribe(message =>
109+
{
110+
Console.WriteLine($"Received message: {message.Data}");
111+
});
112+
```
113+
114+
* Use the Ably CLI to publish a message to your first channel. The message will be received by the client you've subscribed to the channel, and be logged to the console.
115+
116+
```[sh]
117+
ably channels publish my-first-channel 'Hello!' --name "myEvent"
118+
```
119+
120+
* In a new terminal tab, subscribe to the same channel using the CLI:
121+
122+
```[sh]
123+
ably channels subscribe my-first-channel
124+
```
125+
126+
Publish another message using the CLI and you will see that it's received instantly by the client you have running locally, as well as the subscribed terminal instance.
127+
128+
To publish a message in your code, you can add the following line to your @Main@ method, above the line @// Keep the program running@, after subscribing to the channel:
129+
130+
```[csharp]
131+
await channel.PublishAsync("", "A message sent from my first client!");
132+
```
133+
134+
h2(#step-3). Step 3: Join the presence set
135+
136+
Presence enables clients to be aware of one another if they are present on the same channel. You can then show clients who else is online, provide a custom status update for each, and notify the channel when someone goes offline.
137+
138+
* Add the following lines to your @Main@ method, above the line @// Keep the program running@, to subscribe to, and join, the presence set of the channel:
139+
140+
```[csharp]
141+
// Subscribe to presence events on the channel
142+
channel.Presence.Subscribe(presenceMessage =>
143+
{
144+
Console.WriteLine($"Event type: {presenceMessage.Action} from {presenceMessage.ClientId} with the data {presenceMessage.Data}");
145+
});
146+
147+
// Enter the presence set
148+
await channel.Presence.EnterAsync("I'm here!");
149+
```
150+
151+
* You can have another client join the presence set using the Ably CLI:
152+
153+
```[sh]
154+
ably channels presence enter my-first-channel --client-id "my-cli" --data '{"status":"learning about Ably!"}'
155+
```
156+
157+
h2(#step-4). Step 4: Retrieve message history
158+
159+
You can retrieve previously sent messages using the history feature. Ably stores all messages for 2 minutes by default in the event a client experiences network connectivity issues. This can be extended for longer if required.
160+
161+
If more than 2 minutes has passed since you published a regular message (excluding the presence events), then publish some more before trying out history. You can use the Pub/Sub SDK, Ably CLI or the dev console to do this.
162+
163+
For example, using the Ably CLI to publish 5 messages:
164+
165+
```[sh]
166+
ably channels publish --count 5 my-first-channel "Message number {{.Count}}" --name "myEvent"
167+
```
168+
169+
* Add the following lines to your @Main@ method, above the line @// Keep the program running@, to retrieve any messages that were recently published to the channel:
170+
171+
```[csharp]
172+
// Retrieve message history
173+
var historyResult = await channel.HistoryAsync();
174+
175+
if (historyResult.IsSuccess)
176+
{
177+
if (historyResult.Items.Any())
178+
{
179+
Console.WriteLine("Message History:");
180+
foreach (var message in historyResult.Items)
181+
{
182+
Console.WriteLine($" * {message.Data}");
183+
}
184+
}
185+
else
186+
{
187+
Console.WriteLine("No messages in history.");
188+
}
189+
}
190+
else
191+
{
192+
Console.WriteLine($"Error retrieving history: {historyResult.Error.Message}");
193+
}
194+
```
195+
196+
The output will look similar to the following:
197+
198+
```[json]
199+
[
200+
'Message number 5',
201+
'Message number 4',
202+
'Message number 3',
203+
'Message number 2',
204+
'Message number 1'
205+
]
206+
```
207+
208+
h2(#step-5). Step 5: Close the connection
209+
210+
Connections are automatically closed approximately 2 minutes after no heartbeat is detected by Ably. Explicitly closing connections when they are no longer needed is good practice to help save costs. It will also remove all listeners that were registered by the client.
211+
212+
Note that messages are streamed to clients as soon as they attach to a channel, as long as they have the necessary capabilities. Clients are implicitly attached to a channel when they call @Subscribe()@. Detaching from a channel using the @Detach()@ method will stop the client from being streamed messages by Ably.
213+
214+
Listeners registered when subscribing to a channel are registered client-side. Unsubscribing by calling @Unsubscribe()@ will remove previously registered listeners for that channel. Detaching from a channel has no impact on listeners. As such, if a client reattaches to a channel that they previously registered listeners for, then those listeners will continue to function upon reattachment.
215+
216+
* Replace the @Console.ReadKey();@ line with the following to close the connection after a simulated 10 seconds:
217+
218+
```[csharp]
219+
// Close the connection after 10 seconds
220+
await Task.Delay(10000);
221+
realtime.Close();
222+
Console.WriteLine("Connection closed after 10 seconds.");
223+
```
224+
225+
h2(#next). Next steps
226+
227+
Continue to explore the documentation with C# as the selected language:
228+
229+
Read more about the concepts covered in this guide:
230+
231+
* Revisit the basics of "Pub/Sub":/docs/pub-sub?lang=csharp
232+
* Explore more "advanced":/docs/pub-sub/advanced?lang=csharp Pub/Sub concepts
233+
* Understand realtime "connections":/docs/connect?lang=csharp to Ably
234+
* Read more about how to use "presence":/docs/presence-occupancy/presence?lang=csharp in your apps
235+
* Fetch message "history":/docs/storage-history/history?lang=csharp in your apps
236+
237+
You can also explore the Ably CLI further, or visit the Pub/Sub "API

src/pages/docs/getting-started/index.mdx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,11 @@ These are your first steps towards building a realtime application that can effo
5454
image: 'icon-tech-php',
5555
link: '/docs/getting-started/php',
5656
},
57+
{
58+
title: 'C# .NET',
59+
description: 'Start building with Pub/Sub using Ably\'s .NET SDK.',
60+
image: 'icon-tech-dotnet',
61+
link: '/docs/getting-started/dotnet',
62+
},
5763
]}
5864
</Tiles>

0 commit comments

Comments
 (0)