Giter Club home page Giter Club logo

onesignal-dotnet-api's Introduction

OneSignalApi - the C# library for the OneSignal

A powerful way to send personalized messages at scale and build effective customer engagement strategies. Learn more at onesignal.com

  • API version: 1.2.2
  • SDK version: 2.0.2
  • Build package: org.openapitools.codegen.languages.CSharpNetCoreClientCodegen For more information, please visit https://onesignal.com

Frameworks supported

  • .NET Core >=1.0
  • .NET Framework >=4.6
  • Mono/Xamarin >=vNext

Dependencies

The DLLs included in the package may not be the latest version. We recommend using NuGet to obtain the latest version of the packages:

Install-Package RestSharp
Install-Package Newtonsoft.Json
Install-Package JsonSubTypes
Install-Package System.ComponentModel.Annotations

NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See RestSharp#742. NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See RestSharp#1406.

Installation

Generate the DLL using your preferred tool (e.g. dotnet build)

Then include the DLL (under the bin folder) in the C# project, and use the namespaces:

using OneSignalApi.Api;
using OneSignalApi.Client;
using OneSignalApi.Model;

Usage

To use the API client with a HTTP proxy, setup a System.Net.WebProxy

Configuration c = new Configuration();
System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/");
webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
c.Proxy = webProxy;

Getting Started

using System.Collections.Generic;
using System.Diagnostics;
using OneSignalApi.Api;
using OneSignalApi.Client;
using OneSignalApi.Model;

namespace Example
{
    public class Example
    {
        public static void Main()
        {
            // Configure configuration with user_key Bearer token for authorization to access endpoints
            // that require the OneSignal User Auth Key.
            var userConfig = new Configuration();
            userConfig.BasePath = "https://onesignal.com/api/v1";
            userConfig.AccessToken = "USER_AUTH_KEY";
            
            var userInstance = new DefaultApi(userConfig);

            try
            {
                // Create a new app
                var app = new App(name: "Sample App");
                var result = userInstance.CreateApp(app);
                Debug.WriteLine(result);
            }
            catch (ApiException e)
            {
                Debug.Print("Exception when calling DefaultApi.CreateApp: " + e.Message );
                Debug.Print("Status Code: "+ e.ErrorCode);
                Debug.Print(e.StackTrace);
            }


            // Configure configuration with app_key Bearer token for authorization to access endpoints
            // that require the OneSignal App REST API Key.
            var appConfig = new Configuration();
            appConfig.BasePath = "https://onesignal.com/api/v1";
            appConfig.AccessToken = "REST_API_KEY";
            
            var appInstance = new DefaultApi(appConfig);

            var appId = "appId_example";  // string | 
            var notificationId = "notificationId_example";  // string | 
            try
            {
                // Stop a scheduled or currently outgoing notification
                var result = appInstance.CancelNotification(appId, notificationId);
                Debug.WriteLine(result);
            }
            catch (ApiException e)
            {
                Debug.Print("Exception when calling DefaultApi.CancelNotification: " + e.Message );
                Debug.Print("Status Code: "+ e.ErrorCode);
                Debug.Print(e.StackTrace);
            }
        }
    }
}

Documentation for API Endpoints

All URIs are relative to https://onesignal.com/api/v1

Class Method HTTP request Description
DefaultApi BeginLiveActivity POST /apps/{app_id}/live_activities/{activity_id}/token Start Live Activity
DefaultApi CancelNotification DELETE /notifications/{notification_id} Stop a scheduled or currently outgoing notification
DefaultApi CreateApp POST /apps Create an app
DefaultApi CreateNotification POST /notifications Create notification
DefaultApi CreatePlayer POST /players Add a device
DefaultApi CreateSegments POST /apps/{app_id}/segments Create Segments
DefaultApi CreateSubscription POST /apps/{app_id}/users/by/{alias_label}/{alias_id}/subscriptions
DefaultApi CreateUser POST /apps/{app_id}/users
DefaultApi DeleteAlias DELETE /apps/{app_id}/users/by/{alias_label}/{alias_id}/identity/{alias_label_to_delete}
DefaultApi DeletePlayer DELETE /players/{player_id} Delete a user record
DefaultApi DeleteSegments DELETE /apps/{app_id}/segments/{segment_id} Delete Segments
DefaultApi DeleteSubscription DELETE /apps/{app_id}/subscriptions/{subscription_id}
DefaultApi DeleteUser DELETE /apps/{app_id}/users/by/{alias_label}/{alias_id}
DefaultApi EndLiveActivity DELETE /apps/{app_id}/live_activities/{activity_id}/token/{subscription_id} Stop Live Activity
DefaultApi ExportEvents POST /notifications/{notification_id}/export_events?app_id={app_id} Export CSV of Events
DefaultApi ExportPlayers POST /players/csv_export?app_id={app_id} Export CSV of Players
DefaultApi FetchAliases GET /apps/{app_id}/subscriptions/{subscription_id}/user/identity
DefaultApi FetchUser GET /apps/{app_id}/users/by/{alias_label}/{alias_id}
DefaultApi FetchUserIdentity GET /apps/{app_id}/users/by/{alias_label}/{alias_id}/identity
DefaultApi GetApp GET /apps/{app_id} View an app
DefaultApi GetApps GET /apps View apps
DefaultApi GetEligibleIams GET /apps/{app_id}/subscriptions/{subscription_id}/iams
DefaultApi GetNotification GET /notifications/{notification_id} View notification
DefaultApi GetNotificationHistory POST /notifications/{notification_id}/history Notification History
DefaultApi GetNotifications GET /notifications View notifications
DefaultApi GetOutcomes GET /apps/{app_id}/outcomes View Outcomes
DefaultApi GetPlayer GET /players/{player_id} View device
DefaultApi GetPlayers GET /players View devices
DefaultApi IdentifyUserByAlias PATCH /apps/{app_id}/users/by/{alias_label}/{alias_id}/identity
DefaultApi IdentifyUserBySubscriptionId PATCH /apps/{app_id}/subscriptions/{subscription_id}/user/identity
DefaultApi TransferSubscription PATCH /apps/{app_id}/subscriptions/{subscription_id}/owner
DefaultApi UpdateApp PUT /apps/{app_id} Update an app
DefaultApi UpdateLiveActivity POST /apps/{app_id}/live_activities/{activity_id}/notifications Update a Live Activity via Push
DefaultApi UpdatePlayer PUT /players/{player_id} Edit device
DefaultApi UpdatePlayerTags PUT /apps/{app_id}/users/{external_user_id} Edit tags with external user id
DefaultApi UpdateSubscription PATCH /apps/{app_id}/subscriptions/{subscription_id}
DefaultApi UpdateUser PATCH /apps/{app_id}/users/by/{alias_label}/{alias_id}

