### Get P12 Certificate Raw Data in Base64 (C#) Source: https://github.com/alexalok/dotapns/wiki/Unit-testing This C# code snippet demonstrates how to load a .p12 certificate file, extract its raw data, and convert it to a Base64 encoded string. This is useful for populating the `dotapns_tests_p12_base64enc` field in the env.json file. ```csharp var cert = new X509Certificate2("path/to/my/cert.p12"); var bytes = cert.GetRawCertData(); string base64 = Convert.ToBase64String(bytes); Console.WriteLine(base64); ``` -------------------------------- ### Send Background Push Notification with JWT Source: https://github.com/alexalok/dotapns/blob/master/README.md Example of sending a background push notification using JWT authentication. The ApplePush object is configured with content-available and the device token. ```csharp var push = new ApplePush(ApplePushType.Background) .AddContentAvailable() .AddToken("token"); var options = new ApnsJwtOptions() { ... }; var response = await _apnsService.SendPush(push, options); ``` -------------------------------- ### Create ApnsClient using X509Certificate2 Object Source: https://github.com/alexalok/dotapns/blob/master/README.md Instantiate the ApnsClient by providing an X509Certificate2 object. This is an alternative to providing a file path directly. Requires .NET Core 3.0 and above. ```csharp var cert = new X509Certificate2("voip.p12"); var apns = ApnsClient.CreateUsingCert(cert); ``` -------------------------------- ### Create ApnsClient using Certificate File Source: https://github.com/alexalok/dotapns/blob/master/README.md Instantiate the ApnsClient using a .p12 certificate file. Ensure the file path is correct. This method is supported on .NET Core 3.0 and above. ```csharp var apns = ApnsClient.CreateUsingCert("voip.p12"); ``` -------------------------------- ### Injecting and Using IApnsService Source: https://github.com/alexalok/dotapns/blob/master/README.md Demonstrates how to inject the IApnsService into controllers and use its methods to send push notifications. ```APIDOC ## Injecting and Using IApnsService ### Description After registering `ApnsService`, you can inject the `IApnsService` interface into your controllers or other services to send push notifications. ### Method Signatures ```csharp Task SendPush(ApplePush push, X509Certificate2 cert); Task SendPush(ApplePush push, ApnsJwtOptions jwtOptions); Task> SendPushes(IReadOnlyCollection pushes, X509Certificate2 cert); Task> SendPushes(IReadOnlyCollection pushes, ApnsJwtOptions jwtOptions); ``` ### Injection Inject the `IApnsService` interface into your class constructor. ```csharp readonly IApnsService _apnsService; public MyController(IApnsService apnsService) { _apnsService = apnsService; } ``` ### Sending a Simple Background Push An example of sending a background push notification using token-based authentication. ```csharp var push = new ApplePush(ApplePushType.Background) .AddContentAvailable() .AddToken("device_token"); var options = new ApnsJwtOptions() { // Configure your JWT options here, e.g.: // KeyId = "YOUR_KEY_ID", // TeamId = "YOUR_TEAM_ID", // PrivateKeyPath = "path/to/your/private.p8" }; var response = await _apnsService.SendPush(push, options); ``` ### Parameters - **push** (`ApplePush`): The push notification payload. - **cert** (`X509Certificate2`): The certificate for certificate-based authentication. - **jwtOptions** (`ApnsJwtOptions`): The options for token-based (JWT) authentication. - **pushes** (`IReadOnlyCollection`): A collection of push notifications to send. ### Response - **ApnsResponse**: An object containing the result of sending a single push notification. - **List**: A list of results for sending multiple push notifications. ``` -------------------------------- ### Configure APNS Certificates for Unit Tests (env.json) Source: https://github.com/alexalok/dotapns/wiki/Unit-testing Use this JSON structure in `./dotAPNS/dotAPNS.Tests/env.json` to provide paths and contents for APNS certificates required for unit testing. Replace placeholder values with your actual certificate details. ```json { "dotapns_tests_p8_path": "REPLACE_TO_PATH_OF_YOUR_P8_CERTIFICATE_FILE", "dotapns_tests_p8_contents" : "REPLACE_WITH_YOUR_P8_CERTIFICATE_CONTENTS", "dotapns_tests_p12_base64enc" : "REPLACE_WITH_YOUR_P12_CERTIFICATE_RAW_CERT_DATA_BASE64ENCODED" } ``` -------------------------------- ### HttpClient with WinHttpHandler for .NET Framework Source: https://github.com/alexalok/dotapns/blob/master/README.md Workaround for .NET Framework to ensure HttpClient has HTTP/2 support by using the WinHttpHandler. This is crucial for establishing a compliant connection to APNs. ```csharp new HttpClient(new WinHttpHandler()) ``` -------------------------------- ### Register dotAPNS Service in ASP.NET Core Source: https://github.com/alexalok/dotapns/blob/master/README.md Call AddApns() in your Startup class's ConfigureServices method to register the ApnsService. This sets up the HttpClient, ApnsClientFactory, and ApnsService as singletons. ```csharp public void ConfigureServices(IServiceCollection services) { sservices.AddRazorPages(); services.AddApns(); // <-- this call registers ApnsService // ... } ``` -------------------------------- ### Send Basic Alert Push Notification in C# Source: https://github.com/alexalok/dotapns/blob/master/README.md Use this to send a simple alert notification. Ensure ApnsJwtOptions are correctly configured and the client is initialized. Handles various APNs response reasons and HTTP exceptions. ```csharp var options = new ApnsJwtOptions() { ... }; var apns = ApnsClient.CreateUsingJwt(new HttpClient(), options); var push = new ApplePush(ApplePushType.Alert) .AddAlert("title", "body") .AddToken("token"); try { var response = await apns.Send(push); if (response.IsSuccessful) { Console.WriteLine("An alert push has been successfully sent!"); } else { switch (response.Reason) { case ApnsResponseReason.BadCertificateEnvironment: // The client certificate is for the wrong environment. // TODO: retry on another environment break; // TODO: process other reasons we might be interested in default: throw new ArgumentOutOfRangeException(nameof(response.Reason), response.Reason, null); } Console.WriteLine("Failed to send a push, APNs reported an error: " + response.ReasonString); } } catch (TaskCanceledException) { Console.WriteLine("Failed to send a push: HTTP request timed out."); } catch (HttpRequestException ex) { Console.WriteLine("Failed to send a push. HTTP request failed: " + ex); } catch (ApnsCertificateExpiredException) { Console.WriteLine("APNs certificate has expired. No more push notifications can be sent using it until it is replaced with a new one."); } ``` -------------------------------- ### Configure APNs JWT Options Source: https://github.com/alexalok/dotapns/blob/master/README.md Specify options required for JWT authentication with APNs. Use either certificate content or file path, but not both. Ensure BundleId does not include specific topics. ```csharp var options = new ApnsJwtOptions() { BundleId = "bundle", CertContent = "-----BEGIN PRIVATE KEY-----\r\nMIGTA ... -----END PRIVATE KEY-----", // CertFilePath = "secret.p8", // use either CertContent or CertFilePath, not both KeyId = "key", TeamId = "team" }; ``` -------------------------------- ### Create APNs Client with JWT Source: https://github.com/alexalok/dotapns/blob/master/README.md Instantiate an APNs client using JWT authentication. You must provide an HttpClient instance to manage its lifecycle. Ensure the HttpClient has HTTP/2 support, especially on .NET Framework. ```csharp var options = new ApnsJwtOptions() { ... }; var apns = ApnsClient.CreateUsingJwt(new HttpClient(), options); ``` -------------------------------- ### Send Background Push Notification in C# Source: https://github.com/alexalok/dotapns/blob/master/README.md Use this to send a silent background push notification. Background pushes are subject to Apple's limitations and cannot be circumvented. ```csharp var push = new ApplePush(ApplePushType.Background) .AddContentAvailable() .AddToken("replaceme"); ``` -------------------------------- ### Registering ApnsService Source: https://github.com/alexalok/dotapns/blob/master/README.md Automatically registers ApnsService, ApnsClientFactory, and a named HttpClient for dotAPNS within your ASP.NET Core application's dependency injection container. ```APIDOC ## Registering ApnsService ### Description This method registers the necessary services for dotAPNS integration into your ASP.NET Core application. ### Method `services.AddApns();` ### Parameters None ### Usage Call this method within the `ConfigureServices` method of your `Startup` class. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); services.AddApns(); // Registers ApnsService, ApnsClientFactory, and HttpClient // ... } ``` ``` -------------------------------- ### Add Custom Property to Push Payload Root in C# Source: https://github.com/alexalok/dotapns/blob/master/README.md Add a custom field to the root of the APNs payload using `AddCustomProperty`. ```csharp var push = new ApplePush(ApplePushType.Alert) .AddCustomProperty("thread-id", "123"); ``` -------------------------------- ### Inject IApnsService in ASP.NET Core Controller Source: https://github.com/alexalok/dotapns/blob/master/README.md Inject the IApnsService interface into your controllers or services to gain access to its methods for sending push notifications. Do not inject the concrete type. ```csharp readonly IApnsService _apnsService; public MyController(IApnsService apnsService) { _apnsService = apnsService; } ``` -------------------------------- ### Add Custom Property to APNs Payload 'aps' Section in C# Source: https://github.com/alexalok/dotapns/blob/master/README.md Add a custom field to the 'aps' section of the APNs payload by setting the `addInAps` parameter to true in `AddCustomProperty`. ```csharp var push = new ApplePush(ApplePushType.Alert) .AddCustomProperty("thread-id", "123", true); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.