Beispiel #1
0
        private static async void MessageSender(string contactNumber)
        {
            if (_device == null)
            {
                try
                {
                    _device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return;
                }
            }
            //if (_device == null) return;

            var msg = new SmsTextMessage2
            {
                To   = contactNumber,
                Body = "I am in need of help. My coordinates are\n Latitude:" + _latitude + "Longitude \n" + _longitude
            };
            var result = await _device.SendMessageAndGetResultAsync(msg);

            if (!result.IsSuccessful)
            {
                return;
            }
            var msgStr = "";

            msgStr += "Text message sent, To: " + _phonenumber;
            var msg1 = new MessageDialog("Message Sent!" + msgStr);
            await msg1.ShowAsync();
        }
Beispiel #2
0
 public static async void SendSmsAsync(string message, List<object> recipients)
 {
     var contacts = recipients.Cast<EventContact>();
     foreach(var contact in contacts)
     {
         var sms = new SmsTextMessage2();
         sms.To = contact.PhoneNumber;
         sms.Body = message;
         var result = await SmsDevice2.GetDefault().SendMessageAndGetResultAsync(sms);
     }
 }
Beispiel #3
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
            string taskName = taskInstance.Task.Name;

            var smsDetails = taskInstance.TriggerDetails as SmsMessageReceivedTriggerDetails;

            SmsTextMessage2 smsTextMessage = smsDetails.TextMessage;

            Debug.WriteLine(smsTextMessage.Body);

            //            smsTextMessage.

            smsDetails.Accept();

            //settings.Values[taskName] = notification.Content;
        }
Beispiel #4
0
        private async void MessageSender(string contactNumber)
        {
            if (_device == null)
            {
                try
                {
                    _device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return;
                }
            }
            //if (_device == null) return;


            var msg = new SmsTextMessage2
            {
                To   = contactNumber,
                Body = Message + "\t My coordinates are\n Latitude:" + _latitude + "Longitude \n" + _longitude
            };
            var result = await _device.SendMessageAndGetResultAsync(msg);

            SosPageText += "Sending Message.... \n";
            RaisePropertyChanged(() => SosPageText);

            if (!result.IsSuccessful)
            {
                if (result.NetworkCauseCode.Equals(50))
                {
                    SosPageText += "\n Network Error in sending SMS. Possibly no balance!";
                }
                SosPageText += "Message Sending Failed \n";
                RaisePropertyChanged(() => SosPageText);
                return;
            }
            var msgStr = "";

            msgStr      += "Text message sent, To: " + _phonenumber;
            SosPageText += msgStr + "\n";
            RaisePropertyChanged(() => SosPageText);
        }