Documentation for Models

Documentation for Authorization

app_key

  • Type: Bearer Authentication

user_key

  • Type: Bearer Authentication

onesignal-dotnet-api's People

Contributors

brismithers avatar jkasten2 avatar kesheshyan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

onesignal-dotnet-api's Issues

[question]: How do I send a notification filtering the users role OR location?

How can we help?

I've got a use case to send users a push notifcation based on their role OR location. How do I use the CreateNotificationAsync method to send a notification based on such criteria?

According to the documentation, in order to correctly specify this behavior, I believe the final json data would be something like:

{
  ...
  "filters": [
    {"field": "tag", "key": "is_admin", "relation": "=", "value": "true"},
    {"operator": "OR"}, {"field": "location", "lat": "37.5426574", "long" : "-122.3019626", "radius": "100" }
  ]
}

With this, I believe there is two issues:

  1. The OR operator must be suported for filters - a Pull Request submited by @bnoffer should fix this.
  2. The lat, long and radius props must be added to the Filter class/model.

Any ideia how can I achieve this? Let me know if i can help submiting a PR.

Victor Gazzinelli

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: CreateNotificationSuccessResponse.Recipients = 0 after sending push.

What happened?

we are sending notifications and the response.Recipients is always = 0, but we have few active devices that receive them.

Steps to reproduce?

this is my code (using asp.net mvc)

if (ModelState.IsValid)
			{
				// prepara record
				PushNotification push = new PushNotification
				{
					Note = pushvm.Note,
					Title = pushvm.Title,
					Language = (int)pushvm.Language,
					UCode = StringUtils.CleanString(MAGNETICA.Utils.Funzioni.GenerateHashMD5(MAGNETICA.Utils.Funzioni.CreateUnixTime())),
					InsDate = DateTime.Now,
					InsUser = User.Identity.Name,
					Sent = false
				};

				//invio push
				OneSignalApi.Client.Configuration config = new OneSignalApi.Client.Configuration();
				config.BasePath = "https://onesignal.com/api/v1";
				config.AccessToken = ConfigurationManager.AppSettings["OneSignalRestAPIKey"];

				var apiInstance = new DefaultApi(config);

				StringMap headings;
				StringMap content;
				string segment;
				if (pushvm.Language == PushLanguage.Italian)
				{
					headings = new StringMap(it: pushvm.Title, en: pushvm.Title);
					content = new StringMap(it: pushvm.Note, en: pushvm.Note);
					segment = "Lang-it";
				}
				else
				{
					headings = new StringMap(en: pushvm.Title);
					content = new StringMap(en: pushvm.Note);
					segment = "Lang-end";
				}
				var notification = new Notification(appId: ConfigurationManager.AppSettings["OneSignalAppID"])
				{
					SmallIcon = ConfigurationManager.AppSettings["BaseUrl"] + "/Content/Media/logos/AppIcon.png",
					IncludedSegments = new List<string> { segment },
					Headings = headings,
					Contents = content,
				}; // Notification | 

				try
				{
					// Create notification
					CreateNotificationSuccessResponse result = await apiInstance.CreateNotificationAsync(notification);

					push.Sent = true;
					push.SendDate = DateTime.Now;
					push.Recipients = result.Recipients;
				}
				catch (ApiException e)
				{
					//Debug.Print("Exception when calling DefaultApi.CreateNotification: " + e.Message);
					//Debug.Print("Status Code: " + e.ErrorCode);
					//Debug.Print(e.StackTrace);
				}

				_moDb.PushNotifications.Add(push);
				_moDb.SaveChanges();

				return RedirectToAction("Index");
			}

			return View(pushvm);

What did you expect to happen?

receive the number of recipients

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

How do I filter by tags?

How can we help?

How should be the Tag field be formatted to filter by tags?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Mรฉthode introuvableย : 'Void RestSharp.RestRequest..ctor(RestSharp.Method)'.

What happened?

Good morning ,
I'm trying OneSignal's server-side API to send push notifications.

When I execute the method CreateNotificationSuccessResponse result = appInstance.CreateNotification(notification);

var appConfig = new Configuration();
appConfig.BasePath = "https://onesignal.com/api/v1";
appConfig.AccessToken = "ApiKey";

var appInstance = new DefaultApi(appConfig);

var notification = new Notification(appId: "app id");

StringMap stringMap = new StringMap();
stringMap.En = message;
notification.Contents = stringMap;
notification.ExternalId = Guid.NewGuid().ToString();
if (!string.IsNullOrWhiteSpace(link))
{
notification.Url = link;
}
if (Subcription.Count > 0)
{
notification.IncludedSegments = Subcription;
}
if (ExternalID.Count > 0)
{
PlayerNotificationTargetIncludeAliases playerNotificationTargetIncludeAliases = new PlayerNotificationTargetIncludeAliases(ExternalID);
notification.IncludeAliases = playerNotificationTargetIncludeAliases;
}
try
{
// Create notification
CreateNotificationSuccessResponse result = appInstance.CreateNotification(notification);
return result.Id + " --- "+result.Recipients.ToString();
}
catch (ApiException e)
{
Debug.Print("Exception when calling DefaultApi.CreateNotification: " + e.Message);
Debug.Print("Status Code: " + e.ErrorCode);
Debug.Print(e.StackTrace);
return "Exception when calling DefaultApi.CreateNotification: " + e.Message;
}

I have this error Method not found: 'Void RestSharp.RestRequest..ctor(RestSharp.Method)'.

Steps to reproduce?

OneSignalApi 2.0.2
RestSharp 110.2.0

What did you expect to happen?

