예제 #1
0
        public bool SendSms(string phoneNumber, string message)
        {
            SmsManager smsManager = SmsManager.Default;

            try
            {
                // TODO fix this better
                try
                {
                    //UnregisterReceiver();
                }
                catch (Exception e)
                {
                    Log.Warning(e);
                }
                RegisterReceiver();
                Log.Verbose(string.Format("Sending [{0}] to: [{1}]", message, phoneNumber));
                smsManager.SendTextMessage(phoneNumber, null, message, _sentPI, _deliveredPI);
                return(true);
            }
            catch (IllegalArgumentException iae)
            {
                Log.Error(iae);
                return(false);
            }
        }
예제 #2
0
            public void SuccessfullyDeletesReadMessages()
            {
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGD=1,3\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                bool result = manager.DeleteMsg(_serialPort, "AT+CMGD=1,3");

                // Assert
                Assert.AreEqual(true, result);
            }
예제 #3
0
            public void ThrowsExceptionWhenFailingToDeleteMessages()
            {
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGD=1,3\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nERROR\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                // Assert
                Assert.That(() => manager.DeleteMsg(_serialPort, "AT+CMGD=1,3"),
                            Throws.Exception.TypeOf <ApplicationException>()
                            .With.Message.EqualTo("No success message was received."));
            }
예제 #4
0
            public void SuccessfullySendsAMessage()
            {
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGS=\"+31628870634\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "Hello World!" + (char)0x1A + "\r\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                bool result = manager.sendMsg(_serialPort, "+31628870634", "Hello World!");

                // Assert
                Assert.AreEqual(true, result);
            }
예제 #5
0
            public void ThrowsExceptionWhenFailingToSendMessage()
            {
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGS=\"+31628870634\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "Hello World!" + (char)0x1A + "\r\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nERROR\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                // Assert
                Assert.That(() => manager.sendMsg(_serialPort, "+31628870634", "Hello World!"),
                            Throws.Exception.TypeOf <ApplicationException>()
                            .With.Message.EqualTo("No success message was received."));
            }
예제 #6
0
            public void SuccessfullyCountsMessages()
            {
                // READ THIS: http://tech.findmypast.com/dont-mock-what-you-dont-own/
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CPMS?\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("+CPMS: \"SM\",4,20,\"SM\",0,20,\"ME\",186,1000\r\n\r\nOK\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                int count = manager.CountSMSmessages(_serialPort);

                // Assert
                Assert.AreEqual(4, count);
                // Note that CountSMSmessages() ignores messages not stored on SIM card.
            }
예제 #7
0
            public void ThrowsExceptionWhenFailingToSelectMessageStorage()
            {
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CSCS=\"PCCP437\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CPMS=\"SM\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nERROR\r\n");
                    manager._receiveNow.Set();
                });

                // Act
                // Assert
                Assert.That(() => manager.ReadSMS(_serialPort, "AT+CMGL=\"ALL\""),
                            Throws.Exception.TypeOf <ApplicationException>()
                            .With.Message.EqualTo("No success message was received."));
            }
예제 #8
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            var sendSMSButton       = FindViewById <Button>(Resource.Id.MyButton);
            var phoneNumberEditText = FindViewById <EditText>(Resource.Id.editText1);
            var messageEditText     = FindViewById <EditText>(Resource.Id.editText2);

            _smsManager = SmsManager.Default;

            sendSMSButton.Click += (s, e) =>
            {
                var phone   = phoneNumberEditText.Text;
                var message = messageEditText.Text;

                if (!PhoneNumberUtils.IsWellFormedSmsAddress(phone) || PhoneNumberUtils.IsEmergencyNumber(phone))
                {
                    return;
                }

                var piSent      = PendingIntent.GetBroadcast(this, 0, new Intent("SMS_SENT"), 0);
                var piDelivered = PendingIntent.GetBroadcast(this, 0, new Intent("SMS_DELIVERED"), 0);

                _smsManager.SendTextMessage(phone, null, message, piSent, piDelivered);
            };
        }
