示例#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();
        }
示例#2
0
        public CellularLineControl(SmsDevice2 device)
        {
            this.InitializeComponent();
            this.device = device;

            Load();
        }
示例#3
0
        private static async Task <bool> PerformMandatoryChecks()
        {
            bool available = false;

            try
            {
                var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null);

                foreach (var smsDevice in smsDevices)
                {
                    try
                    {
                        SmsDevice2 dev = SmsDevice2.FromId(smsDevice.Id);
                        switch (dev.DeviceStatus)
                        {
                        case SmsDeviceStatus.Ready:
                        {
                            return(true);
                        }
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
                available = false;
            }
            return(available);
        }
示例#4
0
        private async void HandleArguments(ToastNotificationActivatedEventArgs args)
        {
            string arguments = args.Argument;

            string action   = args.Argument.Split('&').First(x => x.ToLower(new CultureInfo("en-US")).StartsWith("action=", StringComparison.InvariantCulture)).Split('=')[1];
            string from     = args.Argument.Split('&').First(x => x.ToLower(new CultureInfo("en-US")).StartsWith("from=", StringComparison.InvariantCulture)).Split('=')[1];
            string deviceid = args.Argument.Split('&').First(x => x.ToLower(new CultureInfo("en-US")).StartsWith("deviceid=", StringComparison.InvariantCulture)).Split('=')[1];

            switch (action.ToLower(new CultureInfo("en-US")))
            {
            case "reply":
            {
                try
                {
                    string     messagetosend = (string)args.UserInput["textBox"];
                    SmsDevice2 smsDevice     = SmsDevice2.FromId(deviceid);
                    await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend);
                }
                catch
                {
                }

                break;
            }

            case "openthread":
            {
                ChatMenuItemControl selectedConvo = null;
                foreach (var convo in ViewModel.ChatConversations)
                {
                    var contact = convo.ViewModel.Contact;
                    foreach (var num in contact.Phones)
                    {
                        if (ContactUtils.ArePhoneNumbersMostLikelyTheSame(from, num.Number))
                        {
                            selectedConvo = convo;
                            break;
                        }
                    }
                    if (selectedConvo != null)
                    {
                        break;
                    }
                }
                if (selectedConvo != null)
                {
                    ViewModel.SelectedItem = selectedConvo;
                }
                break;
            }
            }
        }
示例#5
0
        private async Task HandleTaskActions(IBackgroundTaskInstance taskInstance)
        {
            try
            {
                if (taskInstance.TriggerDetails is ToastNotificationActionTriggerDetail)
                {
                    try
                    {
                        BadgeHandler.DecreaseBadgeNumber();
                    }
                    catch
                    {
                    }

                    var details = taskInstance.TriggerDetails as ToastNotificationActionTriggerDetail;

                    string arguments = details.Argument;

                    string action   = details.Argument.Split('&').First(x => x.ToLower().StartsWith("action=")).Split('=')[1];
                    string from     = details.Argument.Split('&').First(x => x.ToLower().StartsWith("from=")).Split('=')[1];
                    string deviceid = details.Argument.Split('&').First(x => x.ToLower().StartsWith("deviceid=")).Split('=')[1];

                    switch (action.ToLower())
                    {
                    case "reply":
                    {
                        try
                        {
                            string     messagetosend = (string)details.UserInput["textBox"];
                            SmsDevice2 smsDevice     = SmsDevice2.FromId(deviceid);
                            await SmsUtils.SendTextMessageAsync(smsDevice, from, messagetosend);
                        }
                        catch
                        {
                        }

                        break;
                    }

                    case "openthread":
                    {
                        break;
                    }
                    }
                }
            }
            catch
            {
            }
        }
示例#6
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);
        }
示例#7
0
        // Methods
        private static async Task <ObservableCollection <CellularLineControl> > GetSmsDevices()
        {
            ObservableCollection <CellularLineControl> collection = new ObservableCollection <CellularLineControl>();
            var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null);

            foreach (var smsDevice in smsDevices)
            {
                try
                {
                    SmsDevice2          dev     = SmsDevice2.FromId(smsDevice.Id);
                    CellularLineControl control = new CellularLineControl(dev);
                    collection.Add(control);
                }
                catch
                {
                }
            }
            return(collection);
        }
示例#8
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();
            }
        }
示例#9
0
文件: SmsService.cs 项目: Redth/f50
        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();
            }
        }