ร  OneSignalApi.Client.ApiClient.NewRequest(HttpMethod method, String path, RequestOptions options, IReadableConfiguration configuration)
ร  OneSignalApi.Client.ApiClient.Post[T](String path, RequestOptions options, IReadableConfiguration configuration)
ร  OneSignalApi.Api.DefaultApi.CreateNotificationWithHttpInfo(Notification notification, Int32 operationIndex)
ร  OneSignalApi.Api.DefaultApi.CreateNotification(Notification notification, Int32 operationIndex)
ร  WebAPI.Helper.Utils.SendNotification(String message, List1 Subcription, List1 ExternalID, String link) dans D:\WORK\APPLICATION\CNPS\MA CNPS A MOI\AppMobile\WEP API\WebAPI\Helper\Utils.cs :ligne 967
ร  WebAPI.Controllers.CallBackAPIController.testsss() dans D:\WORK\APPLICATION\CNPS\MA CNPS A MOI\AppMobile\WEP API\WebAPI\Controllers\CallBackAPIController.cs :ligne 3079

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: RestSharp constructor not found

What happened?

Version 1.0.1 of the OneSignalApi throws an exception when sending a notification because it can't find a constructor in the RestSharp package.

Message: Method not found: 'Void RestSharp.RestRequest..ctor(RestSharp.Method)'.

StackTrace:
System.MissingMethodException: Method not found: 'Void RestSharp.RestRequest..ctor(RestSharp.Method)'.\r\n at OneSignalApi.Client.ApiClient.NewRequest(HttpMethod method, String path, RequestOptions options, IReadableConfiguration configuration)\r\n at OneSignalApi.Client.ApiClient.Post[T](String path, RequestOptions options, IReadableConfiguration configuration)\r\n at OneSignalApi.Api.DefaultApi.CreateNotificationWithHttpInfo(Notification notification, Int32 operationIndex)\r\n at OneSignalApi.Api.DefaultApi.CreateNotification(Notification notification, Int32 operationIndex)\r\n

Using RestSharp 108.0.1, I don't see a constructor in their code that matches the pattern of just taking in a Method.

I'm mixing a .NET Framework API with a .NET Standard Class Library, and the required packages are installed in both projects.

Code Snippet (inside the .NET Standard Class Library, called from the .NET Framework API):

var restApiKey = "......";
var Configuration = new OneSignalApi.Client.Configuration();
Configuration.BasePath = "https://onesignal.com/api/v1";
Configuration.AccessToken = restApiKey;
Configuration.ApiKey.Add("default", restApiKey);

var model = new OneSignalApi.Model.Notification(appId: AppId)
 {
    IncludeExternalUserIds = new List<string> { "..." },
    Name = "Test Message",
    ChannelForExternalUserIds = "push"
};

model.Contents = new OneSignalApi.Model.StringMap { En = "message contents" };

var api = new DefaultApi(Configuration);
var result = api.CreateNotification(model);
return !String.IsNullOrWhiteSpace(result.Id);

Steps to reproduce?

1. Create .NET Framework 4.8.1 API
2. Create .NET Standard 2.0 Class Library
3. Install packages: OneSignalApi 1.0.1, RestSharp 108.0.1, Newtonsoft.Json 13.0.1, JsonSubTypes 1.9.0, System.ComponentModel.Annotations 5.0.0 in both projects
4. Call the class library from the api
5. Get error

What did you expect to happen?

I expected the API to send a push notification message.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

CreateNotificationAsync returns random null value

How can we help?

Hi

From time to time, when I try to send an email, the CreateNotificationAsync(...) returns a null value, instead of a CreateNotificationSuccessResponse, and the email does not get sent.
The fact that it returns a null value makes it impossible to debug, even more as the bug is totally unpredictable. And I can't see any way to get the trace of the api call on the onesignal dashboard ?
Does anyone get this error too ?
Thanks

Julien

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: When creating new segment always getting null exception.

What happened?

Although I set name property of segment I getting null exception.

My code is below:

        public void CreateSegment(string segmentName)
        {
            Segment newSegment = new()
            {
                Name = segmentName
            };
            var filterItem = new FilterExpressions(new Filter(field: "user_tag", relation: Filter.RelationEnum.Equal, value: segmentName));
            newSegment.Filters.Add(filterItem);

            _appInstance.CreateSegments(appId: _appId, segment: newSegment);
        }

SS attachment

![one_signal_create_segment](https://github.com/OneSignal/onesignal-dotnet-api/assets/105269510/e629b655-aed8-43fd-be58-d9cac4c5b004)

Steps to reproduce?

1. Installed RestSharp v108.0.3
2. Installed OneSignal Api v2.0.2

What did you expect to happen?

I expected to create new segment

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

Update RestSharp dependency

What happened?

There's a conflict when trying to add the package to our project, because we're using version 108.0.1 of RestSharp, but the package is using an older version.

Steps to reproduce?

1. Install the package on a project with RestSharp version 108.0.1

What did you expect to happen?

The dependency should be updated to the last available version

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]:

What happened?

Everythings works when I develop on Windows using Visual Studio 2022 and send notification well to all targets. But when I build and deploy app to ubuntu 20/06 server. I got error and app can not create notification.
OnsignalLog.txt


public static void SendNotification(string targetGroup, string message)
        {
            try
            {
                // Configure the OneSignal Library
                var appConfig = new Configuration();
                appConfig.BasePath = "https://onesignal.com/api/v1";
                appConfig.AccessToken = "API KEY";
                var appInstance = new DefaultApi(appConfig);

                // Create and send notification to all subscribed users
                var notification = new Notification(appId: "ID")
                {
                    Contents = new StringMap(en: message),
                    IncludedSegments = new List { targetGroup }
                };
                var response = appInstance.CreateNotification(notification);

                Console.WriteLine($"Notification created for {response} recipients");
            }
            catch (Exception e)
            {

                Console.WriteLine(e.Message);
            }
        }

Steps to reproduce?

1. Create dotnet app. 
2. Add notification example to app
3. Build and deploy to ubuntu 20.04
4. Try to create notification

What did you expect to happen?

I expected to create and send notification to users on ubuntu 20.04 LTS

Relevant log output