예제 #9
0
        public async Task <OTPSendResponse> SendCodeAsync(OTPSendRequest request)
        {
            SmsData smsData = new SmsData()
            {
                MessageBody     = string.Format("کد فعال سازی روزانه: {0}", (object)request.Code),
                MobileNo        = request.UserMobile,
                EntityID        = request.UserId.ToString(),
                EntityName      = "OTPSendRequest",
                RecieverID      = new int?(request.UserId),
                SmsReceiverType = SmsReceiverType.User
            };
            SmsResponse response = await SmsManager.SendSmsAsync(smsData);

            if (response.Status == SmsResponseStatus.Failed)
            {
                return new OTPSendResponse()
                       {
                           Status = OTPSendStatus.Failed
                       }
            }
            ;
            return(new OTPSendResponse()
            {
                Status = OTPSendStatus.Succeed
            });
        }
예제 #10
0
        public async Task <AjaxResponse> AuthPhoneCode(SmsCheckModel model)
        {
            SmsManager smsManager = new SmsManager(model.PhoneNumber, _userVerifyAppService);
            var        result     = await smsManager.AuthPhoneCode(model.AuthCode);

            return(new AjaxResponse(result));
        }
예제 #11
0
        protected override Dialog OnCreateDialog(int id)
        {
            base.OnCreateDialog(id);
            Dialog d = new Dialog(this);

            d.SetTitle("Datos de cliente");
            d.SetContentView(Resource.Layout.UserInfoDialog);
            d.OwnerActivity = this;
            d.SetCanceledOnTouchOutside(true);
            var bt_aceptar = d.FindViewById <Button> (Resource.Id.dialog_bt_aceptar);

            bt_aceptar.Click += (object sender, EventArgs e) => {
                var tb_clienteName = d.FindViewById <EditText> (Resource.Id.dialog_tb_clientName);
                var rg             = d.FindViewById <RadioGroup> (Resource.Id.dialog_rg_tipCliente);
                var rb_checked     = d.FindViewById <RadioButton> (rg.CheckedRadioButtonId);
                if (tb_clienteName.Text != "")
                {
                    SmsManager sms_mngr = SmsManager.Default;
                    prefmodel.Client_Name = tb_clienteName.Text;
                    prefmodel.Client_Type = rb_checked.Text;
                    string request = prefmodel.GetInfoForRequest(this, true);
                    tb_serial_number.Text = request;
                    //sms_mngr.SendTextMessage (OWNER_CONTACT_NUMBER, null, GetInfoForRequest(), null, null);
                    d.Dismiss();
                }
            };
            return(d);
        }
예제 #12
0
        void SendSMS(string number, string message)
        {
            List <PendingIntent> sentPendingIntents      = new List <PendingIntent>();
            List <PendingIntent> deliveredPendingIntents = new List <PendingIntent>();
            PendingIntent        sentPI = PendingIntent.GetBroadcast(BaseContext, 0,
                                                                     new Intent(BaseContext, typeof(SmsSentReceiver)), 0);
            PendingIntent deliveredPI = PendingIntent.GetBroadcast(BaseContext, 0,
                                                                   new Intent(BaseContext, typeof(SmsDeliveredReceiver)), 0);

            try
            {
                SmsManager    sms         = SmsManager.Default;
                List <string> mSMSMessage = sms.DivideMessage(message).ToList();
                for (int i = 0; i < mSMSMessage.Count; i++)
                {
                    sentPendingIntents.Add(sentPI);
                    deliveredPendingIntents.Add(deliveredPI);
                }
                sms.SendMultipartTextMessage(number, null, mSMSMessage,
                                             sentPendingIntents, deliveredPendingIntents);
            }
            catch (Exception e)
            {
                Toast.MakeText(BaseContext, "SMS sending failed... I don't get a f**k why, I'm just an application. Contact the developer.", ToastLength.Short).Show();
            }
        }
