Send Voip Push On development but not on production - c#

i Am Using JsSoft.Apple.Apns.Notification . When i do sandbox= true. it works fine but when i change into false Notification is not received. also i No error will be arise. Please Tell Me what i missed or Doing wrong?
Apple .p12 Certificate is Created for Production.
here is the Code. or (https://github.com/Redth/APNS-Sharp).
using System;
using System.Collections.Generic;
using System.Text;
using JdSoft.Apple.Apns.Notifications;
namespace JdSoft.Apple.Apns.Test
{
class Program
{
[STAThread]
static void Main(string[] args)
{
//Variables you may need to edit:
//---------------------------------
//True if you are using sandbox certificate, or false if using production
bool sandbox = false;
//Put your device token in here
string testDeviceToken = "7e6baf66c0a908f65e15b9575dd04c291021b7b77079624223b39cd053d38c26";
//Put your PKCS12 .p12 or .pfx filename here.
// Assumes it is in the same directory as your app
string p12File = #"C:\Users\Nouman\source\repos\AsteriskComunicationApi\AsteriskComunicationApi\p12File\VOIP_iOS_New.p12";
//This is the password that you protected your p12File
// If you did not use a password, set it as null or an empty string
string p12FilePassword = "12345678";
//Number of notifications to send
int count = 3;
//Number of milliseconds to wait in between sending notifications in the loop
// This is just to demonstrate that the APNS connection stays alive between messages
int sleepBetweenNotifications = 3000;
//Actual Code starts below:
//--------------------------------
string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);
NotificationService service = new NotificationService(sandbox, p12Filename, p12FilePassword, 1);
service.SendRetries = 5; //5 retries before generating notificationfailed event
service.ReconnectDelay = 5000; //5 seconds
service.Error += new NotificationService.OnError(service_Error);
service.NotificationTooLong += new NotificationService.OnNotificationTooLong(service_NotificationTooLong);
service.BadDeviceToken += new NotificationService.OnBadDeviceToken(service_BadDeviceToken);
service.NotificationFailed += new NotificationService.OnNotificationFailed(service_NotificationFailed);
service.NotificationSuccess += new NotificationService.OnNotificationSuccess(service_NotificationSuccess);
service.Connecting += new NotificationService.OnConnecting(service_Connecting);
service.Connected += new NotificationService.OnConnected(service_Connected);
service.Disconnected += new NotificationService.OnDisconnected(service_Disconnected);
//The notifications will be sent like this:
// Testing: 1...
// Testing: 2...
// Testing: 3...
// etc...
for (int i = 1; i <= count; i++)
{
//Create a new notification to send
Notification alertNotification = new Notification(testDeviceToken);
alertNotification.Payload.Alert.Body = string.Format("Testing {0}...", i);
alertNotification.Payload.Sound = "default";
alertNotification.Payload.Badge = i;
//Queue the notification to be sent
if (service.QueueNotification(alertNotification))
Console.WriteLine("Notification Queued!");
else
Console.WriteLine("Notification Failed to be Queued!");
//Sleep in between each message
if (i < count)
{
Console.WriteLine("Sleeping " + sleepBetweenNotifications + " milliseconds before next Notification...");
System.Threading.Thread.Sleep(sleepBetweenNotifications);
}
}
Console.WriteLine("Cleaning Up...");
//First, close the service.
//This ensures any queued notifications get sent befor the connections are closed
service.Close();
//Clean up
service.Dispose();
Console.WriteLine("Done!");
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}

Related

Mifare Desfire / Mifare plus can't read with ACS ACR1252

Hi i'm newbie in RFID reading. So firstly i downloaded pcsc sharp repository from github. Then i tried to read binary from common rfid tag, it works perfect but the next step was to read data from as i think emulated rfid tag. RFID tag controller is pn71501. From this tag using pcsc sharp i can't read any data excluding ATR and uid. I tried to read this tag using my iPhone and it read it. So what i'm doing wrong?
I also tried to use already done software but it couldn't read it also.
Here is what i get using NFC Tools:
PS Smart Card reader i used is ACS ACR1252
Here is my code:
using System;
using System.Text;
using System.Collections.Generic;
using PCSC;
using PCSC.Iso7816;
namespace Transmit {
public class Program {
public static void Main() {
using (var context = ContextFactory.Instance.Establish(SCardScope.System)) {
var readerNames = context.GetReaders();
if (NoReaderFound(readerNames)) {
Console.WriteLine("You need at least one reader in order to run this example.");
Console.ReadKey();
return;
}
var readerName = ChooseRfidReader(readerNames);
if (readerName == null) {
return;
}
String response = "";
using (var rfidReader = context.ConnectReader(readerName, SCardShareMode.Shared, SCardProtocol.Any)) {
// for (byte i = 0x00; i < 0x47; i++) {
var apdu = new CommandApdu(IsoCase.Case3Extended, rfidReader.Protocol) {
CLA = 0xFF,
Instruction = (InstructionCode)0xB0,
P1 = 0x00,
P2 = 0x00,
Le = 0x10
};
using (rfidReader.Transaction(SCardReaderDisposition.Leave)) {
//Console.WriteLine("Retrieving the UID .... ");
var sendPci = SCardPCI.GetPci(rfidReader.Protocol);
var receivePci = new SCardPCI(); // IO returned protocol control information.
var receiveBuffer = new byte[256];
var command = apdu.ToArray();
var bytesReceived = rfidReader.Transmit(
sendPci, // Protocol Control Information (T0, T1 or Raw)
command, // command APDU
command.Length,
receivePci, // returning Protocol Control Information
receiveBuffer,
receiveBuffer.Length); // data buffer
var responseApdu =
new ResponseApdu(receiveBuffer, bytesReceived, IsoCase.Case3Extended, rfidReader.Protocol);
Console.WriteLine(String.Format("SW1: {0:X2} SW2: {1:X2}", responseApdu.SW1, responseApdu.SW2));
//if(responseApdu.DataSize > 0) {
//response += BitConverter.ToString(responseApdu.GetData()).Replace('-', ' ');
response += responseApdu.DataSize;
// }
}
// }
}
/*String[] devidedResponse = response.Split(' ');
String stillResponse = "";
bool notStarted = true;
int skipBytes = 7;
int onByte = 0;
for(int i = 0; i < devidedResponse.Length; i++) {
if (devidedResponse[i] != "D1" && notStarted) {
continue;
} else if (onByte < skipBytes) {
notStarted = false;
onByte += 1;
continue;
} else if (devidedResponse[i] == "FE") {
break;
}
stillResponse += devidedResponse[i] + " ";
}
String res = stillResponse.Trim();
string asciiCharString = "";
var splitResult = res.Split(' ');
foreach (string hexChar in splitResult) {
var byteChar = int.Parse(hexChar, System.Globalization.NumberStyles.HexNumber);
asciiCharString += (char)byteChar;
}*/
Console.WriteLine(response);
}
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
private static string ChooseRfidReader(IList<string> readerNames) {
// Show available readers.
Console.WriteLine("Available readers: ");
for (var i = 0; i < readerNames.Count; i++) {
Console.WriteLine($"[{i}] {readerNames[i]}");
}
// Ask the user which one to choose.
Console.Write("Which reader is an RFID reader? ");
var line = Console.ReadLine();
if (int.TryParse(line, out var choice) && choice >= 0 && (choice <= readerNames.Count)) {
return readerNames[choice];
}
Console.WriteLine("An invalid number has been entered.");
Console.ReadKey();
return null;
}
private static bool NoReaderFound(ICollection<string> readerNames) =>
readerNames == null || readerNames.Count < 1;
}
}
I know. I looked it up earlier. Can you read the card with the file explorer?
A hardware device like a UART can be read at three different levels
Read/Write UART directly by finding hardware I/O address
Read/Write through driver. In c# Use Open Serial Port. The driver gets the hardware I/O
Read/Write through an application. The application does 1 and/or 2 above.
You have a working application (number 3) and I do not know if it is using method 1 or 2.
With the card reader I'm trying to make your programming as simple as possible. The easiest method is 3 if you have an API. Next easiest is method 2 which you should be able to use if you installed the vendor driver. You should see device in device manager.
To unlock the card (encryption) you also need to install the certificate than came with card. The file explorer should be able to read/write card.

Consume EventArgs from CouchDB

i am struggling with consuming the data i get from my CouchDB database.
I am trying to consume new data that comes to the specific view.
CouchDB offers an option for feed=continous, but i tested it and dont get any data, same in postman.
But if i change it to feed=eventsource i can see the changes in the console. But i dont know how to handle the events.
I opened a method with the right connection, but im stuck now, any help would be great.
public async Task ObserveDbAndTrigger()
{
var url = "http://localhost:5984/MyDB/_changes?feed=eventsource&filter=_view&view=MyView&include_docs=true&attachments=true&heartbeat=1000&since=0";
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"user:password" + $"")));
var request = new HttpRequestMessage(HttpMethod.Get, url);
// handle the incoming events and work with the incoming data
}
}
Any suggestions ?
Clearly there's work to be done. Normally I shy away from answering such questions as posed because it seems like a code service request, but I believe this answer may benefit others beyond the OP.
Here is an extremely naïve bit of code meant to illustrate event delegation and the simplicity of communicating with CouchDB over TCP.
Ultimately this demonstrates the publish/subscribe pattern, which is a reasonable fit. I tested this against CouchDB 2.3 on Windows. The code is hardwired to localhost:5984 because whatever.
class NaiveChangeWatcher
{
static void Main(string[] args)
{
if (args.Length >= 4)
{
// set up server info.
string db = args[0];
string auth = "Basic " + Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(String.Join(":", args[1], args[2])));
string query = db + "/_changes?feed=continuous&since=0&heartbeat=" + args[3];
// init the publisher
ChangesPublisher pub = new ChangesPublisher();
// let's subscribe to the OnChange event which writes event data to the console.
pub.OnChange += (sender, e) => Console.WriteLine(e.Value);
pub.OnException += (sender, e) => Console.WriteLine(e.Value.ToString() + "\r\n\r\nPress a key to exit.");
//// start publishing.
Task.Run(async () =>
{
await pub.Begin("localhost", 5984, query, auth, int.Parse(args[3]));
});
// Press a key when bored of it all
Console.ReadKey();
// stop the publisher gracefully
pub.Stop = true;
}
else
{
Console.WriteLine("usage: NaiveChangeWatcher db_name username password timeout_millis");
}
}
//
// The ChangesPublisher notifies subscribers of new data from the changes feed
// via the ChangeEvent. The publisher will trigger an OnException event in the
// event of an exception prior to ending its task.
//
public class ChangesPublisher
{
// Set to true to stop publishing. This causes the Begin method to complete.
public bool Stop { get; set; }
// The event posted when data from the server arrived
public class ChangeEvent : EventArgs
{
public string Value { get; set; }
public ChangeEvent(string value)
{
Value = value;
}
}
// Event triggered when the subscriber croaks by exception
public class ExceptionEvent : EventArgs
{
public Exception Value { get; set; }
public ExceptionEvent(Exception value)
{
Value = value;
}
}
// Subscription to changes from the _changes endpoint
public event EventHandler<ChangeEvent> OnChange = delegate { };
// Subscription to publisher exit on error
public event EventHandler<ExceptionEvent> OnException = delegate { };
public async Task Begin(string serverAddr, int port, string query, string auth, int timeout)
{
using (var client = new TcpClient())
{
string request = String.Join("\r\n", new List<string> {
String.Format("GET /{0} HTTP/1.1",query),
"Authorization: " + auth,
"Accept: application/json",
"Host: " + serverAddr,
"Connection: keep-alive",
"\r\n"
});
try
{
await client.ConnectAsync(serverAddr, port);
using (NetworkStream stream = client.GetStream())
{
StreamWriter writer = new StreamWriter(stream);
await writer.WriteAsync(request);
await writer.FlushAsync();
// read lines from the server, ad nauseum.
StreamReader reader = new StreamReader(stream);
while (!Stop)
{
string data = await reader.ReadLineAsync();
// emit a change event
OnChange(this, new ChangeEvent(data));
}
}
}
catch (Exception e)
{
OnException(this, new ExceptionEvent(e));
}
}
}
}
}