OneSignalApi.Client.ApiException: Error calling CreateNotification: <!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Just a moment...</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="robots" content="noindex,nofollow" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <link href="/cdn-cgi/styles/cf-errors.css" rel="stylesheet" />

<script>
    (function(){
        window._cf_chl_opt={
            cvId: '2',
            cType: 'managed',
            cNounce: '53946',
            cRay: '73d172891fa462fd',
            cHash: 'c7a2d5fcc435852',
            cUPMDTk: "\/api\/v1\/notifications?__cf_chl_tk=f4JGP6XJf9US8CTq2aw2HenxZBUf1Eb8t81JGcAxxBU-1660896989-0-gaNycGzNCSU",
            cFPWv: 'g',
            cTTimeMs: '1000',
            cTplV: 3,
            cRq: {
                ru: 'aHR0cHM6Ly9vbmVzaWduYWwuY29tL2FwaS92MS9ub3RpZmljYXRpb25z',
                ra: 'T3BlbkFQSS1HZW5lcmF0b3IvMS4wLjAvY3NoYXJw',
                rm: 'UE9TVA==',
                d: 'k5QAF2SNlvSut+0Lnw//CZyeQUFiNv/Q1H9nDij/JTIo6nq44r6WWnvoRbP4hS4g1A9XS/aTc4wCWQ8XJ6lddwE5ILDYFYr8gJSl2t/4sSDjS+/Tga5wDllRpm1tfRYes+ZiMwdiv1pVPIqvXoX5l+6Q0e8dw8/5F/Jv/0rxlZRvL3WXGF+EmP8WVU1udIKppedAZvSaH8qu7owotCyqsnJTINbpIjMHH0SjzXp0M4y4/zt5tf1QA9nR6X9yIuBlYfWyWaJQE40t9DV06mD1siSYEeD55pBFr4jTnc2CMroszyCp8yaoIhyBPX+Z8SyEkS1khcGALAhd2/berxY3lVrXi5asQxXbp82QUAEmngsRNYlksanCW75s/zNQwmb1WXDJHGHRIQkCuDR1gtdVHCJONZfgUO01OE3tbG67VtZ+m70gc68MMQiRxOiypDcDyMR082gAvlVyoyPvq0UF+wUtwYBbzeKti0hY6A1SEefPKBgpaIY95HJ6irjaQ1FsinJFViIB1yeKlY+QPAoW+XNt96MalMUg1uHoMb4YIIeA7mSEO+qSFHYsoHxR/lFEqXOHF+xDMw66rJpjfGdA/j2znb+qmUbaR9K/pC2OLS4=',
                t: 'MTY2MDg5Njk4OS42MjUwMDA=',
                m: 'kaGwi0BeSuUxnHoQ/oCtFj9NdmEc4yQKluKl503D0Xk=',
                i1: 'TVcb5Z9MgIzFCAMZt70xyg==',
                i2: 'R2PTJv8cYopd2HvlFI6bSw==',
                zh: '+KtgPo/etXk/GhHkem7tMZGOSg+gOJkBazFZCJPDJfE=',
                uh: 'ynrEyNrE9W/VYtc6AlBXRaWCGMXJ5I2ireFswieWvCQ=',
                hh: 'wevBjSckyDZXN5+oz/bYe5ROXBZcjTVK/NgF2DnUshM=',
            }
        }
        window._cf_chl_enter = function(){window._cf_chl_opt.p=1};
    })();
</script>

</head>
<body class="no-js">
    <div class="main-wrapper" role="main">
    <div class="main-content">
        <h1 class="zone-name-title h1">
            <img class="heading-favicon" src="/favicon.ico"
                 onerror="this.onerror=null;this.parentNode.removeChild(this)" />
            onesignal.com
        </h1>
        <h2 class="h2" id="cf-challenge-running">
            Checking if the site connection is secure
        </h2>
        <noscript>
            <div id="cf-challenge-error-title">
                <div class="h2">
                    <span class="icon-wrapper">
                        <div class="heading-icon warning-icon"></div>
                    </span>
                    <span id="cf-challenge-error-text">
                        Enable JavaScript and cookies to continue
                    </span>
                </div>
            </div>
        </noscript>
        <div id="trk_jschal_js" style="display:none;background-image:url('/cdn-cgi/images/trace/managed/nojs/transparent.gif?ray=73d172891fa462fd')"></div>
        <div id="cf-challenge-body-text" class="core-msg spacer">
            onesignal.com needs to review the security of your connection before
            proceeding.
        </div>
        <form id="challenge-form" action="/api/v1/notifications?__cf_chl_f_tk=f4JGP6XJf9US8CTq2aw2HenxZBUf1Eb8t81JGcAxxBU-1660896989-0-gaNycGzNCSU" method="POST" enctype="application/x-www-form-urlencoded">
            <input type="hidden" name="md" value="sHlVEp1AOoQzlI3YENRyMiMAGoLAF7eum2vBzOG_1Q0-1660896989-0-ATc-NqJWxQ1OGRtPc3w8MuWNtOwPOnQSPFVxs0SCepmtlUlSKM5Rq-cdeQh9cIDq5OAuk-TK4s9qlbm9bM7JGZvwFIt2zdWM1VAz4zam_b2pPz8635QeiZOwENm5KJ7P2MIVro_TBkRzRuwWgEgeKgj-RVxkRl90UPB8bvLW9RW26bf9-7aoAL8WnKJI_3fhVZO57mHBoal_HaeKqoCN15TsVa3WqgthuUaSPvptG3F5vZ1G6FtTmhQoggw0OhXwx3BkWgBZuQU4khx-raTMJLmSUrInJeTJdSGmisUam28C-TokvVKdGNunSPJH1f3A-wSMBQKes1pjhO8a2-0y1Fxxb2meqPpCaKTHxl2GxrA7Z35MnecDy-5llzjnOtSzyK3aFbk_LcGLKLAbwastx4_qFxg5bXOuR-CDhzzZT_tucmgQ7MsUGPijtV4_dktg4MCqFhsr2pDmbV7C3xl6K_Q5GxGbjgnqygLpGbRkjmTDStCM3DtnMss4Ni9_X1oOCtmyqDby-aSvKG1V_erjtW8RQX0nBD-DD5KMucz1huP9lpVYI_F-N9lghJmBeh6TUgFSqgV85D_fk4x8mTljQhUqc0gOFHW6Otc3LigsixaQ7l70hrKpUV6YkHbnH-yAGYj77QYrq0PWfp5l7SfFziqraPjS4WeBoJyji2z2MkHm" />
            <input type="hidden" name="r" value="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"/>
        </form>
    </div>