예제 #13
0
 public AccountController(AccountManager accountManager, IJwtIssuer jwtIssuer, SmsManager smsManager, TotpManager totpManager)
 {
     _accountManager = accountManager ?? throw new ArgumentNullException(nameof(accountManager));
     _jwtIssuer      = jwtIssuer ?? throw new ArgumentNullException(nameof(jwtIssuer));
     _smsManager     = smsManager;
     _totpManager    = totpManager;
 }
예제 #14
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            _vcManager = VcManager.GetInstance();
            if (Page.IsPostBack)
            {
                return;
            }

            if (!FileConfigManager.Instance.IsFindPassword)
            {
                PageUtils.RedirectToErrorPage("基于安全考虑,找回密码功能已关闭,如需使用请与管理员联系!");
            }
            else if (!SmsManager.IsSmsReady())
            {
                PageUtils.RedirectToErrorPage("短信发送未开启或配置不正确,找回密码功能无法使用,如需使用请与管理员联系!");
            }

            if (FileConfigManager.Instance.IsValidateCode)
            {
                LtlValidateCodeImage.Text =
                    $@"<img id=""imgVerify"" name=""imgVerify"" src=""{PageValidateCode.GetRedirectUrl(_vcManager.GetCookieName())}"" align=""absmiddle"" />";
            }
            else
            {
                PhValidateCode.Visible = false;
            }

            this.LtlPageTitle.Text = "找回密码";
        }
        [Create(@"{code}", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            try
            {
                SmsManager.ValidateSmsCode(user, code);

                var token = SecurityContext.AuthenticateMe(user.ID);

                MessageService.Send(Request, MessageAction.LoginSuccessViaApiSms);

                var tenant  = CoreContext.TenantManager.GetCurrentTenant().TenantId;
                var expires = TenantCookieSettings.GetExpiresTime(tenant);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(expires),
                    Sms = true,
                    PhoneNoise = SmsSender.BuildPhoneNoise(user.MobilePhone)
                });
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailViaApiSms, MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
            finally
            {
                SecurityContext.Logout();
            }
        }
        [Create(@"{code}", false)] //NOTE: this method doesn't requires auth!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string code)
        {
            var user = GetUser(userName, password);

            SmsManager.ValidateSmsCode(user, code);

            try
            {
                var token = SecurityContext.AuthenticateMe(user.ID);

                if (string.IsNullOrEmpty(token))
                {
                    throw new AuthenticationException("User authentication failed");
                }

                MessageService.Send(_context, MessageAction.LoginSuccessViaApiSms);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(DateTime.UtcNow.AddYears(1)),
                    Sms = true,
                    PhoneNoise = SmsManager.BuildPhoneNoise(user.MobilePhone)
                });
            }
            catch
            {
                MessageService.Send(_context, userName, MessageAction.LoginFailViaApi);
                throw;
            }
        }
        [Create(@"{code}", false, false)] //NOTE: this method doesn't requires auth!!!  //NOTE: this method doesn't check payment!!!
        public AuthenticationTokenData AuthenticateMe(string userName, string password, string provider, string accessToken, string code)
        {
            bool viaEmail;
            var  user = GetUser(userName, password, provider, accessToken, out viaEmail);

            try
            {
                SmsManager.ValidateSmsCode(user, code);

                var token = SecurityContext.AuthenticateMe(user.ID);

                MessageService.Send(Request, MessageAction.LoginSuccessViaApiSms);

                return(new AuthenticationTokenData
                {
                    Token = token,
                    Expires = new ApiDateTime(DateTime.UtcNow.AddYears(1)),
                    Sms = true,
                    PhoneNoise = SmsManager.BuildPhoneNoise(user.MobilePhone)
                });
            }
            catch
            {
                MessageService.Send(Request, user.DisplayUserName(false), MessageAction.LoginFailViaApiSms, MessageTarget.Create(user.ID));
                throw new AuthenticationException("User authentication failed");
            }
        }
