DependencyService.Get<ILogManager>().GetLog() System.NullReferenceException: 'Object reference not set to an instance of an object' - xamarin.forms

I am trying to execute Xamarin App.
I can build and deploy solutions on both Android and iOS devices. But when I am Debugging/running iOS App I am receiving an error
**System.NullReferenceException:** 'Object reference not set to an instance of an object'
on
private static ILogger logger = DependencyService.Get<ILogManager>().GetLog(); line
I have installed the latest version of the Nlog NuGet Package.
My ILogManager file is
namespace VolMobile.AppData.Interfaces
{
public interface ILogManager
{
ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath]string callerFilePath = "");
void Reload();
void DeleteLog();
}
}
How can I resolve this issue?
update
My NLogManager iOS file
using System;
using System.Collections.Generic;
using Xamarin.Forms;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
using VolMobile.AppData.Interfaces;
using VolMobile.iOS.Logging;
[assembly: Dependency(typeof(NLogManager))]
namespace VolMobile.iOS.Logging
{
public class NLogManager : ILogManager
{
string logFile;
LoggingConfiguration config;
public NLogManager()
{
Reload();
}
public void Reload()
{
config = new LoggingConfiguration();
var consoleTarget = new ConsoleTarget();
config.AddTarget("console", consoleTarget);
var consoleRule = new LoggingRule("*", LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(consoleRule);
//File logging level
LogLevel llSetting = LogLevel.Off;
IEnumerable<LogLevel> sysLevels = LogLevel.AllLevels;
//default to trace at startup
string currentLogLevel = "Trace";
//load the app state if available
if (App.AppState != null)
currentLogLevel = App.AppState.AppSettings.LogLevel;// AppData.AppData.LogLevel;
foreach (LogLevel ll in sysLevels)
{
if (currentLogLevel == ll.Name)
{
llSetting = ll;
}
}
var fileTarget = new FileTarget();
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); //android.os.environment is the other option
fileTarget.FileName = Path.Combine(folder, "Log.txt");
fileTarget.Layout = "${longdate}|${level:uppercase=true}|${callsite}|${appdomain}|${logger}|${threadid}|${message}|{exception:format=tostring}";
config.AddTarget("file", fileTarget);
logFile = Path.Combine(folder, "Log.txt");
var fileRule = new LoggingRule("*", llSetting, fileTarget);//LogLevel.Warn
config.LoggingRules.Add(fileRule);
LogManager.Configuration = config;
}
public void DeleteLog()
{
File.Delete(logFile);
}
// Services.Logging.ILogger
//AppData.Interfaces.ILogger
//public NLogLogger GetLog([System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "")
//{
// string fileName = callerFilePath;
// if (fileName.Contains("/"))
// {
// fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
// }
// var logger = LogManager.GetLogger(fileName);
// return new NLogLogger(logger, logFile);
//}
public AppData.Interfaces.ILogger GetLog([System.Runtime.CompilerServices.CallerFilePath] string callerFilePath = "")
{
string fileName = callerFilePath;
if (fileName.Contains("/"))
{
fileName = fileName.Substring(fileName.LastIndexOf("/", StringComparison.CurrentCultureIgnoreCase) + 1);
}
var logger = LogManager.GetLogger(fileName);
return new NLogLogger(logger, logFile);
}
}
}
The app is working perfectly fine on iOS, Andriod simulators, and Android Device only not on iOS devices.

Related

How do I use FirebaseAdmin with proxy?