</div>
<script>
    (function(){
        var trkjs = document.createElement('img');
        trkjs.setAttribute('src', '/cdn-cgi/images/trace/managed/js/transparent.gif?ray=73d172891fa462fd');
        trkjs.setAttribute('style', 'display: none');
        document.body.appendChild(trkjs);
        var cpo = document.createElement('script');
        cpo.src = '/cdn-cgi/challenge-platform/h/g/orchestrate/managed/v1?ray=73d172891fa462fd';
        window._cf_chl_opt.cOgUHash = location.hash === '' && location.href.indexOf('#') !== -1 ? '#' : location.hash;
        window._cf_chl_opt.cOgUQuery = location.search === '' && location.href.slice(0, -window._cf_chl_opt.cOgUHash.length).indexOf('?') !== -1 ? '?' : location.search;
        if (window.history && window.history.replaceState) {
            var ogU = location.pathname + window._cf_chl_opt.cOgUQuery + window._cf_chl_opt.cOgUHash;
            history.replaceState(null, null, "\/api\/v1\/notifications?__cf_chl_rt_tk=f4JGP6XJf9US8CTq2aw2HenxZBUf1Eb8t81JGcAxxBU-1660896989-0-gaNycGzNCSU" + window._cf_chl_opt.cOgUHash);
            cpo.onload = function() {
                history.replaceState(null, null, ogU);
            };
        }
        document.getElementsByTagName('head')[0].appendChild(cpo);
    }());
</script>

    <div class="footer" role="contentinfo">
        <div class="footer-inner">
            <div class="clearfix diagnostic-wrapper">
                <div class="ray-id">Ray ID: <code>73d172891fa462fd</code></div>
            </div>
            <div class="text-center">
                Performance &amp; security by
                <a rel="noopener noreferrer" href="https://www.cloudflare.com?utm_source=challenge&utm_campaign=m" target="_blank">Cloudflare</a>
            </div>
        </div>
    </div>
</body>
</html>

   at OneSignalApi.Api.DefaultApi.CreateNotificationWithHttpInfo(Notification notification, Int32 operationIndex)
   at OneSignalApi.Api.DefaultApi.CreateNotification(Notification notification, Int32 operationIndex)
   at Agrotek.Helpers.OneSignalHelper.SendNotificationGeneric(String targetRole, String message) in /home/nobat/dotnet/AgrotekAPI/Agrotek/Helpers/OneSignalHelper.cs:line 50

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Cant send notification allready exist externalID

What happened?

When i try to send notification to spesific user with externalID it returns theres no user with this id. but from another app i can send notification to same id.

Heres my code:

using OneSignalApi.Api;
using OneSignalApi.Client;
using OneSignalApi.Model;

var appConfig = new Configuration();
                                appConfig.BasePath = "https://onesignal.com/api/v1";
                                appConfig.AccessToken = "Y2U*****************NDkwNTY2";
                                var appInstance = new DefaultApi(appConfig);

                                // Create and send notification to all subscribed users
                                var notification = new Notification(appId: "83dd880a-********-f10d048d6578")
                                {
                                    Contents = new StringMap(en: "Test text."),
                                    IncludeExternalUserIds = new List<string> { "1ze5WrBgcuY****ornekOrF343Z2" }
                                };
                                var response = await appInstance.CreateNotificationAsync(notification);

Heres onesignal users page:
image

Steps to reproduce?

i tried to pass user value directly string
i added channel "push"

What did you expect to happen?

I expect to send notification to spesific external user id

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Cannot use Filter as field always throw null error

What happened?

I want to send notification base on user tags filter but it seems like i cannot initialize Filter() without it throws null error:

ArgumentNullException: Value cannot be null.
Parameter name: field is a required property for Filter and cannot be null
OneSignalApi.Model.Filter..ctor(string field, string key, string value, RelationEnum relation) in Filter.cs, line 116

Steps to reproduce?

public static async Task<string> testSendAsync()
        {
            appConfig.BasePath = "https://onesignal.com/api/v1";
            appConfig.AccessToken = Authorization;
            var appInstance = new DefaultApi(appConfig);

            var notification = new Notification(appId: AppId)
            {
                Contents = new StringMap(en: "Hello World from .NET!"),
                Headings = new StringMap(en: "Hello"),
                IncludedSegments = new List<string> { "Sale Role" },
                Filters = new List<Filter>
                {
                    new Filter(){ Field = "tag", Key = "Role", Value = "4", Relation = Filter.RelationEnum.Equal}
                },
            };

            var response = await appInstance.CreateNotificationAsync(notification);

            return $"Alert success: {response.Recipients.ToString()}";
        }

What did you expect to happen?

It should not be null when we provide value to "field" already

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Why Don't we have a default constructor

How can we help?

Hello,

In the .net sdk why don't we have a default constructor?

I had to use this...


            var notification = new Notification(null,null,null, null, null, null, null, null,

                null, null, null, null, null, null, null, null, null, null, null, null, null,
                null, null, null, null, null, null, null, null, null, null, null, null, null, null,
                null, _config["OneSignalAppID"]); 

var notification = new Notification() {AppId = "my app id"}; ///this doesn't work

It throws a null parameter exception


