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>
});
});
}
Related
I am trying to delete message in SQS queue, but it is not deleting in the queue. I have been trying to make a lot of changes, but is still not working. I am new to c#, .net core, and AWS. Can anyone please help me with this?
Here is my main method:
[HttpGet]
public async Task<ReceiveMessageResponse> Get()
{
ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest
{
WaitTimeSeconds = 3 //it'll ping the queue for 3 seconds if I don't do this, sometimes I receive message and sometimes I don't
};
receiveMessageRequest.QueueUrl = myQueueUrl;
receiveMessageRequest.MaxNumberOfMessages = 10; // can change number of messages as needed
//receiveing messages/responses
var receiveMessageResponse = await amazonSQSClient.ReceiveMessageAsync(receiveMessageRequest);
if (receiveMessageResponse.Messages.Count > 0){
var bucketName = getBucketName(receiveMessageResponse);
var objectKey = getObjectKey(receiveMessageResponse);
var versionId = getVersionId(receiveMessageResponse);
string filePath = "C:\\InputPdfFile\\"; // change it later
string path = filePath + objectKey;
//get the file from s3 bucket and download it in in
var downloadInputFile = await DownloadAsync(path, versionId, objectKey);
//Get score from the output file
string jsonOutputFileName = "\\file-1.txt"; //change it later from text file to json file
string jsonOutputPath = "C:\\OutputJsonFile"; //change it later
string jasonArchivePath = "C:\\ArchiveJsonFile"; //change it later
int score = GetOutputScore(jsonOutputPath, jsonOutputFileName);
//update metadata from the score received from ML worker (GetOutputScore)
PutObjectResponse putObjectResponse = await UpdateMetadataAsync(score);
//Move file from output to archive after updating metadata
string sourceFile = jsonOutputPath + jsonOutputFileName;
string destFile = jasonArchivePath + jsonOutputFileName;
if (!Directory.Exists(jasonArchivePath))
{
Directory.CreateDirectory(jasonArchivePath);
}
System.IO.File.Move(sourceFile, destFile);
//delete message after moving file from archive
*DeleteMessage(receiveMessageResponse);* //not sure why it is not deleting**
}
return receiveMessageResponse;
}
Here is my Delete method:
public async void DeleteMessage(ReceiveMessageResponse receiveMessageResponse)
{
if (receiveMessageResponse.Messages.Count > 0)
{
foreach (var message in receiveMessageResponse.Messages)
{
var delRequest = new DeleteMessageRequest
{
QueueUrl = myQueueUrl,
ReceiptHandle = message.ReceiptHandle
};
var deleteMessage = await amazonSQSClient.DeleteMessageAsync(delRequest);
}
}
else // It is not going in else because the message was found but still not deleting it
{
Console.WriteLine("No message found");
}
}
Any help would be greatly appreciated!
I created an console app with .NET 4.0 like this:
static void Test2(string deviceToken, string message)
{
try
{
//Get Certificate
var appleCert = System.IO.File.ReadAllBytes("Certificates_moi.p12");
// Configuration (NOTE: .pfx can also be used here)
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox, appleCert, "vnpt1234");
// Create a new broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) =>
{
aggregateEx.Handle(ex =>
{
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
string desc = "Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}";
Console.WriteLine(desc);
//lblStatus.Text = desc;
}
else
{
string desc = "Apple Notification Failed for some unknown reason : {ex.InnerException}";
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine(desc);
//lblStatus.Text = desc;
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) =>
{
//lblStatus.Text = "Apple Notification Sent successfully!";
Console.WriteLine("Apple Notification Sent successfully!");
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string devicToken, DateTime timestamp) =>
{
// Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
};
// Start Proccess
apnsBroker.Start();
if (deviceToken != "")
{
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload = JObject.Parse(("{\"aps\":{\"badge\":1,\"sound\":\"oven.caf\",\"alert\":\"" + (message + "\"}}")))
});
}
apnsBroker.Stop();
}
catch (Exception ex)
{
throw;
}
}
There is an error at apnsBroker.Start();
- $exception {"Specified argument was out of the range of valid values.\r\nParameter name: creationOptions"} System.Exception {System.ArgumentOutOfRangeException}
Can anybody help me, please?
I fixed this issue. Move to another machine running .NET 4.5 and it worked.
In my UWP app I am downloading a file and storing it in the location chosen by the user using FolderPicker. When the download has completed, I show a ToastNotification. I am using these two namespaces as shown in the docs.
using Microsoft.QueryStringDotNET; // for receciving arguments
using Microsoft.Toolkit.Uwp.Notifications;
the toast that I send has two buttons, 1) open the file 2) Dismiss.
I want to open the downloaded file when the user taps on the first button.
But from what I understand, toasts can only send string arguments to the application ( Correct me if wrong ). And in order to open a file, StorageFile object is needed ( path of StorageFile won't do ).
So is there any way to actually open the downloaded file from the toast ( using foreground or background activation ) ?
Code to download the file:
private async void DownloadButton_Click(object sender, RoutedEventArgs e)
{
StorageFolder selectedFolder;
try
{
selectedFolder = await ChooseFolderAsync();
}
catch
{
Toast.ShowToast("Something went wrong", ToastRow);
return;
}
Uri downloadLink = new Uri("ValidUri");
StorageFile destinationFile = await selectedFolder.CreateFileAsync(selectedAsset.name, CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
downloader.SuccessToastNotification = handler.MakeToastWithButtons("Downloaded", selectedAsset.name, "Open", "Dismiss");
// downloader.SuccessToastNotification = handler.MakeToast("Downloaded", nameOfFile, string.Empty, 2);
DownloadOperation download = downloader.CreateDownload(downloadLink, destinationFile);
download.Priority = BackgroundTransferPriority.High;
download.CostPolicy = BackgroundTransferCostPolicy.Always;
var toast = handler.MakeToast("Downloading...", selectedAsset.name, selectedAsset.contentSize, 12);
toast.Group = "downloadStartedTag";
ToastNotificationManager.CreateToastNotifier().Show(toast);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(handler.DownloadProgress);
try
{
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
catch (Exception ex)
{
var errorCode = BackgroundTransferError.GetStatus(ex.HResult);
toast = handler.MakeToast("Download failed", selectedAsset.name, TextFormatter.CamelToHumanCase(errorCode.ToString()), 12);
toast.Group = "downloadFailedTag";
ToastNotificationManager.CreateToastNotifier().Show(toast);
return;
}
finally
{
ToastNotificationManager.History.Remove("downloadStartedTag");
}
}
Method that creates toast:
public ToastNotification MakeToastWithButtons(string heading, string line1, string button1, string button2)
{
ToastVisual visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText() {Text = heading},
new AdaptiveText() {Text = line1},
}
}
};
ToastActionsCustom actions = new ToastActionsCustom()
{
Buttons =
{
new ToastButton("Open", new QueryString()
{
{ "action", "open" }
//maybe file path can be given here in some argument
}.ToString())
{
ActivationType = ToastActivationType.Foreground
},
new ToastButton("Dismiss", new QueryString()
{
{ "action", "dismiss" }
//more details about the file can be given here
}.ToString())
{
ActivationType = ToastActivationType.Background
}
}
};
ToastContent toastContent = new ToastContent()
{
Visual = visual,
Actions = actions,
// Arguments when the user taps body of toast
Launch = new QueryString()
{
{ "action", "nothing" }
}.ToString()
};
// And create the toast notification
var toast = new ToastNotification(toastContent.GetXml());
toast.ExpirationTime = DateTime.Now.AddDays(2);
toast.Group = "DownloadCompleteGroup";
return toast;
}
One way to do this is to store the destinationFile created by the background download in the FutureAccessList, which will provide you with a token you can add to the payload data of the toast:
// using Windows.Storage.AccessCache;
string token = StorageApplicationPermissions.FutureAccessList.Add(destinationFile);
// add the token to your toast payload
Then when the user clicks the toast, you can redeem the token to get the file back:
var file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token);
Now you can do things with the file. Note that the token is good "forever" - as long as the file exists on disk, the token will work after your app restarts or even a reboot.
When you are done with the file (including if the download fails or the user cancels, etc.) you should remove the token from FutureAccessList so that the list doesn't fill up:
StorageApplicationPermissions.FutureAccessList.Remove(token);
This means you likely want to persist the token in your app's settings as well, just in case the user ignores the toast.
I'm trying to make an program that send a file to a mobile device encrypted, and the device will get it in another program and decrypt it.
So far I've done the bluetooth connection:
private void Connect()
{
using (SelectBluetoothDeviceDialog bldialog = new SelectBluetoothDeviceDialog())
{
bldialog.ShowAuthenticated = true;
bldialog.ShowRemembered = true;
bldialog.ShowUnknown = true;
if (bldialog.ShowDialog() == System.Windows.Forms.DialogResult.OK )
{
if (bldialog.SelectedDevice == null)
{
System.Windows.Forms.MessageBox.Show("No device selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
BluetoothDeviceInfo selecteddevice = bldialog.SelectedDevice;
BluetoothEndPoint remoteEndPoint = new BluetoothEndPoint(selecteddevice.DeviceAddress, BluetoothService.ObexFileTransfer);
client = new BluetoothClient();
client.Connect(remoteEndPoint);
session = new ObexClientSession(client.GetStream(), UInt16.MaxValue);
session.Connect(ObexConstant.Target.FolderBrowsing);
tbConnectionDet.Text = string.Format("Connected to: {0}", selecteddevice.DeviceName);
}
}
}
Also I'm sending the file this way:
private void UploadFiles(string[] files)
{
long size = 0;
List<string> filestoupload = new List<string>();
foreach (string filename in files)
{
if (File.Exists(filename))
{
FileInfo info = new FileInfo(filename);
filestoupload.Add(filename);
size += info.Length;
}
}
using (FileForm upform = new FileForm(new List<string>(filestoupload),
false, session, size, null))
{
upform.ExceptionMethod = ExceptionHandler;
upform.ShowDialog();
lsvExplorer.BeginUpdate();
for (int i = 0; i <= upform.FilesUploaded; i++)
{
ListViewItem temp = new ListViewItem(new string[]{ Path.GetFileName(filestoupload[i]),
FormatSize(new FileInfo(filestoupload[i]).Length, false)},
GetIconIndex(Path.GetExtension(filestoupload[i]), false));
temp.Tag = false;
lsvExplorer.Items.Add(temp);
}
lsvExplorer.EndUpdate();
}
}
I'm using 32feet and BrechamObex libraries .
I have the following questions :
I want to send a public key from my phone to my computer then encrypt a file and send it back to my phone. After I receive the file, I want to decrypt it so I will need another program in order to do this. How can I send information from one program to another using bluetooth?
Whenever I send a file, the phone gets it, but the size it always 0
i have developed code for push notification in ios in c# but it is not sending notification in mobile.
I have used pushsharp library.
My code is as followed:
PushNotificationApple pushNotification = new PushNotificationApple();
pushNotification.SendNotification(postData);
My PushNotificationApple constructor code is as below:-
public PushNotificationApple()
{
if (_pushBroker == null)
{
//Create our push services broker
_pushBroker = new PushBroker();
//Wire up the events for all the services that the broker registers
_pushBroker.OnNotificationSent += NotificationSent;
_pushBroker.OnChannelException += ChannelException;
_pushBroker.OnServiceException += ServiceException;
_pushBroker.OnNotificationFailed += NotificationFailed;
_pushBroker.OnDeviceSubscriptionExpired += DeviceSubscriptionExpired;
_pushBroker.OnDeviceSubscriptionChanged += DeviceSubscriptionChanged;
_pushBroker.OnChannelCreated += ChannelCreated;
_pushBroker.OnChannelDestroyed += ChannelDestroyed;
var appleCert = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath("~/Certificates" + ConfigSettings.SnaptymAPNSCertificate));
_pushBroker.RegisterAppleService(new ApplePushChannelSettings(false, appleCert,ConfigSettings.SnaptymAPNSPassword)); //Extension method
}
}
My SendNotification function is as below:-
public bool SendNotification(GcmNotificationPostDataModel postData)
{
if (_pushBroker != null)
{
foreach (var registrationId in postData.RegistrationIds)
{
_pushBroker.QueueNotification(new AppleNotification()
.ForDeviceToken(registrationId) //the recipient device id
.WithAlert(postData.Data.Message) //the message
.WithBadge(1)
.WithSound("sound.caf"));
}
}
return true;
}
I am making use of PushSharp 4.0.10 and the following code works for me.
private void SendMessage()
{
//IOS
var MainApnsData = new JObject();
var ApnsData = new JObject();
var data = new JObject();
MainApnsData.Add("alert", Message.Text.Trim());
MainApnsData.Add("badge", 1);
MainApnsData.Add("Sound", "default");
data.Add("aps", MainApnsData);
ApnsData.Add("CalledFromNotify", txtboxID.Text.Trim());
data.Add("CustomNotify", ApnsData);
//read the .p12 certificate file
byte[] bdata = System.IO.File.ReadAllBytes(Server.MapPath("~/App_Data/CertificatesPushNew.p12"));
//create push sharp APNS configuration
var config = new ApnsConfiguration(ApnsConfiguration.ApnsServerEnvironment.Sandbox,bdata,"YourPassword");
//create a apnService broker
var apnsBroker = new ApnsServiceBroker(config);
// Wire up events
apnsBroker.OnNotificationFailed += (notification, aggregateEx) => {
aggregateEx.Handle(ex => {
// See what kind of exception it was to further diagnose
if (ex is ApnsNotificationException)
{
var notificationException = (ApnsNotificationException)ex;
// Deal with the failed notification
var apnsNotification = notificationException.Notification;
var statusCode = notificationException.ErrorStatusCode;
Console.WriteLine($"Apple Notification Failed: ID={apnsNotification.Identifier}, Code={statusCode}");
}
else
{
// Inner exception might hold more useful information like an ApnsConnectionException
Console.WriteLine($"Apple Notification Failed for some unknown reason : {ex.InnerException}");
}
// Mark it as handled
return true;
});
};
apnsBroker.OnNotificationSucceeded += (notification) => {
Console.WriteLine("Apple Notification Sent!");
};
var fbs = new FeedbackService(config);
fbs.FeedbackReceived += (string deviceToken1, DateTime timestamp) =>
{
//Remove the deviceToken from your database
// timestamp is the time the token was reported as expired
Console.WriteLine("Feedback received!");
};
fbs.Check();
// Start the broker
apnsBroker.Start();
var deviceToken = "Your device token";
// Queue a notification to send
apnsBroker.QueueNotification(new ApnsNotification
{
DeviceToken = deviceToken,
Payload= data
});
// Stop the broker, wait for it to finish
// This isn't done after every message, but after you're
// done with the broker
apnsBroker.Stop();
}