Following code is working locally very fine.
The users receive All pushes (notifications) when I send them via local PC.
But I need use proxy on the server and this code fires the error: "Failed to establish a connection: Network is unreachable".
Plz help me setup the proxy for this code.
using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
namespace JMGlobal.Handlers
{
public class PushHandler : IRequestHandler<Request_Push, Response_Push>
{
public async Task<Response_Push> Handle(Request_Push request, CancellationToken cancellationToken)
{
try
{
var defaultApp = FirebaseApp.DefaultInstance;
if (defaultApp == null)
{
var keyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "jKey.json");
defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile(keyPath),
// HttpClientFactory --- ????
});
}
var message = new Message()
{
Token = request.FirebaseToken,
Apns = new ApnsConfig()
{
Aps = new FirebaseAdmin.Messaging.Aps()
{
Alert = new ApsAlert()
{
Title = "push",
Body = request.PushMessage
}
}
},
Notification = new Notification
{
Title = "System Notification",
Body = $"Message: {request.PushMessage}"
}
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = await messaging.SendAsync(message); // here fires the error: "Failed to establish a connection: Network is unreachable"
return new Response_Push()
{ .... };
}
catch (Exception ex)
{..... }
}
}
}
Working version below.
using System;
using MediatR;
using System.IO;
using FirebaseAdmin;
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Http;
using System.Net.Http;
using System.Net;
using Microsoft.Extensions.Options;
namespace JMGlobal.Handlers
{
public class ProxyHttpClientFactory2 : Google.Apis.Http.HttpClientFactory
{
private readonly string proxyAddress;
private readonly bool proxyUseProxy;
private readonly bool proxyBypassOnLocal;
public ProxyHttpClientFactory2(string proxyAddress, bool proxyUseProxy, bool proxyBypassOnLocal)
{
this.proxyAddress = proxyAddress;
this.proxyUseProxy = proxyUseProxy;
this.proxyBypassOnLocal = proxyBypassOnLocal;
}
protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
{
var proxy = new WebProxy(Address: proxyAddress, BypassOnLocal: proxyBypassOnLocal, BypassList: null, Credentials: null);
var webRequestHandler = new HttpClientHandler()
{
Proxy = proxy,
UseProxy = proxyUseProxy,
UseCookies = false
};
return webRequestHandler;
}
}
public class PushHandler : IRequestHandler<Request_PushFromBackend, Response_PushFromBackend>
{
private readonly IDBCommander _commander;
private readonly ILogger<PushHandler> _logger;
public PushFromBackendHandler(ILogger<PushHandler> logger, IDBCommander commander)
{
_logger = logger;
_commander = commander;
}
public async Task<Response_PushFromBackend> Handle(Request_PushFromBackend request, CancellationToken cancellationToken)
{
var sw = Stopwatch.StartNew();
bool isProxyUsing = false;
try
{
var resultFCMcreds = await _commander.Get_FCMcredentials(); // settings from DB
var resultProxy = await _commander.Get_ProxySettings(); // settings from DB
var defaultApp = FirebaseApp.DefaultInstance;
if (defaultApp == null)
{
var serviceAccountEmail = resultFCMcreds?.ServiceAccountEmail;
var PrivateKey = resultFCMcreds?.PrivateKey;
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
ProjectId = resultFCMcreds?.ProjectId,
HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal),
}.FromPrivateKey(PrivateKey));
defaultApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromServiceAccountCredential(credential),
HttpClientFactory = new ProxyHttpClientFactory2(resultProxy?.Address, (bool)resultProxy?.UseProxy, (bool)resultProxy?.BypassOnLocal)
});
}
FirebaseAdmin.Messaging.Aps aps_data = new Aps();
if (request.PushMode == 1)
{
aps_data.ContentAvailable = true;
}
var message = new Message()
{
//Topic = "news",
Token = request.FirebaseToken,
Apns = new ApnsConfig()
{
Aps = aps_data
},
Data = new Dictionary<string, string>()
{
["Changed"] = "true",
},
Notification = (request.PushMode == 1) ? null : new Notification
{
Title = $"System Notification {((request.PushMode == 1) ? " (SILENT)" : " (NORMAL)")}",
Body = $"Message: {request.PushMessage}"
}
};
var messaging = FirebaseMessaging.DefaultInstance;
var result = await messaging.SendAsync(message);
_logger.LogInformation($"result: {result}");
return new Response_PushFromBackend()
{
....
};
}
catch (Exception ex)
{
return new Response_PushFromBackend()
{
Error = ex.Message
};
}
}
}
}