Windows Phone Push Notification By Azure Notification Hub

I am android app developer .Now, I am developing app for windows phone . I am integrating push notification in windows phone first time by Azure notification Hub. I want help for notification Hub. How to integrate? How to send notification to selected device not to all?
I was integrated notification but after some time notification is stop. I have done with many notification hub credentials. Now notification is coming.
private async void Application_Launching(object sender, LaunchingEventArgs e)
{
StorageFile MyDBFile = null;
try
{
// Read the db file from DB path
MyDBFile = await StorageFile.GetFileFromPathAsync(DB_PATH);
}
catch (FileNotFoundException)
{
if (MyDBFile == null)
{
// Copy file from installation folder to local folder.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(DbConst.DATABASE, UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile(DB_PATH))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
}
var channel = HttpNotificationChannel.Find("MyPushChannel");
if (channel == null)
{
channel = new HttpNotificationChannel("MyPushChannel");
channel.Open();
channel.BindToShellToast();
}
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(async (o, args) =>
{
//var hub = new NotificationHub("<hub name>", "<connection string>");
var hub = new NotificationHub("mnokhgjhjhjbohkjkl", "Endpoint=sb://connect-hub.servicebus.windows.net/;SharedAccessKeyName=DefaultListenSharedAccessSignature;SharedAccessKey=RM6jjnbjnbjAnjhttD4yxqnknknklmkmnkkmkkkmmkbnl5rSk=");
Registration x= await hub.RegisterNativeAsync(args.ChannelUri.ToString());
//mChennelURI = x.ChannelUri;
Debug.WriteLine("Chennel URI: " + x.ChannelUri);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
System.Diagnostics.Debug.WriteLine(args.ChannelUri.ToString());
});
});
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(async (o,args) =>
{
// Error handling logic for your particular application would be here.
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}", args.ErrorType, args.Message, args.ErrorCode,args.ErrorAdditionalData));
});
});
// Handle the event that is raised when a toast is received.
channel.ShellToastNotificationReceived +=new EventHandler<NotificationEventArgs>((o, args) =>
{
string message = "";
foreach (string key in args.Collection.Keys)
{
message += args.Collection[key] + ": ";
}
//string[] separators = { "#"};
// string[] words = message.Split(separators, StringSplitOptions.RemoveEmptyEntries);
// string type = words[0];
// string title = words[1];
// string body = words[2];
// string attach = words[3];
//string date = words[4];
//string time = words[5];
//string msdId = words[6];
//string groupIDS = words[7];
//foreach (var word in words)
//Console.WriteLine(word);
Console.WriteLine("Push notification : " + message);
Debug.WriteLine("Push notification : " + message);
Debugger.Log(1, "Push", "Push notification : " + message);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
// Show the notification since toasts aren't
// displayed when the app is currently running.
MessageBox.Show(message);
//<Temp>
// DatabaseHelperClass dbHelper = new DatabaseHelperClass();
// dbHelper.Insert(new Msg(msdId, groupIDS, type, title, body, attach, date, time, Constants.NO));
//</Temp>
});
});
}

