How to send iOS - APN Notification With P12 Certificate - C# Samples - c#

I am new to IOS APN - Notification generating service , Please help on How we can send APN from C# Windows Service - .Net Framework 4.5 / 4.7?
Tired with Moon-APN , Pushsharp , DotAPN but no result. If any one have sample code with step by step process please share .
Thanks in Advance :-)

#Sumesh you can use the .NET open source library PushSharp to push messages to Apple's APNS service.
step1: Download PushSharp open source project compilation https://github.com/Redth/PushSharp!
step2: After successful compilation, APNS push needs to use Newtonsoft.Json.dll, PushSharp.Apple.dll, PushSharp.Core.dll three assembly library files
step3: Then the ios client needs to provide the .p12 certificate file and the encryption password of the certificate file
step4: After preparing these, create a new console program to reference the above library file, copy the certificate to the root directory, change the attributes, and output to the copy directory as always copy
console program code as follow:
class Program
{
static ApnsConfiguration config;
static ApnsServiceBroker apnsBroker;
static void Main(string[] args)
{
config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, "certificate.p12", "certificate's password");
apnsBroker = new ApnsServiceBroker(config);
//post catch error
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
//handle failed APN msg
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine("Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}" + notification.DeviceToken);
}
else
{
//internal catch error
Console.WriteLine("Apple Notification Failed for some unknown reason : {ex.InnerException}" + notification.DeviceToken);
}
// flag handle
return true;
});
};
//successed
apnsBroker.OnNotificationSucceeded += (notification) =>
{
Console.WriteLine("Apple Notification Sent ! "+notification.DeviceToken);
};
//engined start
apnsBroker.Start();
}
/// <summary>
/// apn message
/// </summary>
public static void SendMsg()
{
List<string> MY_DEVICE_TOKENS = new List<string>() {
"1f6f37acad29348c6a5957529c9fa61ad69766ec9c7367948745899cbccdfd51",
"1f6f37acad29348c6a5957529c9fa61ad69766ec9c7367948745899cbccdfd51"
};
foreach (var deviceToken in MY_DEVICE_TOKENS)
{
// queue triger a notification message to iOS client
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken, // this one deviceToken from iOS client,it have to
Payload = JObject.Parse("{\"aps\":{\"sound\":\"default\",\"badge\":\"1\",\"alert\":\"This is a test of a mass advertising message push message\"}}")
});
}
//engined stop
apnsBroker.Stop();
Console.Read();
}
}
I hope I can help you

Related

Program crashes on StartScanningForDevicesAsync() PLUGIN.BLE