ArgumentNullException: Value cannot be null. (Parameter 'appId is a required property for Notification and cannot be null')
OneSignalApi.Model.Notification..ctor(List<string> includedSegments, List<string> excludedSegments, string lastSession, string firstSession, string sessionCount, string sessionTime, string amountSpent, string boughtSku, string tag, string language, string appVersion, string location, string email, string country, List<string> includePlayerIds, List<string> includeExternalUserIds, List<string> includeEmailTokens, List<string> includePhoneNumbers, List<string> includeIosTokens, List<string> includeWpWnsUris, List<string> includeAmazonRegIds, List<string> includeChromeRegIds, List<string> includeChromeWebRegIds, List<string> includeAndroidRegIds, string id, Nullable<bool> isIos, Nullable<bool> isAndroid, Nullable<bool> isHuawei, Nullable<bool> isAnyWeb, Nullable<bool> isChromeWeb, Nullable<bool> isFirefox, Nullable<bool> isSafari, Nullable<bool> isWPWNS, Nullable<bool> isAdm, Nullable<bool> isChrome, string channelForExternalUserIds, string appId, string externalId, StringMap contents, StringMap headings, StringMap subtitle, object data, string huaweiMsgType, string url, string webUrl, string appUrl, object iosAttachments, string templateId, Nullable<bool> contentAvailable, bool mutableContent, string targetContentIdentifier, string bigPicture, string huaweiBigPicture, string admBigPicture, string chromeBigPicture, string chromeWebImage, List<Button> buttons, List<Button> webButtons, string iosCategory, string androidChannelId, string huaweiChannelId, string existingAndroidChannelId, string huaweiExistingChannelId, NotificationAllOfAndroidBackgroundLayout androidBackgroundLayout, string smallIcon, string huaweiSmallIcon, string largeIcon, string huaweiLargeIcon, string admSmallIcon, string admLargeIcon, string chromeWebIcon, string chromeWebBadge, string firefoxIcon, string chromeIcon, string iosSound, string androidSound, string huaweiSound, string admSound, string wpWnsSound, string androidLedColor, string huaweiLedColor, string androidAccentColor, string huaweiAccentColor, Nullable<int> androidVisibility, Nullable<int> huaweiVisibility, string iosBadgeType, Nullable<int> iosBadgeCount, string collapseId, string webPushTopic, object apnsAlert, DateTime sendAfter, string delayedOption, string deliveryTimeOfDay, Nullable<int> ttl, Nullable<int> priority, string apnsPushTypeOverride, string throttleRatePerMinute, string androidGroup, string androidGroupMessage, string admGroup, object admGroupMessage, string threadId, string summaryArg, int summaryArgCount, string emailSubject, string emailBody, string emailFromName, string emailFromAddress, string smsFrom, List<string> smsMediaUrls)

I'm using the latest version 1.0.0

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Is there a way to add Launch URL to the push notification button?

How can we help?

Documentation says that we can create WebButtons with LaunchUrl (Url) as a parameter, but WebButtons attribute is a List, where Button doesn't have Url parameter. How can we add Url to the WebButtons?
If anything else is needed from my side, I'm happy to help.
Image below shows this issue in action:
image

Thank you.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Not receiving webpush notifications to android smartphone. How to solve this problem?

How can we help?

Hi there!

I would like to ask for help about this topic.
We've integrated the push notification service to our website and it worked perfectly until now.
The past few days we got some bug reports, that the web push notifications didn't received on android smartphones.

Previously, to solve this problem, I subscribed to push notifications via Google Chrome and enabled every notification in my android phone's settings.
Simultaneously, I subscribed to push notifications on my laptop (Linux, Google Chrome) too, and when our web application sends to one signal server a push notification request, then the notification message is arriving to my desktop but not receiving to my android smartphone.

Furthermore I posted a request via ,,postman" to https://onesignal.com/api/v1/notifications and still not receiving the push notification to my android smartphone.
Message id: "15616798-6f54-4fb4-94a5-bc3f5bfc20a8"

I sent a custom message on website for myself and i received successfully the push notification on my android smartphone.

Device: Linux x86_64
SubscriptionID: 2a4f3b15-f64e-49e4-bd13-c11123654d9c
OneSignalID: bb1841b9-86d5-3eef-82b5-ab2f9edf13ec

Device: Linux armv81
SubscriptionID: 70db25a8-8678-467e-bf28-822c5ab404a3
OneSignalID: bb1841b9-86d5-3eef-82b5-ab2f9edf13ec

Could you give some advice, how to solve this problem?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Intermittent upstream connect errors

How can we help?

I am getting intermittent upstream connect errors with CreateNotification. Initially I suspected that it was a potential throttling failure, but I cannot reproduce it even when making several simultaneous calls at a time.

The stack trace for the error is:

OneSignalApi.Client.ApiException: Error calling CreateNotification: upstream connect error or disconnect/reset before headers. reset reason: overflow
at OneSignalApi.Api.DefaultApi.CreateNotificationWithHttpInfo(Notification notification, Int32 operationIndex)

There is nothing extraordinary about my call to CreateNotification. I'm instantiating and setting up an instance of AppConfig, AppInstance, and Notifcation, and then making the call.

I didn't log this as a bug on the chance that it's an issue in how I'm making the call. Is there something I should be looking for or doing differently?

Thank you! :)

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: MissingMethodException: Method not found: 'Void RestSharp.RestRequest..ctor(RestSharp.Method)'.

What happened?

The latest version of the SDK causes the notification unable to create.

After I try to execute the OneSignal CreateNotification function from the latest SDK version, this error occurs

image

Below is my code on how to trigger the error
image

Steps to reproduce?

1. Execute the CreateNotificationSuccessResponse result = apiInstance.CreateNotification(notification);
2. Error occurs

What did you expect to happen?

Notification send out successfully

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Value cannot be null. (Parameter 'id is a required property for CreateNotificationSuccessResponse and cannot be null')

What happened?

Getting the following error when trying to send a push notification

Value cannot be null. (Parameter 'id is a required property for CreateNotificationSuccessResponse and cannot be null')

public async Task SendNotificationToUser(string userid,string message)
{
Notification notification =new Notification(appId: "3bcfdf8e-d1aa-4fc1-9823-87fb8c19faa4");
//notification.AppId="3bcfdf8e-d1aa-4fc1-9823-87fb8c19faa4";
notification.Id=Guid.NewGuid().ToString();
notification.Contents =new StringMap();
notification.Contents.En=message;
notification.IncludeExternalUserIds=new List();
notification.IncludeExternalUserIds.Add(userid);
var result= await _oneSignalApiService.SendNotification(notification);
return Ok(result);
}

Steps to reproduce?

Value cannot be null. (Parameter 'id is a required property for CreateNotificationSuccessResponse and cannot be null')

What did you expect to happen?