RabbitMQ C# verify message was sent

I'm new to RabbitMQ and trying to write to a Queue and verify the message was sent. If it fails I need to know about it.
I made a fake queue to watch it fail but no matter what I see no execptions and when I am looking for a ack I always get one. I never see the BasicNack.
I'm not even sure i'm the BasicAcks is the way to go.
private void button1_Click(object sender, EventArgs e)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("task_queue", true, false, false, null);
var message = ("Helllo world");
var body = Encoding.UTF8.GetBytes(message);
channel.ConfirmSelect();
var properties = channel.CreateBasicProperties();
properties.SetPersistent(true);
properties.DeliveryMode = 2;
channel.BasicAcks += channel_BasicAcks;
channel.BasicNacks += channel_BasicNacks;
//fake queue should be task_queue
channel.BasicPublish("", "task_2queue", true, properties, body);
channel.WaitForConfirmsOrDie();
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
void channel_BasicNacks(IModel model, BasicNackEventArgs args)
{
}
void channel_BasicAcks(IModel model, BasicAckEventArgs args)
{
}
For those looking for a C# answer - here is what you need.
https://rianjs.net/2013/12/publisher-confirms-with-rabbitmq-and-c-sharp
Something like this: (BasicAcks attaches an event handler - there is also BasicNacks)
using (var connection = FACTORY.CreateConnection())
{
var channel = connection.CreateModel();
channel.ExchangeDeclare(QUEUE_NAME, ExchangeType.Fanout, true);
channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
channel.QueueBind(QUEUE_NAME, QUEUE_NAME, String.Empty, new Dictionary<string, object>());
channel.BasicAcks += (sender, eventArgs) =>
{
//implement ack handle
};
channel.ConfirmSelect();
for (var i = 1; i <= numberOfMessages; i++)
{
var messageProperties = channel.CreateBasicProperties();
messageProperties.SetPersistent(true);
var message = String.Format("{0}\thello world", i);
var payload = Encoding.Unicode.GetBytes(message);
Console.WriteLine("Sending message: " + message);
channel.BasicPublish(QUEUE_NAME, QUEUE_NAME, messageProperties, payload);
channel.WaitForConfirmsOrDie();
}
}
You need a Publisher Confirms
as you can read you can implement:
The transaction:
ch.txSelect(); <-- start transaction
ch.basicPublish("", QUEUE_NAME,
MessageProperties.PERSISTENT_BASIC,
"nop".getBytes());
ch.txCommit();<--commit transaction
The message is stored to the queue and to the disk.
This way can be slow, if you need performance you shouldn't use it.
You can use the Streaming Lightweight Publisher Confirms, using:
ch.setConfirmListener(new ConfirmListener() {
public void handleAck(long seqNo, boolean multiple) {
if (multiple) {
unconfirmedSet.headSet(seqNo+1).clear();
} else {
unconfirmedSet.remove(seqNo);
}
}
public void handleNack(long seqNo, boolean multiple) {
// handle the lost messages somehow
}
I hope it helps
Ok, you always get the ACK for your message sent because "Every time message is delivered to Default Exchange Successfully."
PS: You are not sending message directly to Queue, Once Exchange recevis the message it gives you ACK then it route the message to all bound queue using the routing keys if any.

Specific message makes Push Sharp ApplePushService stop working

I am implementing push notifications using push sharp and I have 2 types of messages I am sending RecomendationLiked and NewFollower, I can send RecomendationLiked messages as much as I want and everything works fine but sending a single NewFollower message simpley causes the service to stop responding with no exception, or any of the events called. This happens both in Production and in Development environment
Here is the service creation logic:
private void InitApplePushService()
{
try
{
string appDataPath = HttpContext.Current.Server.MapPath("~/app_data");
//***** Development Server *****//
string file = Path.Combine(appDataPath, "PushSharp.PushCert.Development.p12");
var appleCert = File.ReadAllBytes(file);
_applePushService = new ApplePushService(new ApplePushChannelSettings(false, appleCert, "XXX"));
_applePushService.OnChannelCreated += OnChannelCreated;
_applePushService.OnChannelDestroyed += OnChannelDestroyed;
_applePushService.OnChannelException += OnChannelException;
_applePushService.OnDeviceSubscriptionChanged += OnDeciveSubscriptionChanged;
_applePushService.OnDeviceSubscriptionExpired += OnDeviceSubscriptionExpired;
_applePushService.OnNotificationFailed += OnNorificationFailed;
_applePushService.OnNotificationRequeue += OnNotificationQueued;
_applePushService.OnNotificationSent += OnNOtificationSend;
_applePushService.OnServiceException += OnServiceException;
Trace.TraceInformation("ApplePushService initialized succesfully");
}
catch (Exception e)
{
Trace.TraceError("Error initializing ApplePushService : " + e);
throw;
}
}
RecomendationLiked message creation:
private void SendRecomendationLikedMessageToAppleDevice(User likingUser, Recomendation recomendation)
{
var notification = new AppleNotification();
notification.DeviceToken = recomendation.User.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewLikeNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { likingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("LikingUser", likingUser.NickName);
notification.Payload.AddCustom("AlertType", "RecomendationLiked");
notification.Payload.AddCustom("ID", likingUser.ID);
notification.Payload.AddCustom("ImageUrl", likingUser.ImageUrl);
_applePushService.QueueNotification(notification);
}
NewFollower message creation:
private void SendNewFollowingUserMessageToAppleDevice(User followingUser, User followedUser)
{
var notification = new AppleNotification();
notification.DeviceToken = followedUser.PushNotificationID;
notification.Payload.Alert.LocalizedKey = "NewFollowingUserNotification";
notification.Payload.Alert.LocalizedArgs = new List<object> { followingUser.NickName };
notification.Payload.Sound = "default";
notification.Payload.AddCustom("followingUser", followingUser.NickName);
notification.Payload.AddCustom("AlertType", "NewFollowingUser");
notification.Payload.AddCustom("ID", followingUser.ID);
notification.Payload.AddCustom("ImageUrl", followingUser.ImageUrl);
Trace.TraceInformation("Trying to send notifications: "+ notification);
_applePushService.QueueNotification(notification);
//_pushService.QueueNotification(notification);
}
The first one works, the second kills the push service silently...
Any ideas?
Solved it finally...
The issue is with the length of the json string that is generated. it seems that the maximum is 255 chars. anything higher and it fails silently...
beware.
Amit

Categories

Resources