receive message from android beam in xamarin forms

I'm develop cross-platform mobile application that use NFC. I already check the xamarin android beam sample here. Now i'm trying implement the same sample using xamarin forms so i'm using dependency service to call the function from android project.
I already create Ndef message and send function:
using System;
using System.Text;
using Android.App;
using MyApp.Droid;
using Android.Nfc;
using Xamarin.Forms;
[assembly: Dependency(typeof(PhoneBeam))]
namespace MyApp.Droid
{
public class PhoneBeam : Activity, NfcAdapter.ICreateNdefMessageCallback, NfcAdapter.IOnNdefPushCompleteCallback, iBeam
{
private NfcAdapter nfcAdapter;
public void Beam()
{
nfcAdapter = NfcAdapter.GetDefaultAdapter(MainActivity.Instance);
nfcAdapter.SetNdefPushMessageCallback(this, MainActivity.Instance);
nfcAdapter.SetOnNdefPushCompleteCallback(this, MainActivity.Instance);
}
public NdefMessage CreateNdefMessage(NfcEvent evt)
{
DateTime time = DateTime.Now;
var text = ("Beam me up!\n\n" + "Beam : " +
time.ToString("HH:mm:ss"));
NdefMessage msg = new NdefMessage(
new NdefRecord[]{ CreateMimeRecord (
"application/com.companyname.MyApp",
Encoding.UTF8.GetBytes (text)) });
return msg;
}
public NdefRecord CreateMimeRecord(String mimeType, byte[] payload)
{
byte[] mimeBytes = Encoding.UTF8.GetBytes(mimeType);
NdefRecord mimeRecord = new NdefRecord(
NdefRecord.TnfMimeMedia, mimeBytes, new byte[0], payload);
return mimeRecord;
}
public void OnNdefPushComplete(NfcEvent e){}
}
}
However, I really don't know how to receive a message. In android beam sample, they implement it in mainactivity. Here's sample:
protected override void OnResume ()
{
base.OnResume ();
if (NfcAdapter.ActionNdefDiscovered == Intent.Action) {
ProcessIntent (Intent);
}
}
void ProcessIntent (Intent intent)
{
IParcelable [] rawMsgs = intent.GetParcelableArrayExtra (
NfcAdapter.ExtraNdefMessages);
NdefMessage msg = (NdefMessage) rawMsgs [0];
mInfoText.Text = Encoding.UTF8.GetString (msg.GetRecords () [0].GetPayload ());
}
So i want to implement in class file so i can use dependencyService. Is there a way to implement this?
Edit: I did the send function:
public NdefMessage CreateNdefMessage (NfcEvent evt)
{
DateTime time = DateTime.Now;
var text = ("Beam me up!\n\n" +
"Beam Time: " + time.ToString ("HH:mm:ss"));
NdefMessage msg = new NdefMessage (
new NdefRecord[] { CreateMimeRecord (
"application/com.companyname.MyApp", Encoding.UTF8.GetBytes (text))
});
return msg;
}
But it return as "NEW TAG COLLECTED: application/com.companyname.MyApp". I want to resume MyApp and show the message. But it didn't.

Using RabbitMQ in ASP.net core IHostedService