예제 #18
0
파일: PageFindPwd.cs 프로젝트: zr53722/cms
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            _vcManager = VcManager.GetInstance();
            if (Page.IsPostBack)
            {
                return;
            }

            if (!ConfigManager.SystemConfigInfo.IsAdminFindPassword)
            {
                PageUtils.RedirectToErrorPage("基于安全考虑,找回密码功能已关闭,如需使用请与管理员联系!");
            }
            else if (!SmsManager.IsReady() || string.IsNullOrEmpty(ConfigManager.SystemConfigInfo.AdminFindPasswordSmsTplId))
            {
                PageUtils.RedirectToErrorPage("短信验证码发送功能未开启或配置不正确,找回密码功能无法使用,如需使用请与管理员联系!");
            }

            LtlValidateCodeImage.Text =
                $@"<img id=""imgVerify"" name=""imgVerify"" src=""{PageValidateCode.GetRedirectUrl(_vcManager.GetCookieName())}"" align=""absmiddle"" />";

            LtlPageTitle.Text = "找回密码";
        }
예제 #19
0
파일: SMSReciver.cs 프로젝트: kuganrajh/LMS
        public override async void OnReceive(Context context, Intent intent)
        {
            if (intent.Action.Equals(Telephony.Sms.Intents.SmsReceivedAction))
            {
                var msgs = Telephony.Sms.Intents.GetMessagesFromIntent(intent);
                foreach (var msg in msgs)
                {
                    string result = await _sMSRManager.GetData(msg.OriginatingAddress, msg.MessageBody);

                    SmsManager sm = SmsManager.Default;
                    if (result.Length >= 150)
                    {
                        List <string> parts = new List <string>();
                        //split the string into chunks of 20 chars.
                        var enumerable = Enumerable.Range(0, result.Length / 149).Select(i => result.Substring(i * 149, 149));
                        parts = enumerable.ToList();
                        int banace = result.Length % 149;
                        parts.Add(result.Substring(parts.Count * 149, banace));
                        sm.SendMultipartTextMessage(msg.OriginatingAddress, null, parts, null, null);
                    }
                    else
                    {
                        sm.SendTextMessage(msg.OriginatingAddress, null, result, null, null);
                    }
                    //SmsManager.Default.SendTextMessage(msg.OriginatingAddress, null, result, null, null);
                }
            }

            Toast.MakeText(context, "Received intent!", ToastLength.Short).Show();
        }
예제 #20
0
        private void execute(Context context, string numberDest, int idLstRep = 0)
        {
            desactiveSon = true;

            AudioManager aM = (AudioManager)context.GetSystemService(Context.AudioService);

            if (aM.RingerMode != RingerMode.Silent)
            {
                aM.RingerMode = RingerMode.Silent;
            }
            else
            {
                desactiveSon = false;
            }

            string     reponse = Global.Instance.GetElement(idLstRep).MessageText;
            SmsManager sms     = SmsManager.Default;

            if (reponse.Length > MAX_SMS_MESSAGE_LENGTH)
            {
                var messagelist = sms.DivideMessage(reponse);
                sms.SendMultipartTextMessage(numberDest, null, messagelist, null, null);
            }
            else
            {
                sms.SendTextMessage(numberDest, null, reponse, null, null);
            }

            Sleep(aM, context);
        }
