Mobiscroll.Connect
1.7.0
dotnet add package Mobiscroll.Connect --version 1.7.0
NuGet\Install-Package Mobiscroll.Connect -Version 1.7.0
<PackageReference Include="Mobiscroll.Connect" Version="1.7.0" />
<PackageVersion Include="Mobiscroll.Connect" Version="1.7.0" />
<PackageReference Include="Mobiscroll.Connect" />
paket add Mobiscroll.Connect --version 1.7.0
#r "nuget: Mobiscroll.Connect, 1.7.0"
#:package Mobiscroll.Connect@1.7.0
#addin nuget:?package=Mobiscroll.Connect&version=1.7.0
#tool nuget:?package=Mobiscroll.Connect&version=1.7.0
Mobiscroll Connect .NET SDK
.NET client for Mobiscroll Connect, the calendar connectivity layer for scheduling products — Google Calendar, Microsoft Outlook, Apple Calendar and CalDAV through one async API. Backend only — works with your own UI.
NuGet · Documentation · Changelog · Source
Features
- Multi-provider support: Google Calendar, Microsoft Outlook, Apple Calendar, CalDAV
- OAuth2 authentication: Full authorization code flow with token exchange
- Automatic token refresh: Silently refreshes expired access tokens and retries the original request
- Event management: Create, read, update, and delete calendar events
- Calendar operations: List calendars from all connected providers
- Webhooks: Subscribe to and unsubscribe from calendar change notifications, and verify deliveries
- Connection management: Check provider connection status, disconnect accounts and revoke tokens
- Typed exceptions: Distinct error classes for authentication, validation, rate limiting, and more
- ASP.NET Core integration: First-class dependency injection support via
AddMobiscrollConnect() - Async-first: All API calls are
async/awaitwithCancellationTokensupport
Requirements
- .NET 8 or higher
Installation
dotnet add package Mobiscroll.Connect
Setup
Create a Mobiscroll Connect application at the Mobiscroll Connect dashboard to obtain your Client ID, Client Secret, and configure your Redirect URI.
Usage
Initialize the Client
using Mobiscroll.Connect;
var client = new MobiscrollConnectClient(
clientId: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
redirectUri: "YOUR_REDIRECT_URI"
);
ASP.NET Core / Dependency Injection
// Program.cs
builder.Services.AddMobiscrollConnect(o =>
{
o.ClientId = builder.Configuration["Mobiscroll:ClientId"]!;
o.ClientSecret = builder.Configuration["Mobiscroll:ClientSecret"]!;
o.RedirectUri = builder.Configuration["Mobiscroll:RedirectUri"]!;
});
Then inject MobiscrollConnectClient into controllers or minimal-API handlers as normal.
Token Refresh
The SDK automatically refreshes expired access tokens. When a request returns 401 Unauthorized and a refresh token is available, the SDK silently exchanges it for a new access token and retries the request.
Register a callback to persist the updated tokens — this is required so the new tokens survive future requests:
client.OnTokensRefreshed(updatedTokens =>
{
// Persist in your database or session store
SaveTokensToDb(userId, updatedTokens);
});
If the refresh token is invalid or revoked, the SDK throws AuthenticationException and the user must re-authorize.
Running more than one instance. Concurrent calls on the same client wait for one shared refresh. The SDK does not coordinate across processes — separate containers, cluster workers or serverless invocations each refresh from the tokens they hold in memory. Connect accepts concurrent refreshes of the same token, but refreshing with a copy that is two or more refreshes out of date revokes the user's authorization. Persist refreshed tokens to storage every instance reads, and call client.SetCredentials(...) with the current tokens when a process starts a job or handles a request. See Refreshing from several instances.
OAuth2 Flow
Step 1: Generate the authorization URL
string authUrl = client.Auth.GenerateAuthUrl(new AuthorizeParams
{
UserId = "your-app-user-id",
// Optional:
// Scope = "read-write",
// State = "csrf-protection-value",
// Providers = "google,microsoft",
// Lng = "es", // Connect page language, see https://mobiscroll.com/docs/connect/localization#supported-languages
// Theme = "dark", // Connect page color scheme: "light", "dark" or "auto"
});
// Redirect the user to authUrl
return Redirect(authUrl);
Step 2: Handle the callback and exchange the code for tokens
string? code = Request.Query["code"];
TokenResponse tokenResponse = await client.Auth.GetTokenAsync(code);
// Persist all token fields — you need the RefreshToken for auto-refresh
SaveTokensToDb(userId, tokenResponse);
Step 3: Restore credentials and make API calls
TokenResponse saved = LoadTokensFromDb(userId);
client.SetCredentials(saved);
// The client is now authenticated — make API calls
IReadOnlyList<Calendar> calendars = await client.Calendars.ListAsync();
Calendars
IReadOnlyList<Calendar> calendars = await client.Calendars.ListAsync();
foreach (Calendar cal in calendars)
Console.WriteLine($"[{cal.Provider}] {cal.Title} ({cal.Id})");
Events
List events
EventsListResponse response = await client.Events.ListAsync(new EventListParams
{
Start = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc),
End = new DateTime(2024, 1, 31, 23, 59, 59, DateTimeKind.Utc),
CalendarIds = new Dictionary<string, List<string>>
{
["google"] = new() { "primary" },
},
PageSize = 50,
});
foreach (CalendarEvent e in response.Events)
Console.WriteLine($"{e.Title}: {e.Start:g} – {e.End:g}");
// Load the next page
if (response.NextPageToken is not null)
{
var next = await client.Events.ListAsync(new EventListParams
{
PageSize = 50,
NextPageToken = response.NextPageToken,
});
}
IncludeCancelled = true also returns the deleted occurrences of series that still exist, as events with Status = "cancelled" (with SingleEvents = true, the default). EventIds returns only the given events: at most 40 IDs per request, given per provider and calendar ID, and not combinable with CalendarIds. With SingleEvents = false each ID returns the event itself, in the order of the IDs, without a time window; with SingleEvents = true it returns what the list returns for that ID between Start and End. IDs that no longer exist are left out. response.Info, when not null, maps a provider wire string to a message about a provider that could not be read, or about calendars no connected account can read.
EventsListResponse response = await client.Events.ListAsync(new EventListParams
{
EventIds = new Dictionary<string, Dictionary<string, List<string>>>
{
["google"] = new() { ["ana@example.com"] = new() { "abc123", "def456" } },
},
SingleEvents = false,
});
Create an event
CalendarEvent created = await client.Events.CreateAsync(new EventCreateData
{
Provider = Provider.Google,
CalendarId = "primary",
Title = "Team Meeting",
Start = new DateTime(2024, 6, 15, 10, 0, 0, DateTimeKind.Utc),
End = new DateTime(2024, 6, 15, 11, 0, 0, DateTimeKind.Utc),
Description = "Quarterly review",
Location = "Conference Room A",
});
Console.WriteLine($"Created: {created.Id}");
Update an event
CalendarEvent updated = await client.Events.UpdateAsync(new EventUpdateData
{
Provider = Provider.Google,
CalendarId = "primary",
EventId = "event-id-to-update",
Title = "Team Meeting (Rescheduled)",
Start = new DateTime(2024, 6, 15, 14, 0, 0, DateTimeKind.Utc),
End = new DateTime(2024, 6, 15, 15, 0, 0, DateTimeKind.Utc),
});
Delete an event
await client.Events.DeleteAsync(new EventDeleteParams
{
Provider = Provider.Google,
CalendarId = "primary",
EventId = "event-id-to-delete",
});
Recurring events
// Update only this instance of a recurring event
await client.Events.UpdateAsync(new EventUpdateData
{
Provider = Provider.Google,
CalendarId = "primary",
EventId = "instance-id",
RecurringEventId = "series-id",
UpdateMode = "this",
Title = "One-off title change",
});
// Delete this and all following instances
await client.Events.DeleteAsync(new EventDeleteParams
{
Provider = Provider.Google,
CalendarId = "primary",
EventId = "instance-id",
RecurringEventId = "series-id",
DeleteMode = "following",
});
Webhooks
Pass the calendar's real ID from Calendars.ListAsync(); an alias such as primary creates a duplicate subscription. A ChannelId you supply that another user already holds is rejected with a MobiscrollConnectException (HTTP 409).
// Subscribe to change notifications for a calendar
WebhookSubscribeResponse subscription = await client.Webhooks.SubscribeWebhookAsync(new WebhookSubscribeData
{
Provider = Provider.Google,
CalendarId = "work@company.com",
});
Console.WriteLine($"Subscribed: {subscription.Subscription.ChannelId}");
// Unsubscribe later — resourceId is required by some providers (e.g. Google) to fully unsubscribe.
// Connect replaces the channel ID when it renews a subscription, so use the current one from the
// latest delivery's Metadata.ChannelId.
WebhookUnsubscribeResponse result = await client.Webhooks.UnsubscribeWebhookAsync(new WebhookUnsubscribeData
{
Provider = Provider.Google,
ChannelId = subscription.Subscription.ChannelId,
ResourceId = subscription.Subscription.ResourceId,
});
// Success is still true even if the provider-side subscription had already expired;
// check Message for details in that case.
if (result.Success)
Console.WriteLine("Unsubscribed successfully");
SingleEvents = false creates the channel in series mode: a changed Google series is delivered as its master event instead of every occurrence. true delivers every occurrence. Outlook, iCloud and CalDAV deliver the series master in both modes. When omitted, the channel keeps the mode of the subscription it replaces, otherwise the application's setting applies. subscription.SingleEvents is the mode the channel was created with (null when the response does not carry it).
WebhookSubscribeResponse seriesMode = await client.Webhooks.SubscribeWebhookAsync(new WebhookSubscribeData
{
Provider = Provider.Google,
CalendarId = "work@company.com",
SingleEvents = false,
});
Verify webhook deliveries
Every delivery to your webhook URL is signed. VerifyWebhookAsync() checks the signature and the timestamp, then returns the parsed WebhookDelivery, or throws WebhookVerificationException. Pass the raw request body: model binding or anything else that deserializes and re-serializes the JSON changes the bytes, and every check fails.
using Mobiscroll.Connect.Exceptions;
using Mobiscroll.Connect.Models;
app.MapPost("/webhooks/mobiscroll", async (HttpRequest request, MobiscrollConnectClient client) =>
{
using var body = new MemoryStream();
await request.Body.CopyToAsync(body);
WebhookDelivery delivery;
try
{
delivery = await client.Webhooks.VerifyWebhookAsync(body.ToArray(), request.Headers);
}
catch (WebhookVerificationException e)
{
return e.Reason == WebhookVerificationReason.NoPublicKeys
? Results.StatusCode(503)
: Results.Unauthorized();
}
await HandleDeliveryAsync(delivery);
return Results.NoContent();
});
Each event is a WebhookEvent, which is a CalendarEvent plus ChangeType. A delivery carries conference as an object (url, provider, meetingProvider, data); VerifyWebhookAsync converts it to the shape Events.ListAsync() returns: Conference is the join URL string (null when the object has no non-empty url) and ConferenceData is the REST shape (provider, autoGenerate when boolean, and the keys of data at the top level; null when empty). Deliveries from Connect 1.6.1 on carry conferenceData themselves, with url and original, and the SDK keeps it; for an earlier delivery the SDK builds it from the conference object, without url and original. A conference that is neither a string, an object nor null fails with InvalidPayload.
The body can be a byte[], ReadOnlyMemory<byte> or string. The headers can be ASP.NET Core's IHeaderDictionary, HttpHeaders, or any dictionary of header names to values; names are matched in any casing.
The public keys are fetched from https://connect.mobiscroll.com/.well-known/webhook-keys on the first delivery and cached for the whole process as the endpoint's Cache-Control allows. If no signature matches, the keys are fetched again (at most once a minute) before the delivery is rejected, so key rotations need no action on your side.
If your handler cannot make outbound requests, pin the key. WebhookPublicKey is used only when the keys endpoint cannot be reached; it stops working when Mobiscroll retires that key, so you must replace it on every rotation.
builder.Services.AddMobiscrollConnect(options =>
{
options.ClientId = builder.Configuration["Mobiscroll:ClientId"]!;
options.ClientSecret = builder.Configuration["Mobiscroll:ClientSecret"]!;
options.RedirectUri = builder.Configuration["Mobiscroll:RedirectUri"]!;
options.WebhookPublicKey = builder.Configuration["Mobiscroll:WebhookPublicKey"]; // whpk_...
});
To check against keys you supply, with no fetching, call WebhookVerifier.VerifyWebhookSignature(rawBody, headers, new[] { "whpk_..." }). It throws WebhookVerificationException and returns nothing. See Verifying deliveries.
Connection Management
// Check which providers are connected
ConnectionStatusResponse status = await client.Auth.GetConnectionStatusAsync();
if (status.Connections.TryGetValue("google", out var googleAccounts))
foreach (ConnectedAccount acct in googleAccounts)
{
Console.WriteLine($"Google: {acct.Display} ({acct.Id})");
// Google's consent screen lets the user untick the calendar permission and still
// finish signing in. Such an account is connected but lists no calendars.
if (acct.CalendarPermissionGranted == false)
Console.WriteLine($" {acct.Id} must reconnect and allow calendar access");
}
if (status.LimitReached)
Console.WriteLine("Connection limit reached");
// Disconnect one account (its Id from GetConnectionStatusAsync), or every account of a provider
// when Account is null. This stops the account's webhook subscriptions and deletes its provider
// credentials; it does not revoke the user's Connect tokens.
DisconnectResponse result = await client.Auth.DisconnectAsync(new DisconnectParams
{
Provider = Provider.Google,
Account = "user@gmail.com",
});
if (result.Success)
Console.WriteLine("Disconnected successfully");
Revoke Tokens
RevokeAsync() revokes the whole grant: every Connect access and refresh token of the user. It does not disconnect calendar accounts or stop webhooks, so to remove a user entirely, disconnect each provider first (that needs a valid access token), then revoke.
await client.Auth.RevokeAsync(); // stored refresh token, else access token; clears the stored credentials
await client.Auth.RevokeAsync(storedRefreshToken); // a token you pass; stored credentials are kept
It returns RevokeResponse { Success = true } for any token, including an unknown or already revoked one. With no argument and no stored credentials it throws ValidationException without making a request.
Error Handling
All SDK methods throw exceptions that extend MobiscrollConnectException:
| Exception | HTTP Status | Extra member |
|---|---|---|
AuthenticationException |
401, 403 | — |
ValidationException |
400, 422 | Details (object?) |
NotFoundException |
404 | — |
RateLimitException |
429 | RetryAfter (int?) |
ServerException |
5xx | StatusCode (int) |
NetworkException |
— | — |
WebhookVerificationException |
— (from VerifyWebhookAsync()) |
Reason (WebhookVerificationReason) |
using Mobiscroll.Connect.Exceptions;
try
{
var events = await client.Events.ListAsync();
}
catch (AuthenticationException)
{
// Token expired and refresh failed — re-authorize the user
}
catch (ValidationException ex)
{
var details = ex.Details; // field-level errors
}
catch (NotFoundException)
{
// Calendar or event not found
}
catch (RateLimitException ex)
{
var retryAfter = ex.RetryAfter; // seconds
}
catch (ServerException ex)
{
var status = ex.StatusCode; // 500, 502, 503, 504
}
catch (NetworkException)
{
// Connection failed
}
catch (MobiscrollConnectException)
{
// Catch-all
}
Testing
# Build the solution
dotnet build
# Run all tests
dotnet test
# Run with coverage
dotnet test --collect:"XPlat Code Coverage"
Project Structure
src/
└── Mobiscroll.Connect/
├── Exceptions/
│ ├── MobiscrollConnectException.cs
│ ├── AuthenticationException.cs
│ ├── ValidationException.cs
│ ├── NotFoundException.cs
│ ├── RateLimitException.cs
│ ├── ServerException.cs
│ ├── NetworkException.cs
│ └── WebhookVerificationException.cs
├── Models/
│ ├── TokenResponse.cs
│ ├── CalendarEvent.cs
│ ├── EventsListResponse.cs
│ ├── Calendar.cs
│ ├── ConnectionStatusResponse.cs
│ ├── DisconnectResponse.cs
│ ├── RevokeResponse.cs
│ ├── AuthorizeParams.cs
│ ├── EventListParams.cs
│ ├── EventCreateData.cs
│ ├── EventUpdateData.cs
│ ├── EventDeleteParams.cs
│ ├── DisconnectParams.cs
│ ├── EventAttendee.cs
│ ├── RecurrenceRule.cs
│ ├── WebhookSubscribeData.cs
│ ├── WebhookSubscribeResponse.cs
│ ├── WebhookUnsubscribeData.cs
│ ├── WebhookUnsubscribeResponse.cs
│ └── WebhookDelivery.cs
├── Resources/
│ ├── Auth.cs
│ ├── Calendars.cs
│ ├── Events.cs
│ └── Webhooks.cs
├── ApiClient.cs
├── MobiscrollConnectClient.cs
├── MobiscrollConnectConfig.cs
├── Provider.cs
└── WebhookVerifier.cs
tests/
└── Mobiscroll.Connect.Tests/
├── ApiClientTests.cs
├── AuthTests.cs
├── CalendarsTests.cs
├── EventsTests.cs
├── WebhooksTests.cs
├── WebhookVerifierTests.cs
├── WebhookVerificationTests.cs
├── ErrorMappingTests.cs
└── SerializationTests.cs
samples/
└── MinimalApp/
└── Program.cs
License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.0
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.2)
- Microsoft.Extensions.Http (>= 8.0.1)
- Microsoft.Extensions.Options (>= 8.0.2)
- NSec.Cryptography (>= 25.4.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.