I am facing a problem that would like help.
I am developing a background process that will be listening to a queue in rabbitmq server.
It is OK if I run it in a .net core console application. However I would like to do it in a more elegant way such as web service (which has given me a lot of trouble where it does not work when installed) or an IIS hosted web application.
I face a problem of Scoped Service when I try to host the service (IHostedService) in .net core web application.
The code below is working fine in a console application. How can make it run as an IHostedService in a .net core web application.
What am I supposed to change.
Your help is appreciated.
CODE:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using PaymentProcessor.Models;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Microsoft.EntityFrameworkCore;
namespace PaymentProcessor
{
public class PaymentProcessingService : HostedService
{
IConfiguration configuration;
private EntitiesContext claimsContext;
private string connectionString;
private string HostName = "";
private string UserName = "";
private string Password = "";
private static int MaxRetries;
private IConnectionFactory factory;
private IConnection connection;
private IModel channel;
public PaymentProcessingService(IConfiguration configuration)
{
this.configuration = configuration;
this.connectionString = configuration.GetConnectionString ("StagingContext");
claimsContext = new EntitiesContext(connectionString);
HostName = this.configuration.GetValue<string>("Settings:HostName");
UserName = this.configuration.GetValue<string>("Settings:UserName");
Password = this.configuration.GetValue<string>("Settings:Password");
MaxRetries = this.configuration.GetValue<string>("Settings:MaxRetries").ConvertTo<int>();
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
connect:
factory = new ConnectionFactory { HostName = HostName, UserName = UserName, Password = Password };
try
{
connection = factory.CreateConnection();
channel = connection.CreateModel();
channel.ExchangeDeclare("payment_rocessing_exchange", "topic");
channel.QueueDeclare("payment_processing_queue", true, false, false, null);
channel.QueueBind("payment_processing_queue", "payment_processing_exchange", "processing");
var queueArgs = new Dictionary<string, object>
{
{ "x-dead-letter-exchange", "payment_processing_exchange" },
{"x-dead-letter-routing-key", "processing_retry"},
{ "x-message-ttl", 10000 }
};
channel.ExchangeDeclare("payment_rocessing_exchange", "topic");
channel.QueueDeclare("payment_processing_retry_queue", true, false, false, queueArgs);
channel.QueueBind("payment_processing_retry_queue", "payment_processing_exchange", "processing_retry", null);
channel.ExchangeDeclare("payment_processing_exchange", "topic");
channel.QueueDeclare("payment_processing_error_queue", true, false, false, null);
channel.QueueBind("payment_processing_error_queue", "payment_processing_exchange", "processing_error", null);
channel.ExchangeDeclare("payment_processing_exchange", "topic");
channel.QueueDeclare("payment_integration_queue", true, false, false, null);
channel.QueueBind("payment_integration_queue", "payment_processing_exchange", "integration", null);
channel.BasicQos(0, 1, false);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var message = ea.Body.DeSerializeText();
try
{
var saveBundle = JObject.Parse(message);
var msg = (dynamic)((dynamic)saveBundle).Message;
string referenceNo = (string)msg.ReferenceNo;
var parameters = new[]
{
new SqlParameter
{
DbType = DbType.String,
ParameterName = "ReferenceNo",
Value =referenceNo
}
};
var result = claimsContext.Database.ExecuteSqlCommand("dbo.PaymentReferencesProcessSingle #ReferenceNo", parameters);
IBasicProperties props = channel.CreateBasicProperties();
props.Persistent = true;
props.ContentType = "text/plain";
props.DeliveryMode = 2;
channel.BasicPublish("payment_processing_exchange", "integration", props, (new MessageEnvelope { RetryCounts = 0, Message = JObject.FromObject(new { ReferenceNo = referenceNo }) }).Serialize());
}
catch (Exception ex)
{
MessageEnvelope envelope = JsonConvert.DeserializeObject<MessageEnvelope>(message);
if (envelope.RetryCounts < MaxRetries)
{
int RetryCounts = envelope.RetryCounts + 1;
MessageEnvelope messageEnvelope = new MessageEnvelope { RetryCounts = RetryCounts, Message = envelope.Message };
var data = messageEnvelope.Serialize();
channel.BasicPublish("payment_processing_exchange", "processing_retry", null, data);
}
else
{
var data = envelope.Serialize();
channel.BasicPublish("payment_processing_exchange", "processing_error", null, data);
}
}
finally
{
channel.BasicAck(ea.DeliveryTag, false);
}
};
channel.BasicConsume(queue: "payment_processing_queue", autoAck: false, consumer: consumer);
}
catch (Exception ex)
{
Thread.Sleep(10000);
goto connect;
}
}
}
}
and then
services.AddScoped<IHostedService, PaymentProcessingService>();
As Dekim mentioned a service should be registered.
Please have a look on an example I created on GitHub.
Program.cs looks like this:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
namespace Core
{
internal class Program
{
static async Task Main(string[] args)
{
await new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<ServiceRabbitMQ>(); // register our service here
})
.RunConsoleAsync();
}
}
}
Because the IHostedService requires the creation of a special scope according to the documentation.
From the Microsoft documentation cited in the above answer :
No scope is created for a hosted service by default.
Consider using : services.AddHostedService<MyHostedService>();