예제 #21
0
        public void OnClick(View v)
        {
            switch (v.Id)
            {
            case Resource.Id.sms:
                if (!(userNum.Text.ToString().Equals("")) && !(userMsg.Text.ToString().Equals("")))
                {
                    no = userNum.Text.ToString();
                    string     userMessage = userMsg.Text.ToString();
                    SmsManager smManager   = SmsManager.Default;
                    smManager.SendTextMessage(no, null, userMessage, null, null);
                }
                else
                {
                    Toast.MakeText(this, "Empty Fields", ToastLength.Short).Show();
                }
                break;

            case Resource.Id.call:
                if (!userNum.Text.ToString().Equals(""))
                {
                    no = userNum.Text.ToString();
                    Intent callIntent = new Intent(Intent.ActionCall);
                    callIntent.SetData(Android.Net.Uri.Parse("tel:" + no));
                    StartActivity(callIntent);
                }
                break;
            }
        }
        public bool SendMessage(long threadId, string message, string phoneAddr)
        {
            try
            {
                if (!string.IsNullOrEmpty(phoneAddr))
                {
                    SmsManager    sm    = SmsManager.Default;
                    List <string> parts = new List <string>(4);

                    if (message.Length <= 160)
                    {
                        parts.Add(message);
                    }
                    else
                    {
                        parts = BreakMessageIntoParts(message, 140);
                    }

                    sm.SendMultipartTextMessage(phoneAddr, null, parts, null, null);
                }
            }
            catch (Exception ex)
            {
                MobileGlobals.AddNewException(ex);
                MobileGlobals.WriteExceptionLog();

                return(false);
            }

            return(true);
        }
예제 #23
0
        /// <summary>
        /// Sends messages to the users who are not blocked.
        /// </summary>
        /// <remarks>It manipulates the user requests whether it is resending activation code request or not, block or unblock the user based on maximum allowed request in 24 hrs and then sends sms to the users who are not blocked.</remarks>
        /// <param name="phoneNumber">A string containing the user's phone number.</param>
        /// <param name="devicePlatform">An enum specifying the device platform.</param>
        /// <param name="activationCode">A string containing activation code to be sent.</param>
        /// <param name="isResend">A bool if true specifying that the request is for resending activation code; otherwise false.</param>
        /// <param name="isRegenerated">A bool if true specifying that the request is for sending regenerated activation code; otherwise false.</param>
        /// <returns>An integer if 0 = sms has not been sent, -1 = sms has been successfully sent or number of remaining minutes to unblock user = user is blocked based on blocking policy. </returns>
        public static int SendActivationCodeToUnBlockedUser(string phoneNumber, DevicePlatform devicePlatform, string activationCode, bool isResend, bool isRegenerated)
        {
            int smsSendingResult = (int)SmsSendingStatus.SendingFailed;

            if (devicePlatform == DevicePlatform.iOS || devicePlatform == DevicePlatform.Android)
            {
                if (isResend == true)
                {
                    SmsManager.SendSms(phoneNumber, activationCode, isRegenerated);
                    smsSendingResult = (int)SmsSendingStatus.Sent;
                    return(smsSendingResult);
                }
                else
                {
                    DbManager dbManager = new DbManager();
                    if (dbManager.StartTransaction())
                    {
                        try
                        {
                            int userBlockedState = dbManager.GetUserBlockedState(phoneNumber);
                            switch ((UserState)userBlockedState)
                            {
                            case UserState.NotBlocked:
                                SmsManager.SendSms(phoneNumber, activationCode, isRegenerated);
                                smsSendingResult = (int)SmsSendingStatus.Sent;
                                break;

                            default:
                                smsSendingResult = userBlockedState;
                                break;
                            }

                            dbManager.CommitTransaction();
                            return(smsSendingResult);
                        }
                        catch (ApplicationException appExp)
                        {
                            dbManager.RollbackTransaction();
                            throw;
                        }
                        catch (Exception exp)
                        {
                            dbManager.RollbackTransaction();
                            LogManager.CurrentInstance.ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, exp.Message, exp);
                            throw new ApplicationException(CustomHttpStatusCode.UnknownError.ToString("D"));
                        }
                    }
                    else
                    {
                        throw new ApplicationException(CustomHttpStatusCode.TransactionFailure.ToString("D"));
                        return(smsSendingResult);
                    }
                }
            }
            else
            {
                // handling for secondary devices.
                return(smsSendingResult);
            }
        }
        public static void SendSMS(SMSModel SMS)
        {
            try
            {
                if (SMS != null)
                {
                    Console.WriteLine("Sending sms to phone number: " + SMS.PhoneNumber);
                    _smsManager = SmsManager.Default;

                    string SmsId = SMS.Id.ToString();
                    if (SentIntent.Extras != null)
                    {
                        SentIntent.Extras.Clear();
                    }

                    SentIntent.PutExtra("SMSGatewayId", SmsId);
                    SentIntent.PutExtra("Message", SMS.Message);
                    SentIntent.PutExtra("PhoneNumber", SMS.PhoneNumber);

                    var piSent      = PendingIntent.GetBroadcast(Application.Context, SMS.Id, SentIntent, 0);
                    var piDelivered = PendingIntent.GetBroadcast(Application.Context, 0, new Intent("SMS_DELIVERED"), 0);

                    SMS.Status = "Mengirim";
                    UpdateSMS(SMS);

                    _smsManager.SendTextMessage(SMS.PhoneNumber, null, SMS.Message, piSent, piDelivered);
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message + Ex.StackTrace);
            }
        }