Beispiel #5
0
        private async void btnSendSms_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var id      = lbDevices.SelectedItem as string;
                var device  = SmsDevice2.FromId(id);
                var message = new SmsTextMessage2();
                message.Body = "test sms";
                var messageLength = device.CalculateLength(message);
                message.To = txtTo.Text;
                var result = await device.SendMessageAndGetResultAsync(message);

                await new MessageDialog($"successfull: {result.IsSuccessful}").ShowAsync();
                await new MessageDialog($"TransportFailureCause: {result.TransportFailureCause}").ShowAsync();
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }
Beispiel #6
0
        public void SendSmsInBackground(string recipient, string message = null)
        {
            if (string.IsNullOrEmpty(recipient))
            {
                throw new ArgumentException(nameof(recipient));
            }

            message = message ?? string.Empty;

            if (CanSendSmsInBackground)
            {
                var sendingMessage = new SmsTextMessage2
                {
                    Body = message,
                    To   = recipient
                };

                SmsDevice2.GetDefault().SendMessageAndGetResultAsync(sendingMessage).AsTask().Wait();
            }
        }
        private async Task Send_Message(bool Emergency = true)
        {
            if (device == null)
            {
                try
                {
                    device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    NotifyUser(ex.Message, NotifyType.ErrorMessage);
                    return;
                }
            }

            string msgStr = "";

            if (device != null)
            {
                try
                {
                    // Create a text message - set the entered destination number and message text.
                    SmsTextMessage2 msg = new SmsTextMessage2();

                    // TODO : What to do below?
                    msg.To = Mnum.countryCode + Mnum.tenDigits;
                    // msg.To = Mnum.tenDigits;

                    try
                    {
                        if (Emergency)
                        {
                            msg.Body = "The Be-Safe app on this user's device has encountered a high acceleration event. Since your number has been listed as the emergency contact by the user, it is highly recommended that an immediate call is made to assure their safety. User's Location Coordinates : " + pos.Coordinate.Latitude.ToString("0.00") + ", " + pos.Coordinate.Longitude.ToString("0.00");
                        }
                        else
                        {
                            msg.Body = "The Be-Safe app is extremely sorry. The user of this number is completely safe, the previous message was a false alarm!";
                        }
                    }
                    catch (Exception)
                    {
                        msg.Body = "Emergency alert! I have been in a possible accident detected automatically by a high acceleration event. Please help.";
                    }
                    // Send the message asynchronously
                    if (Emergency)
                    {
                        NotifyUser("Sending Message to emergency contact.", NotifyType.StatusMessage);
                    }

                    SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                    if (result.IsSuccessful)
                    {
                        msgStr  = "";
                        msgStr += "Message sent to: " + Mnum.countryCode + Mnum.tenDigits + " (Predefined Emergency Number)" + System.Environment.NewLine;
                        try
                        {
                            if (Emergency)
                            {
                                msgStr += "The Be-Safe app on this user's device has encountered a high acceleration event. Since your number has been listed as the emergency contact by the user, it is highly recommended that an immediate call is made to assure their safety. User's Location Coordinates : " + pos.Coordinate.Latitude.ToString("0.00") + ", " + pos.Coordinate.Longitude.ToString("0.00") + System.Environment.NewLine;
                            }
                            else
                            {
                                msgStr += "The Be-Safe app is extremely sorry. The user of this number is completely safe, the previous message was a false alarm!";
                            }
                        }
                        catch (Exception)
                        {
                            msgStr += "Emergency alert! I have been in a possible accident detected automatically by a high acceleration event. Please help.";
                        }
                        if (Emergency)
                        {
                            MainPage.DisplayToast("Emergency Text Sent to " + Mnum.countryCode + Mnum.tenDigits);
                        }
                        else
                        {
                            MainPage.DisplayToast("False Alarm Message Sent");
                        }

                        IReadOnlyList <Int32> messageReferenceNumbers = result.MessageReferenceNumbers;
                        NotifyUser(msgStr, NotifyType.StatusMessage);
                        if (!Emergency)
                        {
                            FalseAlarmButton.Visibility = Visibility.Collapsed;
                            textBlock3.Text             = "False Alarm Message Sent. Sorry for the inconvenience.";
                        }
                        else
                        {
                            FalseAlarmButton.Visibility = Visibility.Visible;
                        }
                    }

                    else
                    {
                        msgStr  = "";
                        msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                        msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                        if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                        {
                            msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                            if (result.CellularClass == CellularClass.Cdma)
                            {
                                msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                            }
                            NotifyUser(msgStr, NotifyType.ErrorMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
            }
            else
            {
                if (Mnum != null)
                {
                    NotifyUser("Could not connect to network. SMS could not be sent", NotifyType.ErrorMessage);
                }
                else
                {
                    NotifyUser("You have not yet entered your emergency contact number!", NotifyType.ErrorMessage);
                }
            }
        }
Beispiel #8
0
        private static async void MessageSender(string contactNumber)
        {
            if (_device == null)
            {
                try
                {
                    _device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return;
                }

            }
            //if (_device == null) return;

            var msg = new SmsTextMessage2
            {
                To = contactNumber,
                Body = "I am in need of help. My coordinates are\n Latitude:" + _latitude + "Longitude \n" + _longitude
            };
            var result = await _device.SendMessageAndGetResultAsync(msg);

            if (!result.IsSuccessful) return;
            var msgStr = "";
            msgStr += "Text message sent, To: " + _phonenumber;
            var msg1 = new MessageDialog("Message Sent!" + msgStr);
            await msg1.ShowAsync();
        }
        // Clicking of the Start App button
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            // This event occurs when the user clicks the Start App button and is distinguished from the event where
            // this button click is triggered by a high acceleration event.
            if (HighAccEvent == false)
            {
                // If the device does have an accelerometer
                if (_accelerometer != null)
                {
                    // Set the report interval to enable the sensor for polling
                    _accelerometer.ReportInterval = _desiredReportInterval;
                    _dispatcherTimer.Start();
                }

                // No Accelerometer found. Notify the user.
                else
                {
                    rootPage.NotifyUser("No accelerometer found. This app is not compatible with your device.", NotifyType.ErrorMessage);
                }
            }


            // This sections corresponds to the the event in which the clicking of the start app button is triggered by HighAccEvent
            else
            {
                // Geolocation based on bing API
                Geolocator geolocator = new Geolocator();
                geolocator.DesiredAccuracyInMeters = 500;
                try
                {
                    Geoposition geoposition = await geolocator.GetGeopositionAsync(
                         maximumAge: TimeSpan.FromMinutes(5),
                         timeout: TimeSpan.FromSeconds(10)
                        );

                    // If this is the first request, get the default SMS device. If this
                    // is the first SMS device access, the user will be prompted to grant
                    // access permission for this application.
                    if (device == null)
                    {
                        try
                        {
                            rootPage.NotifyUser("Getting default SMS device ...", NotifyType.StatusMessage);
                            device = SmsDevice2.GetDefault();
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                            return;
                        }

                    }

                    string msgStr = "";
                    if (device != null)
                    {
                        try
                        {
                            // Create a text message - set the entered destination number and message text.
                            SmsTextMessage2 msg = new SmsTextMessage2();

                            // If the user has not yet entered the number
                            if (Mnumber == null)
                            {
                                rootPage.NotifyUser("You have not yet entered your emergency contact number!", NotifyType.ErrorMessage);
                                return;
                            }

                            msg.To = Mnumber;
                            msg.Body = "Emergency alert! I have been in a possible accident at " + geoposition.Coordinate.Latitude.ToString("0.00") + ", " + geoposition.Coordinate.Longitude.ToString("0.00") + ". Please help.";

                            // Send the message asynchronously
                            rootPage.NotifyUser("Sending Message to emergency contact and rescue services.", NotifyType.StatusMessage);
                            SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                            if (result.IsSuccessful)
                            {
                                msgStr = "";
                                msgStr += "Message sent to: " + Mnumber + "(Predefined Emergency Number)" + System.Environment.NewLine;
                                msgStr += "Emergency alert! I have been in a possible accident at Map Coordinates:" + geoposition.Coordinate.Latitude.ToString("0.00") + ", " + geoposition.Coordinate.Longitude.ToString("0.00") + ". Please help." + System.Environment.NewLine;

                                IReadOnlyList<Int32> messageReferenceNumbers = result.MessageReferenceNumbers;
                                rootPage.NotifyUser(msgStr, NotifyType.StatusMessage);
                            }

                            else
                            {
                                msgStr = "";
                                msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                                msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                                if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                                {
                                    msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                                    if (result.CellularClass == CellularClass.Cdma)
                                    {
                                        msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                                    }
                                    rootPage.NotifyUser(msgStr, NotifyType.ErrorMessage);
                                }
                            }

                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        if (Mnumber != "default")
                            rootPage.NotifyUser("Could not connect to network. SMS could not be sent", NotifyType.ErrorMessage);
                        else
                            rootPage.NotifyUser("You have not yet entered your emergency contact number!", NotifyType.ErrorMessage);
                    }
                }
                catch (Exception ex)
                { // No action needed
                }
            }
        }
Beispiel #10
0
        private async void SendButton_Click(object sender, RoutedEventArgs e)
        {
            if (device == null)

            {
                try

                {
                    Debug.WriteLine("Getting default SMS device ...");

                    device = SmsDevice2.GetDefault();
                }

                catch (Exception ex)

                {
                    Debug.WriteLine(ex.Message);

                    return;
                }
            }



            string msgStr = "";

            if (device != null)

            {
                var wors = recipientbox.Text.Split("; ");
                foreach (var wor in wors)
                {
                    try

                    {
                        // Create a text message - set the entered destination number and message text.

                        SmsTextMessage2 msg = new SmsTextMessage2();

                        msg.To = wor;

                        msg.Body = MessageTB.Text;

                        // Send the message asynchronously

                        Debug.WriteLine("Sending message ...");

                        SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);



                        if (result.IsSuccessful)

                        {
                            msgStr = "";

                            msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();

                            IReadOnlyList <Int32> messageReferenceNumbers = result.MessageReferenceNumbers;



                            for (int i = 0; i < messageReferenceNumbers.Count; i++)

                            {
                                msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
                            }

                            Debug.WriteLine(msgStr);
                        }

                        else

                        {
                            msgStr = "";

                            msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();

                            msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();

                            if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)

                            {
                                msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();



                                if (result.CellularClass == CellularClass.Cdma)

                                {
                                    msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                                }

                                Debug.WriteLine(msgStr);
                            }
                        }
                    }

                    catch (Exception ex)

                    {
                        Debug.WriteLine(ex.Message);
                    }
                }
            }

            else

            {
                Debug.WriteLine("Failed to find SMS device");
            }
        }
        private async void MessageSender(string contactNumber)
        {
            if (_device == null)
            {
                try
                {
                    _device = SmsDevice2.GetDefault();
                    
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return;
                }

            }
            //if (_device == null) return;

            
            var msg = new SmsTextMessage2
            {
                To = contactNumber,
                Body = Message+"\t My coordinates are\n Latitude:" + _latitude + "Longitude \n" + _longitude
            };
            var result = await _device.SendMessageAndGetResultAsync(msg);
            SosPageText += "Sending Message.... \n";
            RaisePropertyChanged(() => SosPageText);

            if (!result.IsSuccessful)
            {
                if (result.NetworkCauseCode.Equals(50))
                {
                    SosPageText += "\n Network Error in sending SMS. Possibly no balance!";
                }
                SosPageText += "Message Sending Failed \n";
                RaisePropertyChanged(() => SosPageText);
                return;
            }
            var msgStr = "";
            msgStr += "Text message sent, To: " + _phonenumber;
            SosPageText += msgStr+"\n";
            RaisePropertyChanged(()=>SosPageText);
        }
Beispiel #12
0
        public async static Task <bool> SendTextMessageAsync(SmsDevice2 device, string[] numbers, string textmessage, string transportId = "0")
        {
            bool             returnresult = true;
            ChatMessageStore store        = await ChatMessageManager.RequestStoreAsync();

            if (string.IsNullOrEmpty(transportId) || await ChatMessageManager.GetTransportAsync(transportId) == null)
            {
                var transports = await ChatMessageManager.GetTransportsAsync();

                if (transports.Count != 0)
                {
                    var transport = transports[0];
                    transportId = transport.TransportId;
                }
                else
                {
                    transportId = await ChatMessageManager.RegisterTransportAsync();
                }
            }
            try
            {
                SmsTextMessage2 message = new SmsTextMessage2();
                message.Body = textmessage;

                foreach (var number in numbers)
                {
                    var num = number.Trim();
                    message.To = num;

                    try
                    {
                        SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(message);

                        var offset = new DateTimeOffset(DateTime.Now);

                        returnresult &= result.IsSuccessful;

                        try
                        {
                            ChatMessage msg = new ChatMessage();

                            msg.Body = textmessage;
                            msg.Recipients.Add(num);

                            msg.LocalTimestamp   = offset;
                            msg.NetworkTimestamp = offset;

                            msg.IsIncoming  = false;
                            msg.TransportId = transportId;

                            msg.MessageOperatorKind = ChatMessageOperatorKind.Sms;
                            msg.Status = result.IsSuccessful ? ChatMessageStatus.Sent : ChatMessageStatus.SendFailed;

                            await store.SaveMessageAsync(msg);
                        }
                        catch
                        {
                        }
                    }
                    catch
                    {
                        returnresult = false;
                    }
                }
            }
            catch
            {
                returnresult = false;
            }

            return(returnresult);
        }
Beispiel #13
0
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            if (SendToText.Text == "")
            {
                rootPage.NotifyUser("Please enter sender number", NotifyType.ErrorMessage);
                return;
            }

            if (SendMessageText.Text == "")
            {
                rootPage.NotifyUser("Please enter message", NotifyType.ErrorMessage);
                return;
            }

            // If this is the first request, get the default SMS device. If this
            // is the first SMS device access, the user will be prompted to grant
            // access permission for this application.
            if (device == null)
            {
                try
                {
                    rootPage.NotifyUser("Getting default SMS device ...", NotifyType.StatusMessage);
                    device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                    return;
                }
            }

            string msgStr = "";

            if (device != null)
            {
                try
                {
                    // Create a text message - set the entered destination number and message text.
                    SmsTextMessage2 msg = new SmsTextMessage2();
                    msg.To   = SendToText.Text;
                    msg.Body = SendMessageText.Text;

                    // Send the message asynchronously
                    rootPage.NotifyUser("Sending message ...", NotifyType.StatusMessage);
                    SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                    if (result.IsSuccessful)
                    {
                        msgStr  = "";
                        msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();
                        IReadOnlyList <Int32> messageReferenceNumbers = result.MessageReferenceNumbers;

                        for (int i = 0; i < messageReferenceNumbers.Count; i++)
                        {
                            msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
                        }
                        rootPage.NotifyUser(msgStr, NotifyType.StatusMessage);
                    }
                    else
                    {
                        msgStr  = "";
                        msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                        msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                        if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                        {
                            msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                            if (result.CellularClass == CellularClass.Cdma)
                            {
                                msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                            }
                            rootPage.NotifyUser(msgStr, NotifyType.ErrorMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Failed to find SMS device", NotifyType.ErrorMessage);
            }
        }
Beispiel #14
0
        public static async void sendSMS(String to, String text)
        {
            if (device == null)
            {
                try
                {
                    //DialogBox.ShowOk("Notification", "Getting default SMS device ...");
                    device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    //rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                    DialogBox.ShowOk("Error", ex.Message);
                    return;
                }
            }

            string msgStr = "";

            if (device != null)
            {
                try
                {
                    // Create a text message - set the entered destination number and message text.
                    SmsTextMessage2 msg = new SmsTextMessage2();
                    msg.To   = to;
                    msg.Body = text;

                    // Send the message asynchronously
                    //rootPage.NotifyUser("Sending message ...", NotifyType.StatusMessage);
                    SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                    if (result.IsSuccessful)
                    {
                        msgStr  = "";
                        msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();
                        IReadOnlyList <Int32> messageReferenceNumbers = result.MessageReferenceNumbers;

                        for (int i = 0; i < messageReferenceNumbers.Count; i++)
                        {
                            msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
                        }
                        DialogBox.ShowOk("Success", msgStr);//change??
                    }
                    else
                    {
                        msgStr  = "";
                        msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                        msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                        if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                        {
                            msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                            if (result.CellularClass == CellularClass.Cdma)
                            {
                                msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                            }
                            DialogBox.ShowOk("Error", msgStr);
                        }
                    }
                }
                catch (Exception ex)
                {
                    DialogBox.ShowOk("Error", ex.Message);
                }
            }
            else
            {
                DialogBox.ShowOk("Error", "Failed to find SMS device");
            }
        }
        // Clicking of the Start App button
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            // This event occurs when the user clicks the Start App button and is distinguished from the event where
            // this button click is triggered by a high acceleration event.
            if (HighAccEvent == false)
            {
                // If the device does have an accelerometer
                if (_accelerometer != null)
                {
                    // Set the report interval to enable the sensor for polling
                    _accelerometer.ReportInterval = _desiredReportInterval;
                    _dispatcherTimer.Start();
                }

                // No Accelerometer found. Notify the user.
                else
                {
                    rootPage.NotifyUser("No accelerometer found. This app is not compatible with your device.", NotifyType.ErrorMessage);
                }
            }


            // This sections corresponds to the the event in which the clicking of the start app button is triggered by HighAccEvent
            else
            {
                // Geolocation based on bing API
                Geolocator geolocator = new Geolocator();
                geolocator.DesiredAccuracyInMeters = 500;
                try
                {
                    Geoposition geoposition = await geolocator.GetGeopositionAsync(
                        maximumAge : TimeSpan.FromMinutes(5),
                        timeout : TimeSpan.FromSeconds(10)
                        );

                    // If this is the first request, get the default SMS device. If this
                    // is the first SMS device access, the user will be prompted to grant
                    // access permission for this application.
                    if (device == null)
                    {
                        try
                        {
                            rootPage.NotifyUser("Getting default SMS device ...", NotifyType.StatusMessage);
                            device = SmsDevice2.GetDefault();
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                            return;
                        }
                    }

                    string msgStr = "";
                    if (device != null)
                    {
                        try
                        {
                            // Create a text message - set the entered destination number and message text.
                            SmsTextMessage2 msg = new SmsTextMessage2();

                            // If the user has not yet entered the number
                            if (Mnumber == null)
                            {
                                rootPage.NotifyUser("You have not yet entered your emergency contact number!", NotifyType.ErrorMessage);
                                return;
                            }

                            msg.To   = Mnumber;
                            msg.Body = "Emergency alert! I have been in a possible accident at " + geoposition.Coordinate.Latitude.ToString("0.00") + ", " + geoposition.Coordinate.Longitude.ToString("0.00") + ". Please help.";

                            // Send the message asynchronously
                            rootPage.NotifyUser("Sending Message to emergency contact and rescue services.", NotifyType.StatusMessage);
                            SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                            if (result.IsSuccessful)
                            {
                                msgStr  = "";
                                msgStr += "Message sent to: " + Mnumber + "(Predefined Emergency Number)" + System.Environment.NewLine;
                                msgStr += "Emergency alert! I have been in a possible accident at Map Coordinates:" + geoposition.Coordinate.Latitude.ToString("0.00") + ", " + geoposition.Coordinate.Longitude.ToString("0.00") + ". Please help." + System.Environment.NewLine;

                                IReadOnlyList <Int32> messageReferenceNumbers = result.MessageReferenceNumbers;
                                rootPage.NotifyUser(msgStr, NotifyType.StatusMessage);
                            }

                            else
                            {
                                msgStr  = "";
                                msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                                msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                                if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                                {
                                    msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                                    if (result.CellularClass == CellularClass.Cdma)
                                    {
                                        msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                                    }
                                    rootPage.NotifyUser(msgStr, NotifyType.ErrorMessage);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                        }
                    }
                    else
                    {
                        if (Mnumber != "default")
                        {
                            rootPage.NotifyUser("Could not connect to network. SMS could not be sent", NotifyType.ErrorMessage);
                        }
                        else
                        {
                            rootPage.NotifyUser("You have not yet entered your emergency contact number!", NotifyType.ErrorMessage);
                        }
                    }
                }
                catch (Exception ex)
                { // No action needed
                }
            }
        }
        public async void Communicate(Contact kontakt)
        {
            if (device == null)
            {
                try
                {
                    //dobavljanje device, api vrati standardno null ako bilo sta nije uredu ヽ(ಠ_ಠ)ノ
                    //treba i capability u manifestu
                    device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

            }
            if (device != null)
            {
                string msgStr;
                try
                {
                    //kreirati poruku
                    SmsTextMessage2 msg = new SmsTextMessage2();
                    //na koji broj
                    string telBroj = kontakt.Phones.FirstOrDefault<ContactPhone>().Number;
                    msg.To = telBroj;
                    //koji tekst
                    msg.Body = textPoruke;
                    //poslati poruku
                    SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);
                    if (result.IsSuccessful)
                    {
                        //povratni info slanja poruke
                        msgStr = "";
                        msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();
                        IReadOnlyList<Int32> messageReferenceNumbers = result.MessageReferenceNumbers;

                        for (int i = 0; i < messageReferenceNumbers.Count; i++)
                        {
                            msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
                        }
                    }
                    else
                    {
                        //povratni info neuspjesnog slanja poruke
                        msgStr = "";
                        msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                        msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                        if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                        {
                            msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                            if (result.CellularClass == CellularClass.Cdma)
                            {
                                msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                            }
                            throw new Exception(msgStr);
                        }
                    }
                }
                catch (Exception ex)
                {
                    //exceptione je dobro ponekad proslijediti onome ko koristi ovu metodu da moze obraditi sta da uradi u tim situacijama
                    throw ex;
                }
            }
            else
            {
                //ako je device null ne zna se zasto, pa se kaze da nema device 
                throw new Exception("Nema SMS device");
            }
        }
Beispiel #17
0
        private async Task DisplayToast(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                SmsMessageReceivedTriggerDetails smsDetails = taskInstance.TriggerDetails as SmsMessageReceivedTriggerDetails;

                string deviceid = "";
                string body     = "";
                string from     = "";
                ContactUtils.ContactInformation information = new ContactUtils.ContactInformation();

                switch (smsDetails.MessageType)
                {
                case SmsMessageType.Text:
                {
                    SmsTextMessage2 smsTextMessage = smsDetails.TextMessage;
                    body        = smsTextMessage.Body;
                    deviceid    = smsTextMessage.DeviceId;
                    from        = smsTextMessage.From;
                    information = await ContactUtils.FindContactInformationFromSmsMessage(smsTextMessage);

                    break;
                }

                /*case SmsMessageType.Wap:
                 *  {
                 *      SmsWapMessage smsWapMessage = smsDetails.WapMessage;
                 *      body = "[DEBUG - Report if seen] " + smsWapMessage.ContentType + " - " + "Wap";
                 *      deviceid = smsWapMessage.DeviceId;
                 *      from = smsWapMessage.From;
                 *      information = await ContactUtils.FindContactInformationFromSmsMessage(smsWapMessage);
                 *      break;
                 *  }
                 * case SmsMessageType.App:
                 *  {
                 *      SmsAppMessage smsAppMessage = smsDetails.AppMessage;
                 *      body = "[DEBUG - Report if seen] " + smsAppMessage.Body + " - RAW: " + BitConverter.ToString(smsAppMessage.BinaryBody.ToArray()) + " - " + "App";
                 *      deviceid = smsAppMessage.DeviceId;
                 *      from = smsAppMessage.From;
                 *      information = await ContactUtils.FindContactInformationFromSmsMessage(smsAppMessage);
                 *      break;
                 *  }
                 * case SmsMessageType.Status:
                 *  {
                 *      SmsStatusMessage smsStatusMessage = smsDetails.StatusMessage;
                 *      body = "[DEBUG - Report if seen] " + smsStatusMessage.Body + " - " + smsStatusMessage.Status.ToString() + " - " + "Status";
                 *      deviceid = smsStatusMessage.DeviceId;
                 *      from = smsStatusMessage.From;
                 *      information = await ContactUtils.FindContactInformationFromSmsMessage(smsStatusMessage);
                 *      break;
                 *  }*/
                default:
                    return;
                }

                var toastContent = new ToastContent()
                {
                    Visual = new ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            Children =
                            {
                                new AdaptiveText()
                                {
                                    Text         = information.DisplayName,
                                    HintMaxLines = 1
                                },
                                new AdaptiveText()
                                {
                                    Text = body
                                }
                            },
                            AppLogoOverride = new ToastGenericAppLogo()
                            {
                                Source   = information.ThumbnailPath,
                                HintCrop = ToastGenericAppLogoCrop.Circle
                            },
                            Attribution = new ToastGenericAttributionText()
                            {
                                Text = information.PhoneNumberKind
                            }
                        }
                    },
                    Actions = new ToastActionsCustom()
                    {
                        Inputs =
                        {
                            new ToastTextBox("textBox")
                            {
                                PlaceholderContent = "Type a message"
                            }
                        },
                        Buttons =
                        {
                            new ToastButton("Send", $"action=reply&from={from}&deviceid={deviceid}")
                            {
                                ActivationType = ToastActivationType.Background,
                                ImageUri       = "Assets/ToastIcons/Send.png",
                                TextBoxId      = "textBox"
                            }
                        }
                    },
                    Launch = $"action=openThread&from={from}&deviceid={deviceid}",
                    Audio  = new ToastAudio()
                    {
                        Src = new Uri("ms-winsoundevent:Notification.SMS")
                    }
                };

                var toastNotif = new ToastNotification(toastContent.GetXml());
                ToastNotificationManager.CreateToastNotifier().Show(toastNotif);

                try
                {
                    BadgeHandler.IncreaseBadgeNumber();
                }
                catch
                {
                }

                smsDetails.Accept();
            }
            catch
            {
            }
        }
        private async void Send_Click(object sender, RoutedEventArgs e)
        {
            if (SendToText.Text == "")
            {
                rootPage.NotifyUser("Please enter sender number", NotifyType.ErrorMessage);
                return;
            }

            if (SendMessageText.Text == "")
            {
                rootPage.NotifyUser("Please enter message", NotifyType.ErrorMessage);
                return;
            }

            // If this is the first request, get the default SMS device. If this
            // is the first SMS device access, the user will be prompted to grant
            // access permission for this application.
            if (device == null)
            {
                try
                {
                    rootPage.NotifyUser("Getting default SMS device ...", NotifyType.StatusMessage);
                    device = SmsDevice2.GetDefault();
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                    return;
                }
                
            }

            string msgStr = "";
            if (device != null)
            {
                try
                {
                    // Create a text message - set the entered destination number and message text.
                    SmsTextMessage2 msg = new SmsTextMessage2();
                    msg.To = SendToText.Text;
                    msg.Body = SendMessageText.Text;

                    // Send the message asynchronously
                    rootPage.NotifyUser("Sending message ...", NotifyType.StatusMessage);
                    SmsSendMessageResult result = await device.SendMessageAndGetResultAsync(msg);

                    if (result.IsSuccessful)
                    {
                        msgStr = "";
                        msgStr += "Text message sent, cellularClass: " + result.CellularClass.ToString();
                        IReadOnlyList<Int32> messageReferenceNumbers = result.MessageReferenceNumbers;

                        for (int i = 0; i < messageReferenceNumbers.Count; i++)
                        {
                            msgStr += "\n\t\tMessageReferenceNumber[" + i.ToString() + "]: " + messageReferenceNumbers[i].ToString();
                        }
                        rootPage.NotifyUser(msgStr, NotifyType.StatusMessage);
                    }
                    else
                    {
                        msgStr = "";
                        msgStr += "ModemErrorCode: " + result.ModemErrorCode.ToString();
                        msgStr += "\nIsErrorTransient: " + result.IsErrorTransient.ToString();
                        if (result.ModemErrorCode == SmsModemErrorCode.MessagingNetworkError)
                        {                            
                            msgStr += "\n\tNetworkCauseCode: " + result.NetworkCauseCode.ToString();

                            if (result.CellularClass == CellularClass.Cdma)
                            {
                                msgStr += "\n\tTransportFailureCause: " + result.TransportFailureCause.ToString();
                            }
                            rootPage.NotifyUser(msgStr, NotifyType.ErrorMessage);
                        }
                    }
                }
                catch (Exception ex)
                {
                    rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Failed to find SMS device", NotifyType.ErrorMessage);
            }
        }
Beispiel #19
0
        public async static Task <ContactInformation> FindContactInformationFromSmsTextMessage(SmsTextMessage2 message)
        {
            ContactInformation info = new ContactInformation()
            {
                DisplayName = message.From, PhoneNumberKind = "Unknown", ThumbnailPath = ""
            };

            try
            {
                var contact = await BindPhoneNumberToGlobalContact(message.From);

                info.DisplayName = contact.DisplayName;

                try
                {
                    info.PhoneNumberKind = contact.Phones.First(x => x.Number.ToLower().Replace(" ", "") == message.From.ToLower().Replace(" ", "")).Kind.ToString();
                }
                catch
                {
                }

                StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

                StorageFile file = await storageFolder.CreateFileAsync(contact.Id + ".png", CreationCollisionOption.ReplaceExisting);

                using (var srcStream = await contact.SmallDisplayPicture.OpenReadAsync())
                    using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                        using (var reader = new DataReader(srcStream.GetInputStreamAt(0)))
                        {
                            var output = targetStream.GetOutputStreamAt(0);
                            await reader.LoadAsync((uint)srcStream.Size);

                            while (reader.UnconsumedBufferLength > 0)
                            {
                                uint dataToRead = reader.UnconsumedBufferLength > 64
                                            ? 64
                                            : reader.UnconsumedBufferLength;

                                IBuffer buffer = reader.ReadBuffer(dataToRead);
                                await output.WriteAsync(buffer);
                            }

                            await output.FlushAsync();

                            info.ThumbnailPath = file.Path;
                        }
            }
            catch
            {
            }

            return(info);
        }