Add bluetooth-lowenergy services and writable characteristics to smartephone Xamarin

I am developing a mobile application that use bluetooth-lowenergy, i need to create services and characteristics in the application
Thanks
this after two days of search, and by reading this page BLE Android i solved my problem
here the class used to create services
using System;
using Android.App;
using Android.Bluetooth;
using Android.Bluetooth.LE;
using Android.OS;
using Java.Util;
using SitBle.Droid;
using SitBle.Interfaces;
using Exception = System.Exception;
[assembly: Xamarin.Forms.Dependency(typeof(Advertiser))]
namespace SitBle.Droid
{
public class Advertiser : IAdvertiser
{
private BluetoothAdvertiseCallback _advertiseCallback;
private readonly UUID _serviceUuid = UUID.FromString("795090c7-420d-4048-a24e-18e60180e23c");
private readonly UUID _characteristicCounterUuid = UUID.FromString("31517c58-66bf-470c-b662-e352a6c80cba");
private readonly UUID _characteristicInteractorUuid = UUID.FromString("0b89d2d4-0ea6-4141-86bb-0c5fb91ab14a");
private readonly UUID _descriptorConfigUuid = UUID.FromString("00002902-0000-1000-8000-00805f9b34fb");
public void Advertise()
{
try
{
_advertiseCallback = new BluetoothAdvertiseCallback();
var androidBluetoothGattServerCallback = new AndroidBluetoothGattServerCallback();
var adapter = BluetoothAdapter.DefaultAdapter;
var advertiseSettingBuilder = new AdvertiseSettings.Builder()
.SetAdvertiseMode(AdvertiseMode.Balanced).SetConnectable(true).SetTimeout(0)
.SetTxPowerLevel(AdvertiseTx.PowerMedium);
var advertiseSetting = advertiseSettingBuilder.Build();
var adverisingDataBuilder = new AdvertiseData.Builder().SetIncludeDeviceName(false).AddServiceUuid(new ParcelUuid(_serviceUuid));
adapter.BluetoothLeAdvertiser.StartAdvertising(advertiseSetting, adverisingDataBuilder.Build(), _advertiseCallback);
var appContext = Application.Context;
var mBluetoothManager = (BluetoothManager)appContext.GetSystemService("bluetooth");
var mGattServer = mBluetoothManager.OpenGattServer(appContext, androidBluetoothGattServerCallback);
mGattServer.AddService(CreateService());
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private BluetoothGattService CreateService()
{
BluetoothGattService service = new BluetoothGattService(_serviceUuid, GattServiceType.Primary);
// Counter characteristic (read-only, supports subscriptions)
BluetoothGattCharacteristic counter = new BluetoothGattCharacteristic(_characteristicCounterUuid,GattProperty.Read|GattProperty.Notify,GattPermission.Read);
BluetoothGattDescriptor counterConfig = new BluetoothGattDescriptor(_descriptorConfigUuid, GattDescriptorPermission.Read|GattDescriptorPermission.Write);
counter.AddDescriptor(counterConfig);
// Interactor characteristic
BluetoothGattCharacteristic interactor = new BluetoothGattCharacteristic(_characteristicInteractorUuid, GattProperty.Read|GattProperty.Write|GattProperty.Notify, GattPermission.Write);
service.AddCharacteristic(counter);
service.AddCharacteristic(interactor);
return service;
}
}
public class BluetoothAdvertiseCallback : AdvertiseCallback
{
public BluetoothAdvertiseCallback()
{
}
public override void OnStartSuccess(AdvertiseSettings settingsInEffect)
{
Console.WriteLine("Success");
}
public override void OnStartFailure(AdvertiseFailure errorCode)
{
Console.WriteLine("Fail");
}
}
public class AndroidBluetoothGattServerCallback : BluetoothGattServerCallback
{
public AndroidBluetoothGattServerCallback()
{
}
}
}

BackgroundTaskRegistration trigger property is null

Hi want to receive push notifications on background task for that i have created Portable library here is my Background task class
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.ApplicationModel.Background;
using Windows.Data.Xml.Dom;
using Windows.Networking.PushNotifications;
using Windows.Storage;
using Windows.UI.Notifications;
namespace BackgroundTask
{
public sealed class NotificationTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Get the background task details
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
string taskName = taskInstance.Task.Name;
Debug.WriteLine("Background " + taskName + " starting...");
// Store the content received from the notification so it can be retrieved from the UI.
ToastNotification notification = (ToastNotification )taskInstance.TriggerDetails;
settings.Values[taskName] = notification.Content;
NotificationTask.AddTostNotification(notification.Content);
Debug.WriteLine("Background " + taskName + " completed!");
}
private static void AddTostNotification(String xmlDocument)
{
List<string> messageSection = NotificationTask.GetMessageAndLandingPage(xmlDocument, "toast");
if (messageSection == null) { return; }
ToastTemplateType toastTemplate = ToastTemplateType.ToastText01;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(messageSection[0]));
// toastTextElements[1].AppendChild(toastXml.CreateTextNode(message));
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("launch", messageSection[1]);
XmlElement audio = toastXml.CreateElement("audio");
audio.SetAttribute("src", "ms-appx:///Assets/Play-Guitar.wav");
//audio.SetAttribute("loop", "true");
toastNode.AppendChild(audio);
//launch tost immediatly
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
Here i am registering Task
internal async void InitChannel()
{
// Applications must have lock screen privileges in order to receive raw notifications
BackgroundAccessStatus backgroundStatus = await BackgroundExecutionManager.RequestAccessAsync();
// Make sure the user allowed privileges
if (backgroundStatus != BackgroundAccessStatus.Denied && backgroundStatus != BackgroundAccessStatus.Unspecified)
{
Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
try
{
var channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
if (channel != null)
{
roamingSettings.Values["ExistingPushChannel"] = channel.Uri;
dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
channel.PushNotificationReceived += OnPushNotificationReceived;
UnregisterBackgroundTask();
RegisterBackgroundTask();
}
else
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
catch
{
roamingSettings.Values["ExistingPushChannel"] = "Failed to create channel";
}
}
}
private void RegisterBackgroundTask()
{
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
PushNotificationTrigger trigger = new PushNotificationTrigger();
taskBuilder.SetTrigger(trigger);
// Background tasks must live in separate DLL, and be included in the package manifest
// Also, make sure that your main application project includes a reference to this DLL
taskBuilder.TaskEntryPoint = "BackgroundTask.NotificationTask";
taskBuilder.Name = "PlaypushNotification";
try
{
BackgroundTaskRegistration task = taskBuilder.Register();
task.Completed += BackgroundTaskCompleted;
}
catch
{
UnregisterBackgroundTask();
}
}
private bool UnregisterBackgroundTask()
{
foreach (var iter in BackgroundTaskRegistration.AllTasks)
{
IBackgroundTaskRegistration task = iter.Value;
if (task.Name == "PlaypushNotification")
{
task.Unregister(true);
return true;
}
}
return false;
}
In my Manifest file
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundTask.NotificationTask">
<BackgroundTasks>
<Task Type="pushNotification" />
</BackgroundTasks>
</Extension>
</Extensions>
PushNotification Trigger is not firing, when i debug i found that trigger property of BackgroundTaskRegistration is null. what is the issue? What wrong is going here?

Resources