예제 #25
0
        public IHttpActionResult Main()
        {
            var body    = new RequestBody();
            var account = body.GetPostString("account");
            var mobile  = BaiRongDataProvider.UserDao.GetMobileByAccount(account);

            var    isSuccess = false;
            string errorMessage;

            if (string.IsNullOrEmpty(mobile) || !StringUtils.IsMobile(mobile))
            {
                errorMessage = "账号对应的用户未设置手机号码";
            }
            else
            {
                var code = StringUtils.GetRandomInt(1111, 9999);
                DbCacheManager.RemoveAndInsert($"SiteServer.API.Controllers.Users.SendSms.{mobile}.Code", code.ToString());
                isSuccess = SmsManager.SendVerify(mobile, code, ConfigManager.UserConfigInfo.FindPasswordSmsTplId, out errorMessage);
            }

            return(Ok(new
            {
                IsSuccess = isSuccess,
                Mobile = mobile,
                ErrorMessage = errorMessage
            }));
        }
        public IHttpActionResult Main()
        {
            var body     = new RequestBody();
            var mobile   = body.GetPostString("mobile");
            var password = body.GetPostString("password");

            var isSms        = false;
            var isRegister   = false;
            var errorMessage = string.Empty;

            if (ConfigManager.UserConfigInfo.RegisterVerifyType == EUserVerifyType.Mobile)
            {
                var code = StringUtils.GetRandomInt(1111, 9999);
                DbCacheManager.RemoveAndInsert($"SiteServer.API.Controllers.Users.SendSms.{mobile}.Code", code.ToString());
                isSms = SmsManager.SendVerify(mobile, code, ConfigManager.UserConfigInfo.RegisterSmsTplId, out errorMessage);
            }

            if (!isSms)
            {
                var userInfo = new UserInfo
                {
                    UserName = mobile,
                    Mobile   = mobile,
                    Password = password
                };
                isRegister = BaiRongDataProvider.UserDao.Insert(userInfo, PageUtils.GetIpAddress(), out errorMessage);
            }

            return(Ok(new {
                IsSms = isSms,
                IsRegister = isRegister,
                ErrorMessage = errorMessage
            }));
        }