示例#10
0
        private async void btnGetDeviceInfo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selector = SmsDevice2.GetDeviceSelector();
                await new MessageDialog("before").ShowAsync();
                var devices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(selector);

                await new MessageDialog("after").ShowAsync();

                lbDevices.Items.Clear();
                foreach (var device in devices)
                {
                    lbDevices.Items.Add(device.Id);
                }
            }
            catch (Exception ex)
            {
                await new MessageDialog(ex.Message).ShowAsync();
            }
        }
示例#11
0
        private async void Load()
        {
            var smsDevices = await DeviceInformation.FindAllAsync(SmsDevice2.GetDeviceSelector(), null);

            foreach (var smsDevice in smsDevices)
            {
                try
                {
                    SmsDevice2          dev     = SmsDevice2.FromId(smsDevice.Id);
                    CellularLineControl control = new CellularLineControl(dev);
                    cellularlineControls.Add(control);
                    CellularLineComboBox.Items.Add(new ComboBoxItem()
                    {
                        Content = control
                    });
                }
                catch
                {
                }
            }
        }
        // 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
                }
            }
        }
示例#13
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");
            }
        }
示例#14
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");
            }
        }
示例#15
0
        public CellularLineControl(SmsDevice2 device)
        {
            this.InitializeComponent();
            this.device = device;

            if (device != null)
            {
                if (device.AccountPhoneNumber != null)
                {
                    LineName.Text = device.AccountPhoneNumber;
                }

                switch (device.DeviceStatus)
                {
                case SmsDeviceStatus.DeviceBlocked:
                {
                    StatusIcon.Text = "";
                    var pad = StatusIcon.Padding;
                    pad.Top            = 0;
                    StatusIcon.Padding = pad;
                    break;
                }

                case SmsDeviceStatus.DeviceFailure:
                {
                    StatusIcon.Text = "";
                    var pad = StatusIcon.Padding;
                    pad.Top            = 0;
                    StatusIcon.Padding = pad;
                    break;
                }

                case SmsDeviceStatus.DeviceLocked:
                {
                    StatusIcon.Text = "";
                    break;
                }

                case SmsDeviceStatus.Off:
                {
                    StatusIcon.Text = "";
                    var pad = StatusIcon.Padding;
                    pad.Top            = 0;
                    StatusIcon.Padding = pad;
                    break;
                }

                case SmsDeviceStatus.Ready:
                {
                    StatusIcon.Text = "";
                    var pad = StatusIcon.Padding;
                    pad.Top            = 0;
                    StatusIcon.Padding = pad;
                    break;
                }

                case SmsDeviceStatus.SimNotInserted:
                case SmsDeviceStatus.SubscriptionNotActivated:
                case SmsDeviceStatus.BadSim:
                {
                    StatusIcon.Text = "";
                    break;
                }
                }
            }
        }
示例#16
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);
        }
        // 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
                }
            }
        }
        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);
        }
示例#19
0
 public async static Task <bool> SendTextMessageAsync(SmsDevice2 device, string number, string textmessage, string transportId = "0")
 {
     return(await SendTextMessageAsync(device, new string[1] {
         number
     }, textmessage, transportId));
 }
示例#20
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);
            }
        }
 public SmsDevice2Events(SmsDevice2 This)
 {
     this.This = This;
 }
        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");
            }
        }
示例#23
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();
        }
        private async Task DisplayToast(ChatMessage message)
        {
            var information = await ContactUtils.FindContactInformationFromSender(message.From);

            string thumbnailpath = "";
            string text          = "";

            string deviceid = SmsDevice2.GetDefault().DeviceId;

            foreach (var attachment in message.Attachments)
            {
                try
                {
                    //extra += " " + attachment.MimeType;

                    if (attachment.MimeType == "application/smil")
                    {
                    }

                    if (attachment.MimeType == "text/vcard")
                    {
                        text += "Contact content in this message. ";
                    }

                    if (attachment.MimeType.StartsWith("image/"))
                    {
                        text += "Image content in this message. ";
                        var imageextension = attachment.MimeType.Split('/').Last();
                        thumbnailpath = await SaveFile(attachment.DataStreamReference, "messagepicture." + DateTimeOffset.Now.ToUnixTimeMilliseconds() + "." + imageextension);
                    }

                    if (attachment.MimeType.StartsWith("audio/"))
                    {
                        text += "Audio content in this message. ";
                        var audioextension = attachment.MimeType.Split('/').Last();
                    }
                }
                catch
                {
                    //extra += " oops";
                }
            }

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

            var toastNotif = new ToastNotification(toastContent.GetXml());

            ToastNotificationManager.CreateToastNotifier().Show(toastNotif);
        }
        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);
            }
        }
        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);
                }
            }
        }