Value cannot be null. (Parameter 'id is a required property for CreateNotificationSuccessResponse and cannot be null')

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Seems like notification sent but its not delivered

What happened?

Hello,

In my .net core app im using onesignal sdk

When i try to send notification it says error below
image

my method:

public async Task<bool> SendNotification(string uid, string title, string message)
        {
            var appConfig = new Configuration();
            appConfig.BasePath = "https://onesignal.com/api/v1";
            appConfig.AccessToken = "**************";
            var appInstance = new DefaultApi(appConfig);
            var notification = new Notification(appId: "**************")
            {
                Headings = new StringMap(en: title),
                Contents = new StringMap(en: message),
                IncludeExternalUserIds = new List<string> { uid },
                IsAndroid = true,
                IsIos = true,
            };

           CreateNotificationSuccessResponse resp =  await appInstance.CreateNotificationAsync(notification);
            Console.WriteLine(resp.ToString());
            return true;


        }

on onesignal panel i see notification sent but in my phone theres no notification

Steps to reproduce?

1- created method
2- filled all required contents

What did you expect to happen?

Sending push

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: How do I send a notification via tags?

How can we help?

I want to send a notification targeting devices with a specific data tag.

For example:

image

public async Task SendNotificationToDataTags(string name, string heading, string message, Dictionary<string,string>data)
    {
        var notification = new Notification(
            appId: _appId, 
            name: name, 
            headings: new StringMap(en: heading),
            smallIcon: "@mipmap/appicon", 
            contents: new StringMap(en: message),
            //tag attribute here
        );
        var response = await _client.CreateNotificationAsync(notification);
    }

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: external id is not set

What happened?

We are using the latest SDK.
When I try to update a Player's external id, it deletes the player's external id but does not set a new one.

example:


           var oneSignalClient = new OneSignalCustomerClient();
            var player = oneSignalClient.GetPlayer(deviceID);
            player.ExternalUserId = "124";
            var results = oneSignalClient.UpdatePlayer(player);

Steps to reproduce?

run provided code snippet. (OneSignalCustomerClient is just a wrapper of the DefaultApi instance.)

What did you expect to happen?

Update the external id of the player.

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: IncludePlayerIds has been marked obsolete in v2.0

How can we help?

IncludePlayerIds has been marked obsolete with no direction on what to use instead. This is the only way we target our users. What is the alternative? We don't use the ExternalUserId property and we don't use segments.

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]:

@Duddde

What happened?

I'm trying to send notification with ExternalId.
I do not receive anything.
But when the external Id is null, i receive the notification on my device.

 public async Task SendNewMatchNotification(string userId)
  {
      //SendOneSignalNotification
      Configuration config = new Configuration();
      config.BasePath = _options.BasePath;
      // Configure Bearer token for authorization: app_key
      config.AccessToken = _options.AccessToken;
      
      var apiInstance = new DefaultApi(config);
      
      var notification = new Notification(appId: _options.AppId)
      {
          TemplateId = _options.NewMatchTemplateId,
          IncludedSegments = new List<string> { "Total Subscriptions" },
          ExternalId = userId
      };
      
      try
      {
          // Create notification
          CreateNotificationSuccessResponse result = await apiInstance.CreateNotificationAsync(notification);
          Debug.WriteLine(result);
      }
      catch (ApiException e)
      {
          Debug.Print("Exception when calling DefaultApi.CreateNotification: " + e.Message);
          Debug.Print("Status Code: " + e.ErrorCode);
          Debug.Print(e.StackTrace);
      }
  }

On my .Net MAUI APP i'm using OneSignal.Login(userId.ToString()); to register the connected user.

But in my subscriptions i have two with the same Id's (it's maybe the problem)

image

Any idea of what's the problem ?

Steps to reproduce?

### Steps to reproduce?


Back end API .Net 7
pckg OneSignalAPI v2.0.2

Client : MAUI .Net 7.0
pckg OneSignal.SDK.Net 5.0.2

What did you expect to happen?

What did you expect to happen?

I expect to receive notification when using externalId

Relevant log output

Output of the one signal api : 
class CreateNotificationSuccessResponse {
  Id: 4cead680-2811-4134-b570-4f4d1bd95acc
  Recipients: 0
  ExternalId: 91b0045a-ed5c-49df-b499-88d382721db4
  Errors: 
}

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Response returned from CreateNotificationAsync is always null with IncludeExternalUserIds

What happened?

Notification is sent to user. However, response returned is null. Triggering through postman with the same object returns response with an id.

var appConfig = new OneSignalApi.Client.Configuration
            {
                BasePath = _appSettings.OneSignalBasePath,
                AccessToken = _appSettings.OneSignalApiKey
            };