예제 #27
0
        public async Task SendOtp(string mobileNumber)
        {
            int otp = 123456;
            //int otp = new Random().Next(100000, 999999); // random OTP

            SharedCollectionDocument <UserAuthModel> userAuthDocument = await DbService.GetDocumentByKeyAsyc <UserAuthModel>(mobileNumber, SecurityAppSettings.ServiceSettings.DocumentTypes.UserAuth);

            if (userAuthDocument == null)
            {
                UserAuthModel user = new UserAuthModel()
                {
                    UserName     = mobileNumber,
                    PasswordHash = PasswordService.DefaultPassword,
                    Otp          = otp,
                    RefreshToken = TokenService.GenerateRefreshToken(),
                };

                SharedCollectionDocument <UserAuthModel> document = await DbService.CreateDocumentAsync(user.UserName, user, SecurityAppSettings.ServiceSettings.DocumentTypes.UserAuth);
            }
            else
            {
                userAuthDocument.Model.Otp = otp;
                await DbService.ReplaceDocumentAsync(userAuthDocument);
            }

            string appHash = CacheService.AndroidSignatureHash;
            string message = String.Format(SmsManager.OtpTemplate, otp, appHash);

            SmsManager.SendSms(mobileNumber, message);
        }
예제 #28
0
        private void AddUser(ClaimsPrincipal claimsPrincipal, UserInfo userInfo)
        {
            try
            {
                _log.DebugFormat("Adding or updating user in database, userId={0}", userInfo.ID);
                if (string.IsNullOrWhiteSpace(userInfo.FirstName))
                {
                    userInfo.FirstName = Resource.FirstName;
                }
                if (string.IsNullOrWhiteSpace(userInfo.LastName))
                {
                    userInfo.LastName = Resource.LastName;
                }
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                if (!string.IsNullOrEmpty(userInfo.MobilePhone))
                {
                    userInfo.MobilePhone = SmsManager.GetPhoneValueDigits(userInfo.MobilePhone);
                }
                Claim  roleClaim = claimsPrincipal.FindFirst(ClaimTypes.Role);
                string role      = roleClaim != null ? roleClaim.Value : string.Empty;
                if (SupportedRoles.IsSupported(role) && role != string.Empty)
                {
                    _log.ErrorFormat("Unknown user role: {0}", role);
                }
                if (string.IsNullOrEmpty(userInfo.UserName))
                {
                    userInfo.ID = Guid.NewGuid();
                    if (role == SupportedRoles.Guest || TenantStatisticsProvider.GetUsersCount() >= TenantExtra.GetTenantQuota().ActiveUsers)
                    {
                        userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false, true);
                    }
                    else
                    {
                        userInfo = UserManagerWrapper.AddUser(userInfo, UserManagerWrapper.GeneratePassword(), true, false);
                    }
                    if (role == SupportedRoles.Admin && !CoreContext.UserManager.IsUserInGroup(userInfo.ID, Constants.GroupAdmin.ID))
                    {
                        CoreContext.UserManager.AddUserIntoGroup(userInfo.ID, Constants.GroupAdmin.ID);
                    }
                }
                else
                {
                    CoreContext.UserManager.SaveUserInfo(userInfo);
                }
                Claim photoUrlClaim = claimsPrincipal.FindFirst(SupportedClaimTypes.RemotePhotoUrl);
                if (photoUrlClaim != null && !string.IsNullOrEmpty(photoUrlClaim.Value))
                {
                    var photoLoader = new UserPhotoLoader();
                    photoLoader.SaveOrUpdatePhoto(photoUrlClaim.Value, userInfo.ID);
                }
            }
            finally
            {
                SecurityContext.Logout();
            }
            var cookiesKey = SecurityContext.AuthenticateMe(userInfo.ID);

            CookiesManager.SetCookies(CookiesType.AuthKey, cookiesKey);
        }
예제 #29
0
        public object ValidateSmsCode(string code)
        {
            var user = GetUser();

            SmsManager.ValidateSmsCode(user, code);

            return(new { RefererURL = GetRefererURL() });
        }
예제 #30
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _smsManager = SmsManager.Default;

            // Set our view from the "main" layout resource
            // SetContentView (Resource.Layout.Main);
        }