I am working on a Xamarin app based on TX/RX serial com, particularly with Xamarin.iOS. I am trying to connect an Arduino to my iOS app, with Plugin.BLE NuGet package. At the time I try to start scanning for devices, the app crashes without debugging logs. This is the command that holds the Task for known device:
public async Task Button_ConnectBT()
{
connected = false;
_handler = CrossBluetoothLE.Current;
_adapter = CrossBluetoothLE.Current.Adapter;
devicelist = new ObservableCollection<IDevice>();
bt_state = "Not Connected";
if (!_adapter.IsScanning)
{
devicelist.Clear();
_adapter.ScanTimeout = 10000;
_adapter.ScanMode = ScanMode.LowPower;
_adapter.DeviceDiscovered += (s, a) =>
{
devicelist.Add(a.Device);
};
if(!_handler.Adapter.IsScanning)
await _adapter.StartScanningForDevicesAsync(); //Breaks here
foreach (var device in devicelist)
{
if (device.Id.ToString() == "96af0bb8-cafa-5b07-a0d2-79c01a414e7ee")
{
...
}
bt_state = "Connected";
}
}
Does anybody know why StartScanningForDevicesASync() is not working? Are there any permissions required by the ios app? If permissions are the impediment, how can I figure them out?
Thank you in advance.
Regards,
Raúl.

Unable to create Hotspot connection using NEHotspotConfigurationManager

when I try to create a hotspot connection in my Xamarin.IOS project I get the following error returned in the description when using NEHotspotConfigurationManager :
Error Domain=NEHotspotConfigurationErrorDomain Code=8 \"internal error.\" UserInfo={NSLocalizedDescription=internal error.}
I have tried to connect to both the network in the office and my phone's wifi hotspot and both return the same message. I have enabled both the options "Accept WiFi Information" and "Hotspot" on both the App ID on the developer portal and also the same in the Entitlements.plist and still the same error. I'm using the code shown below.
public async void JoinNetwork()
{
NEHotspotConfiguration config = new NEHotspotConfiguration("CTIP");
config.JoinOnce = false;
var tcs = new TaskCompletionSource<NSError>();
NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(config, err => tcs.SetResult(err));
var error = await tcs.Task;
if (error != null)
{
PAGE.IOSErrorAlert(error.Description, this);
return;
}
}
Try you code as below
NEHotspotConfiguration config = new NEHotspotConfiguration("CTIP" ,passphrase , false);
config.JoinOnce = true;
var tcs = new TaskCompletionSource<NSError>();
NEHotspotConfigurationManager.SharedManager.ApplyConfiguration(config, err =>
tcs.SetResult(err));
and try to restart your device ,this seems like a known issue on apple side .
Refer to
https://stackoverflow.com/a/47769497/8187800
https://developer.apple.com/forums/thread/107851

tranfer file via bluetooth to iphone using 32feet

I am trying to transfer a file to my iphone using 32feet bluetooth, but cannot seem to get past the ObexWebResponse.
I have read many post on this but none of the solutions seem to work for me.
The Error i get is
// Connect failed
// The requested address is not valid in its context "address:Guid"
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public BTooth() {
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
ConnectAsync();
}
public void ConnectAsync() {
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard() {
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult) {
Console.WriteLine("Success");
Console.WriteLine($"Authenticated equals {_hlkBoardDevice.Authenticated}");
} else {
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e) { _inRangeBluetoothDevices.AddRange(e.Devices); }
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e) {
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i) {
if (_inRangeBluetoothDevices[i].DeviceName == "Uranus") {
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
TransferFile();
return;
}
}
// no devices found
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e) {
e.Confirm = true; // Never reach this line
}
// not working
// transfers a file to the phone
public void TransferFile() {
string file = "E:\\test.txt",
filename = System.IO.Path.GetFileName(file);
string deviceAddr = _hlkBoardDevice.DeviceAddress.ToString();
BluetoothAddress addr = BluetoothAddress.Parse(deviceAddr);
_bluetoothClient.Connect(BluetoothAddress.Parse(deviceAddr), BluetoothService.SerialPort);
Uri u = new Uri($"obex://{deviceAddr}/{file}");
ObexWebRequest owr = new ObexWebRequest(u);
owr.ReadFile(file);
// error:
// Connect failed
// The requested address is not valid in its context ...
var response = (ObexWebResponse)owr.GetResponse();
Console.WriteLine("Response Code: {0} (0x{0:X})", response.StatusCode);
response.Close();
}
The pairing and authentication works just fine, and I can get the BluetoothService.Handsfree to make a call for me but the transferring of the file fails. Not knowing what the actual error is, I tried almost every service available with no luck.
Can you help me figure out what is going on? This is my first attempt working with Bluetooth services so I still have a ton to learn.
Is it possible to transfer a file from iPhone to Windows desktop via Bluetooth?
However, in case you need to transfer media files (images, videos, etc) from Android device, you can use ObexListener class provided by 32Feet library for this purpose, and then you can simply call _obexListener.GetContext() method that will block and wait for incoming connections.
Once a new connection is received, you can save the received file to local storage, as shown in the below example:
ObexListener _listener = new ObexListener();
_listener.Start();
// This method will block and wait for incoming connections
ObexListenerContext _context = _listener.GetContext();
// Once new connection is received, you can save the file to local storage
_context.Request.WriteFile(#"c:\sample.jpg");
NOTE: When working with OBEX on Windows, make sure to disable the "Bluetooth OBEX Service" Windows service, in order not to let it handle the incoming OBEX requests instead of the desired application.
I walked away from this for a while. and started Trying to use xamiren but then had to create a virtual Mac so that I could have the apple store to just load software on my phone. From there xamerin 'should' work well but its another field and tons more to firgure out.

How to Push data from C# to ZeroMQ and Pull from Node.JS or vice-versa?

Scenario:
I am trying to send a data (say String type) from C# сonsole application to Node.JS server through ZeroMQ.
Information:
Using clrzmq for c# and ZeroMQ libs for C# and Node.JS respectively
I am able to perform push-pull from Node.JS, also push - pull from C#.
So, one thing is confirmed that ZeroMQ - The Intelligent Transport Layer is installed on the machine (Windows 7 64-bit)
Issue:
I am not able to push data from C# Console app to Node.JS app (even tried vice-versa), both are on the same machine and on the same address i.e tcp://127.0.0.1:2222
Node.js code:
var zmq = require('zeromq.node');
var pull_socket = zmq.socket('pull');
pull_socket.connect('tcp://127.0.0.1:2222');
pull_socket.on('message', function (data) {
console.log('received data:\n');
console.log(data);
});
C# code:
namespace DataServiceEngine
{
class Program
{
static void Main(string[] args)
{
//clsApp App = new clsApp();
//App.appId = "001";
//App.name = "Back Office";
//Console.WriteLine("appId :" + App.appId + "\n");
//Console.WriteLine("name:" + App.name + "\n");
try
{
// ZMQ Context and client socket
using (var context = new Context(1))
{
using (Socket client = context.Socket(SocketType.PUSH))
{
client.Connect("tcp://127.0.0.1:2222");
string request = "Hello";
for (int requestNum = 0; requestNum < 10; requestNum++)
{
Console.WriteLine("Sending request {0}...", requestNum);
client.Send(request, Encoding.Unicode);
string reply = client.Recv(Encoding.Unicode);
Console.WriteLine("Received reply {0}: {1}", requestNum, reply);
}
}
}
}
catch (ZMQ.Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}
Question: Can anyone tell me what may be the reason or where am I doing wrong?
I had the same issue (but I issued a communication Node.JS -> Node.JS). To solve the problem I used to do sendersocket.connect("tcp://"+host+":"+port); at the sender and receiversocket.bindSync("tcp://*:"+port); at the receiver.
Hope this fix your problem.

push notification iphone error (moon aspn)

I'm using the moon aspn library for sending push notifications in asp.net and c#. I'm encountering the following error: Call to SSPI Failed; in the inner exception i have: Unknown error while processing the certificate; error code: -2147467259.
here is my code:
private void SendQueueToapple(IEnumerable<NotificationPayload> queue)
{
int i = 1000;
foreach (var item in queue)
{
if (!_conected)
{
Connect(_host, NotificationPort, _certificates);
var response = new byte[6];
--> --> --> _apnsStream.BeginRead(response, 0, 6, ReadResponse, new MyAsyncInfo(response, _apnsStream));<-- <-- <--
} try {
if (item.DeviceToken.Length == 64) //check lenght of device token, if its shorter or longer stop generating Payload.
{
item.PayloadId = i;
byte[] payload = GeneratePayload(item);
_apnsStream.Write(payload);
Logger.Info("Notification successfully sent to APNS server for Device Toekn : " + item.DeviceToken);
Thread.Sleep(1000); //Wait to get the response from apple.
}
else
Logger.Error("Invalid device token length, possible simulator entry: " + item.DeviceToken);
}
catch (Exception ex)
{
Logger.Error("An error occurred on sending payload for device token {0} - {1}", item.DeviceToken, ex.Message);
_conected = false;
}
i++;
}
}
This might be a certificate related problem. You have to create .cer and .p12 files. Pay close attention to these files. You first generate the .cer and I'm not going into detail here. There's enough material available. The problem comes when generating the .p12 file.
In your mac, go to the Keychain Access. Select "My Certificates" from the left pane. There you will see a list of certificates. Select the certificate you generated for push notifications. Right click and export. Make sure you DO NOT expand the certificate perform this step on the private key. That's where thing starts to go wrong.

Categories

Resources