var oneSignalClient = new DefaultApi(appConfig);
var ids = new List<string> { "123" }
var options = new Notification(appId: _appSettings.OneSignalAppId)
            {                
                ChannelForExternalUserIds = "push",
                Url = notification.Url,
                Headings = new StringMap(en: "Heading"),
                Contents = new StringMap(en: "Contents"),
                IncludeExternalUserIds = ids,
                IsAnyWeb = true,
                WebButtons = new List<Button>
                {
                    new Button(id: "read-more-button")
                    {                        
                        Icon = "http://i.imgur.com/MIxJp1L.png",
                        Text = "View more"                        
                    }
                
            };
var response = await oneSignalClient.CreateNotificationAsync(options);

Steps to reproduce?

1. Install OneSignalApi v1.0.2
2. Call CreateNotificationAsync with notification object
3. Response is null

What did you expect to happen?

If the notification is sent successfully, the response should not be null and it should have an id like it does with postman

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Notifcation appId cannot be null when using in ASP.NET

What happened?

The latest stable version of the library returns the following error

System.ArgumentNullException: Value cannot be null. (Parameter 'appId is a required property for Notification and cannot be null')

Steps to reproduce?

1. Install Nuget Package "OneSignalApi" Version="2.0.0"
2. Create a service in the folder Services with the following


using OneSignalApi.Api;
using OneSignalApi.Client;
using OneSignalApi.Model;
using static System.Net.WebRequestMethods;

namespace AWC.Web.Services;

public class OneSignalService
{
    private readonly DefaultApi _client;
    private string _appId;
    public OneSignalService(string appId,string oneSignalApiKey)
    {
        _appId = appId;
        var appConfig = new Configuration
        {
            BasePath = "https://onesignal.com/api/v1",
            AccessToken = oneSignalApiKey
        };
        _client = new DefaultApi(appConfig);
    }

    public async Task SendNotification(string name, string message)
    {
        //create notification 
        var notification = new Notification
        {
            AppId = _appId,
            Name = name,
            Headings = new StringMap(en: "Heading"),
            SmallIcon = "@mipmap/appicon",
            Contents = new StringMap(en: message),
            IncludedSegments = new List<string> { "Subscribed Users" },
        };
        var response = await _client.CreateNotificationAsync(notification);
        Console.WriteLine(response);
    }
}

3. Register Service in Program.cs

var oneSignalAppId = builder.Configuration.GetSection("Secrets")["OneSignalAppId"];
var oneSignalApiKey = builder.Configuration.GetSection("Secrets")["OneSignalApIKey"];
builder.Services.AddSingleton(new OneSignalService(oneSignalAppId!,oneSignalApiKey!));

4. Use service in controller

public class MyController : ControllerBase
{
    private readonly OneSignalService _oneSignalService;

    public MyController(OneSignalService oneSignalService)
    {
        _oneSignalService = oneSignalService;
    }

    [HttpPost]
    public async Task<ActionResult> SendNotification([FromBody] string message)
    {
        await _oneSignalService.SendNotification("Heading", "message");

        return Ok();
    }
}


### What did you expect to happen?

I expected the notification to be sent correctly as appId is not null. 
I confirmed as much but don't want to post my secrets here

### Relevant log output

```Shell
System.ArgumentNullException: Value cannot be null. (Parameter 'appId is a required property for Notification and cannot be null')
         at OneSignalApi.Model.Notification..ctor(List`1 includedSegments, List`1 excludedSegments, List`1 includePlayerIds, List`1 includeExternalUserIds, List`1 includeEmailTokens, List`1 includePhoneNumbers, List`1 includeIosTokens, List`1 includeWpWnsUris, List`1 includeAmazonRegIds, List`1 includeChromeRegIds, List`1 includeChromeWebRegIds, List`1 includeAndroidRegIds, PlayerNotificationTargetIncludeAliases includeAliases, Nullable`1 targetChannel, String id, String name, Nullable`1 isIos, Nullable`1 isAndroid, Nullable`1 isHuawei, Nullable`1 isAnyWeb, Nullable`1 isChromeWeb, Nullable`1 isFirefox, Nullable`1 isSafari, Nullable`1 isWPWNS, Nullable`1 isAdm, Nullable`1 isChrome, String channelForExternalUserIds, String appId, String externalId, StringMap contents, StringMap headings, StringMap subtitle, Object data, String huaweiMsgType, String url, String webUrl, String appUrl, Object iosAttachments, String templateId, Nullable`1 contentAvailable, Boolean mutableContent, String targetContentIdentifier, String bigPicture, String huaweiBigPicture, String admBigPicture, String chromeBigPicture, String chromeWebImage, List`1 buttons, List`1 webButtons, String iosCategory, String androidChannelId, String huaweiChannelId, String existingAndroidChannelId, String huaweiExistingChannelId, BasicNotificationAllOfAndroidBackgroundLayout androidBackgroundLayout, String smallIcon, String huaweiSmallIcon, String largeIcon, String huaweiLargeIcon, String admSmallIcon, String admLargeIcon, String chromeWebIcon, String chromeWebBadge, String firefoxIcon, String chromeIcon, String iosSound, String androidSound, String huaweiSound, String admSound, String wpWnsSound, String androidLedColor, String huaweiLedColor, String androidAccentColor, String huaweiAccentColor, Nullable`1 androidVisibility, Nullable`1 huaweiVisibility, String iosBadgeType, Nullable`1 iosBadgeCount, String collapseId, String webPushTopic, Object apnsAlert, String delayedOption, String deliveryTimeOfDay, Nullable`1 ttl, Nullable`1 priority, String apnsPushTypeOverride, String throttleRatePerMinute, String androidGroup, String androidGroupMessage, String admGroup, Object admGroupMessage, String threadId, String summaryArg, Int32 summaryArgCount, String emailSubject, String emailBody, String emailFromName, String emailFromAddress, String smsFrom, List`1 smsMediaUrls, List`1 filters, Nullable`1 sendAfter)
         at AWC.Web.Services.OneSignalService.SendNotification(String name, String message) in D:\Programming\The AWC\The-AWC-App\backend\AWC.Web\Services\OneSignalService.cs:line 26
         at AWC.Web.Controllers.NewsPostsController.PostNewsPost(NewsPost newsPost) in D:\Programming\The AWC\The-AWC-App\backend\AWC.Web\Controllers\NewsPostsController.cs:line 97
         at lambda_method6(Closure, Object)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: How to set ios_interruption_level?

How can we help?

Hello
I can't seem to find where to set ios Focus levels in the API.

The field would be ios_interruption_level, which I want to set to TimeSenstive, but doesn't appear in the notification properties.

Is it somewhere else?

Code of Conduct

  • I agree to follow this project's Code of Conduct

[Bug]: Cannot add device with device_type = 0

What happened?

Cannot add device with device_type = 0

Steps to reproduce?

1. call CreatePlayerAsync with DeviceType = 0
2. Error return {\"errors\":[\"device_type is required\"]}

What did you expect to happen?

Be able to create device with device_type = 0

Relevant log output

No response

Code of Conduct

  • I agree to follow this project's Code of Conduct

[question]: Aliases, IncludeExternalUserIds as deprecated.

How can we help?

Previously I was using IncludeExternalUserIds to send notification to the certain external user/s, but from the newest version, this Datamember is marked as deprecated.

When I'm trying to use aliases I have some problems with it. I'm not sure how to create them (is it available on the FE side like it was for setting up of externalUserIds?)
image

Also in documentation there is a mention about visibility of aliases in OneSignal Dashboard but I can't find these.

My actual code looks like this:
image
and I don't know what should I pass to aliasLabel <- and where to create this if I want the same label for all users but send notifications by their externalId.

Code of Conduct

  • I agree to follow this project's Code of Conduct

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.