Example #1
0
        public override SMSResult AddIgnoreList()
        {
            SMSResult resp = new SMSResult();

            try
            {
                string postdata = "action=addIgnoreCard&uid=" + user + "&token=" + token
                                + "&mobile=" + mobilenum + "&pid=" + projID;
                string html = getHTML(url, postdata);
                if (checkMsg(ref html) == true)
                {
                    resp.Status = true;
                    resp.Result = html;
                }
                else
                {
                    resp.Status = false;
                    resp.Result = html;
                }

            }
            catch (Exception e)
            {
                resp.Status = false;
            }
            return resp;
        }
Example #2
0
        public void SendOneSMS_UseProxy()
        {
            string proxyHost = "";
            int    proxyPort = 0;

            proxyHost = System.Configuration.ConfigurationManager.AppSettings["ProxyHost"];
            if (String.IsNullOrWhiteSpace(proxyHost))
            {
                Assert.Inconclusive("Proxy host not configured - Skipping test");
            }

            string proxyPortTemp = System.Configuration.ConfigurationManager.AppSettings["ProxyPort"];

            if (String.IsNullOrWhiteSpace(proxyPortTemp))
            {
                Assert.Inconclusive("Proxy port not configured - Skipping test");
            }

            if (!int.TryParse(proxyPortTemp, out proxyPort))
            {
                Assert.Inconclusive("Proxy port could not be parsed - Skipping test");
            }

            Clockwork.API api = new API(key);

            api.Proxy = new System.Net.WebProxy(proxyHost, proxyPort);

            SMSResult result = api.Send(new SMS {
                To = "44123457890", Message = "Hello World"
            });

            Assert.IsTrue(result.Success);
        }
Example #3
0
        public override SMSResult AddIgnoreList()
        {
            SMSResult resp = new SMSResult();
            String result = "";

            try
            {
                result = send.HttpPost(url,
                        "action=addIgnoreList&uid=" + user + "&token=" + token
                                + "&mobiles=" + mobilenum + "&pid=" + projID);
                if (isNumber(result))
                {
                    resp.Status = true;
                    resp.Result = result;

                }
                else
                {
                    resp.Status = false;
                    resp.Result = result;
                }

            }
            catch (Exception e)
            {
                resp.Status = false;
            }
            return resp;
        }
Example #4
0
        public override SMSResult AddIgnoreList()
        {
            SMSResult resp = new SMSResult();
            resp.Status = true;
            String result = "";

            try
            {
                string postdata = "Api/userAddBlack?token=" + token + "&phoneList="+projID+"-"+mobilenum;
                string html = getHTML(url, postdata);
                resp.Status = true;
            //                 if (isNumber(result))
            //                 {
            //                     resp.Status = true;
            //                     resp.Result = result;
            //
            //                 }
            //                 else
            //                 {
            //                     resp.Status = false;
            //                     resp.Result = result;
            //                 }

            }
            catch (Exception e)
            {
                resp.Status = false;
            }
            return resp;
        }
Example #5
0
        /// <summary>
        /// 发送邮件验证码
        /// </summary>
        /// <param name="para"></param>
        /// <returns></returns>
        public SMSResult SubmitEmail(SMSApiPara para)
        {
            var result = new SMSResult {
                Code = 0, Message = LanguageUtil.Translate("api_Business_SMS_SubmitEmail_Message")
            };
            var flag      = false;
            var emailType = EmailEnum.Register;

            if (para.ClientBusinessType == BusinessType.BindingPhone)
            {
                emailType = EmailEnum.UpdateEmail;
            }
            else if (para.ClientBusinessType == BusinessType.PwdRecover)
            {
                emailType = EmailEnum.FindPwd;
            }
            EmailHelper.SendEmailHtml(emailType, para.PhoneNumber, new Dictionary <string, string> {
                { "@code@", para.Code }, { "@imageUrl@", @"http://www.5bvv.com/Content/images/icon_img/5BVV_logo_03.png" }
            }, r =>
                                      { flag = r; });
            if (flag)
            {
                result.Code    = 1;
                result.Message = LanguageUtil.Translate("api_Business_SMS_SubmitEmail_resultMessage");
            }
            return(result);
        }
Example #6
0
        public static string GetDescription(SMSResult result)
        {
            DescriptionAttribute attribute = result.GetType()
                                             .GetField(result.ToString())
                                             .GetCustomAttributes(typeof(DescriptionAttribute), false)
                                             .SingleOrDefault() as DescriptionAttribute;

            return(attribute == null?result.ToString() : attribute.Description);
        }
Example #7
0
        public void SendOneSMS_Single()
        {
            Clockwork.API api    = new API(key);
            SMSResult     result = api.Send(new SMS {
                To = "441234567890", Message = "Hello World"
            });

            Assert.IsTrue(result.Success);
        }
Example #8
0
        static void Main(string[] args)
        {
            if (args[1].StartsWith("0") && !args[1].StartsWith("00"))
            {
                args[1] = args[3] + args[1].Substring(1);                                                       // 01 == 491
            }
            else if (args[1].StartsWith("00"))
            {
                args[1] = args[1].Substring(2);                                //0049 => 49
            }
            try

            {
                Clockwork.API api    = new API(args[0]);
                SMSResult     result = api.Send(
                    new SMS
                {
                    To      = args[1],
                    Message = args[2]
                });

                if (result.Success)
                {
                    Console.WriteLine("SMS Sent to {0}, Clockwork ID: {1}",
                                      result.SMS.To, result.ID);
                }
                else
                {
                    Console.WriteLine("SMS to {0} failed, Clockwork Error: {1} {2}",
                                      result.SMS.To, result.ErrorCode, result.ErrorMessage);
                }
            }
            catch (APIException ex)
            {
                // You’ll get an API exception for errors
                // such as wrong username or password
                Console.WriteLine("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn’t reach the Clockwork server
                Console.WriteLine("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                Console.WriteLine("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                Console.WriteLine("Unknown Exception: " + ex.Message);
            }
        }
Example #9
0
        public void SendOneSMS_InvalidNumber()
        {
            Clockwork.API api    = new API(key);
            SMSResult     result = api.Send(new SMS {
                To = "not_a_number", Message = "Hello World"
            });

            Assert.IsNotNull(result);
            Assert.IsFalse(result.Success);
            Assert.AreEqual(10, result.ErrorCode);
        }
        private void Send(string userName, string userPhoneNumber, string messageContent)
        {
            try
            {
                var api = new API(APIKey);

                SMSResult result = api.Send(
                    new SMS
                {
                    To      = userPhoneNumber,
                    Message = $"Hello {userName}, {messageContent}",
                    From    = "447860033104"
                });;

                if (result.Success)
                {
                    Console.WriteLine("SMS Sent to {0}, Clockwork ID: {1}",
                                      result.SMS.To, result.ID);
                }
                else
                {
                    Console.WriteLine("SMS to {0} failed, Clockwork Error: {1} {2}",
                                      result.SMS.To, result.ErrorCode, result.ErrorMessage);
                }
            }
            catch (APIException ex)
            {
                // You’ll get an API exception for errors
                // such as wrong username or password
                Console.WriteLine("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn’t reach the Clockwork server
                Console.WriteLine("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                Console.WriteLine("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                Console.WriteLine("Unknown Exception: " + ex.Message);
            }
        }
Example #11
0
        public ActionResult SendMessage(MessageToSend msg)
        {
            try
            {
                if (msg.to != null && msg.body != null)
                {
                    Clockwork.API api    = new API(apiKey);
                    SMSResult     result = api.Send(new Clockwork.SMS {
                        To = msg.to, Message = "Hello World"
                    });

                    if (result.Success)
                    {
                        ViewBag.result = result;
                        return(View());
                        //Console.WriteLine("SMS Sent to {0}, Clockwork ID: {1}", result.SMS.To, result.ID);
                    }
                    else
                    {
                        Console.WriteLine("SMS to {0} failed, Clockwork Error: {1} {2}", result.SMS.To, result.ErrorCode, result.ErrorMessage);
                    }
                }
            }
            catch (APIException ex)
            {
                // You'll get an API exception for errors
                // such as wrong username or password
                Console.WriteLine("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn't reach the Clockwork server
                Console.WriteLine("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                Console.WriteLine("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                Console.WriteLine("Unknown Exception: " + ex.Message);
            }
            return(View("/"));
        }
Example #12
0
        private void sendMessage_Click(object sender, EventArgs e)
        {
            try
            {
                API api = new API(key.Text);

                SMS sms = new SMS
                {
                    To      = to.Text,
                    Message = message.Text
                };

                SMSResult result = api.Send(sms);

                if (result.Success)
                {
                    MessageBox.Show("Sent\nID: " + result.ID);
                }
                else
                {
                    MessageBox.Show("Error: " + result.ErrorMessage);
                }
            }
            catch (APIException ex)
            {
                // You'll get an API exception for errors
                // such as wrong key
                MessageBox.Show("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn't reach the mediaburst server
                MessageBox.Show("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                MessageBox.Show("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                MessageBox.Show("Unknown Exception: " + ex.Message);
            }
        }
Example #13
0
 public override SMSResult resultByContent(JObject obj)
 {
     if (obj == null)
     {
         return(null);
     }
     try
     {
         var result = new SMSResult();
         result.sid          = obj["sid"].ToString();
         result.ReceivedTime = obj["user_receive_time"].ToString();
         try
         {
             result.uid = obj["uid"].ToString();
         }
         catch { }
         try
         {
             result.mobile = obj["mobile"].ToString();
         }
         catch { }
         try
         {
             result.carrier_code = obj["error_msg"].ToString();
         }
         catch { }
         try
         {
             result.carrier_msg = obj["error_detail"].ToString();
         }
         catch { }
         try
         {
             result.status = obj["report_status"].ToString();
         }
         catch { }
         try
         {
             result.duration = Convert.ToInt32(obj["duration"]);
         }
         catch { }
         return(result);
     }
     catch { }
     return(null);
 }
Example #14
0
        public override SMSResult AddIgnoreList()
        {
            SMSResult result = new SMSResult();

            string postdata = "action=addIgnoreList&mobiles=" + mobilenum + "&token=" + token + "&uid=" + user+"&pid="+projID;
            string html = getHTML(url, postdata);
            if (checkMsg(ref html) == true)
            {
                result.Status = true;
                result.Result = html;
            }
            else
            {
                result.Status = false;
                result.Result = html;
            }
            return result;
        }
Example #15
0
        static void Main(string[] args)
        {
            try
            {
                Clockwork.API api    = new API("b355d5aca9b7a751f3aa85sfs25371022c9d10779f9a9");
                SMSResult     result = api.Send(
                    new SMS
                {
                    To      = "923332279662",
                    Message = "Hello World"
                });

                if (result.Success)
                {
                    Console.WriteLine("SMS Sent to { 0}, Clockwork ID: { 1}", result.SMS.To, result.ID);
                }
                else
                {
                    Console.WriteLine("SMS to { 0} failed, Clockwork Error: { 1}{ 2}", result.SMS.To, result.ErrorCode, result.ErrorMessage);
                }
            }
            catch (APIException ex)
            {
                // You’ll get an API exception for errors
                // such as wrong username or password
                Console.WriteLine("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn’t reach the Clockwork server
                Console.WriteLine("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                Console.WriteLine("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                Console.WriteLine("Unknown Exception: " + ex.Message);
            }
        }
Example #16
0
        public async Task <SMSResult> SendAsync(IEnumerable <string> toPhoneNumbers, string content)
        {
            if (toPhoneNumbers == null ||
                !toPhoneNumbers.Any() ||
                toPhoneNumbers.Any(it => string.IsNullOrWhiteSpace(it)))
            {
                return(SMSResult.Failure("ToPhoneNumbers is required."));
            }

            if (string.IsNullOrEmpty(content))
            {
                return(SMSResult.Failure("Content is required."));
            }

            try
            {
                _httpClient.DefaultRequestHeaders.Add("ContentType", Encoding.UTF8.HeaderName);

                var stringContent = TranslateToStringContent(toPhoneNumbers, content);

                var response = await _httpClient.PostAsync(_baseUrl + "norsubmit", stringContent);

                var responseString = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(SMSResult.Failure($"SMS sending request failed. ResponseStatus: [{response.StatusCode}], Content: [{responseString}]"));
                }

                var notificationSubmitResponse = JsonConvert.DeserializeObject <NotificationSubmitResponse>(responseString);
                if (!notificationSubmitResponse.Success)
                {
                    return(SMSResult.Failure($"SMS sending failed. ResponseCode: [{notificationSubmitResponse.Rspcod}]"));
                }

                return(SMSResult.Success());
            }
            catch (Exception ex)
            {
                return(SMSResult.Failure($"Exception occur: {JsonConvert.SerializeObject(ex)}"));
            }
        }
Example #17
0
        public void Send(string number, string body)
        {
            try
            {
                Clockwork.API api    = new API("e26d24050e1147c7f8a57bdeeb574581dd5ca5f1");
                SMSResult     result = api.Send(
                    new SMS
                {
                    To      = number,
                    Message = body
                });

                if (!result.Success)
                {
                    throw new Exception(result.ErrorMessage);
                }
            }
            catch (APIException ex)
            {
                // You’ll get an API exception for errors
                // such as wrong username or password
                Console.WriteLine("API Exception: " + ex.Message);
            }
            catch (WebException ex)
            {
                // Web exceptions mean you couldn’t reach the Clockwork server
                Console.WriteLine("Web Exception: " + ex.Message);
            }
            catch (ArgumentException ex)
            {
                // Argument exceptions are thrown for missing parameters,
                // such as forgetting to set the username
                Console.WriteLine("Argument Exception: " + ex.Message);
            }
            catch (Exception ex)
            {
                // Something else went wrong, the error message should help
                Console.WriteLine("Unknown Exception: " + ex.Message);
            }
        }
Example #18
0
        public string Send()
        {
            try
            {
                Clockwork.API api    = new API("d09befc38459ecb67e7096a78767ee0de581bb6d ");
                SMSResult     result = api.Send(
                    new SMS
                {
                    To      = "8120983011",
                    Message = "Hello World"
                });

                if (result.Success)
                {
                    return("OK");
                }
                else
                {
                    return("ERROR");
                }
            }
            catch (APIException ex)
            {
                return(ex.Message);
            }
            catch (WebException ex)
            {
                return(ex.Message);
            }
            catch (ArgumentException ex)
            {
                return(ex.Message);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Example #19
0
        public async Task <MessageViewModel> GetPhoneVerificationCode(string imgCodeId, string imgCode, long phoneNumber)
        {
            string imgCodeCached = verificationCodeCached.GetImageVerificationCode(imgCodeId);

            verificationCodeCached.RemoveImageVerificationCode(imgCodeId);

            if (string.IsNullOrEmpty(imgCodeCached) || imgCodeCached.ToLower() != imgCode.ToLower())
            {
                return(new MessageViewModel
                {
                    Code = 408,
                    Message = "验证码错误!"
                });
            }

            int    seed   = Guid.NewGuid().GetHashCode();
            Random random = new Random(seed);
            int    code   = random.Next(1000, 9999);

            SMSResult res = await new TencentCloudSmsUtil().SendLoginCode("86", phoneNumber, code);

            if (res.Result != 0)
            {
                return(new MessageViewModel
                {
                    Code = 409,
                    Message = $"短信接口异常,请稍后重试!"
                });
            }

            verificationCodeCached.SetPhoneVerificationCode(phoneNumber.ToString(), code.ToString());

            return(new MessageViewModel
            {
                Code = MessageCode.Success,
                Message = $"已发送验证码到手机{phoneNumber}"
            });
        }
Example #20
0
    //public class Fetchtele
    //{
    //    public string tele { get; set; }

    //}

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            //List<Fetchtele> student = new List<Fetchtele>();
            string query = "SELECT Telephoneno FROM studpage WHERE BE >= " + cgpa.Text + " AND HSC >= " + hsc.Text + " AND SSC >= " + ssc.Text + " AND lkt <= " + lkt.Text + " AND dkt <= " + dkt.Text + " AND gap <= " + gap.Text;

            // Create a SqlCommand object and pass the constructor the connection string and the query string.
            SqlCommand queryCommand = new SqlCommand(query, con);
            // Fetchtele[] allRecords = null;

            //using (var command = new SqlCommand(query, con))
            //{
            con.Open();

            //SqlCommand cmd = new SqlCommand("select Telephoneno from studpage1", con);
            //SqlDataReader dr;

            //    dr = cmd.ExecuteReader();
            //    while (dr.Read())
            //    {
            //        student.Add(new Fetchtele()
            //        {

            //            tele = dr.GetString(dr.GetOrdinal("Teephoneno"))

            //        });

            //    }
            //    dr.Close();
            ArrayList ar = new ArrayList();
            int       i  = 0;
            using (SqlDataReader reader = queryCommand.ExecuteReader())
            {
                while (reader.Read())
                {
                    ar.Add(reader[0].ToString()); //This writes first column values for your all rows.

                    i = i + 1;
                }
            }
            string[] a = ar.ToArray(typeof(string)) as string[];

            API api = new API("42bfc956346c3dedd3f5a1910a3017b530cca2bf");

            int l = a.Length;
            //  Response.Write(l);
            string b = msg.Text;
            for (i = 0; i < l; i++)
            {
                Response.Write(a[i] + " ");
                SMSResult result = api.Send(new SMS {
                    To = a[i], Message = b
                });
            }
        }

        catch (Exception exp)
        {
            throw exp;
        }
        finally
        {
            con.Close();
        }


        /*
         * String a = String.Empty;
         *
         * try
         * {
         *    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["studpageConnectionString"].ConnectionString))
         *    {
         *        using (SqlCommand com = new SqlCommand("SELECT Telephone No FROM StudRegister WHERE ", con))
         *        {
         *            con.Open();
         *            using (SqlDataReader reader = com.ExecuteReader())
         *            {
         *                while (reader.Read())
         *                {
         *                    a = reader[0].ToString();
         *
         *                }
         *            }
         *        }
         *    }
         * }
         * catch
         * {
         *
         * }
         * con.Close();*/
        // SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["studpageConnectionString"].ConnectionString);

        /*con.Open();
         * SqlCommand cmd = con.CreateCommand();
         * cmd.CommandType = System.Data.CommandType.Text;
         *
         * cmd.ExecuteNonQuery();*/



        // Fetchtele[] allRecords = null;
        // string sql = @"SELECT Telephoneno FROM  studpage1";
        //WHERE BE >= " + cgpa + " AND HSC >= "+ hsc + " AND SSC >= "+ ssc + " AND lkt <= " + lkt + " AND dkt <= " + dkt + " AND gap <= "+ gap;
        // cmd.CommandText = "insert into studpage1 values('" + telephoneno.Text + "','" + rollno.Text + "','" + BE.Text + "','" + hsc.Text + "','" + ssc.Text + "','" + lkt.Text + "','" + dkt.Text + "','" + gap.Text + "')";

/*
 *      using (var command = new SqlCommand(sql, con))
 * {
 *  con.Open();
 *  using (var reader = command.ExecuteReader())
 *  {
 *      var list = new List<Fetchtele>();
 *      while (reader.Read())
 *          list.Add(new Fetchtele { tele = reader.GetString(0)});
 *      allRecords = list.ToArray();
 *              int i;
 *              for ( i=0; i <= 2; i++)
 *              {
 *                  Console.WriteLine(allRecords[i]);
 *              }
 *          }
 * }*/
    }
Example #21
0
 public SMSResult EexcuteTask()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.PHONENUM;
     string postdata = "action=executeBs&pid=" + projID + "&uid=" + user + "&token=" + token + "&mobile=" + mobilenum + "&step=1";
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         result.Status = true;
         result.Result = mobilenum;
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #22
0
        public override SMSResult GetMessage()
        {
            SMSResult result = new SMSResult();
            result.OpType = SMSType.CHECKCODE;
            string postdata = "action=getExeResult&uid=" + user + "&mobile=" + mobilenum + "&token=" + token + "&pid=" + projID +
                 "&step=1";
            string html = getHTML(url, postdata);
            try
            {
                if (checkMsg(ref html) == true)
                {

                    result.Status = true;
                    result.Result = html.Substring(html.IndexOf("|") + 1, html.LastIndexOf("|"));
                }
                else
                {
                    result.Status = false;
                    result.Result = html;
                }
            }
            catch (System.Exception ex)
            {
                result.Status = false;
                result.Result = html;
            }

            return result;
        }
Example #23
0
        public SMSResult SMSAISNew(LogSMSNewData entity)
        {
            dynamic info = new MyExpando();

            info.start         = DateTime.Now;
            info.LogSMSNewData = entity;
            info.method        = "SMSAISNew";

            SMSResult     SMSResult     = new SMSResult();
            string        strResult     = null;
            string        requestDetail = null;
            string        strresponse;
            string        responseDetail = null;
            ProcessNewSMS ps             = new ProcessNewSMS();

            if (entity.Language == "TH")
            {
                requestDetail = "TRANSID=BULK&CMD=SENDMSG&FROM=66899264547&TO=" + entity.Mobilenumber + "&REPORT=N&CHARGE=N&CODE=KTBLeasing_BulkSMS&CTYPE=LUNICODE&CONTENT=" + String2Unicode(entity.SMSDetail).ToUpper().ToString() + "";
            }
            else
            {
                requestDetail = "TRANSID=BULK&CMD=SENDMSG&FROM=66899264547&TO=" + entity.Mobilenumber + "&REPORT=N&CHARGE=N&CODE=KTBLeasing_BulkSMS&CTYPE=LTEXT&CONTENT=" + entity.SMSDetail + "";
            }

            string url = null;

            url = Settings.Default.AISURL;
            HttpWebRequest oRequest = (HttpWebRequest)WebRequest.Create(url);

            oRequest.Accept            = "*/*";
            oRequest.AllowAutoRedirect = true;
            oRequest.UserAgent         = "http_requester/0.1";
            oRequest.Timeout           = Settings.Default.Timeout;
            oRequest.Method            = "POST";
            oRequest.ContentType       = "application/x-www-form-urlencoded";

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] postByteArray = encoding.GetBytes(requestDetail);
            oRequest.ContentLength = postByteArray.Length;

            try
            {
                System.IO.Stream postStream = oRequest.GetRequestStream();
                postStream.Write(postByteArray, 0, postByteArray.Length);
                postStream.Close();

                HttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();

                Logger.Info(JsonConvert.SerializeObject(oRequest));
                Logger.Info(JsonConvert.SerializeObject(oResponse));

                if (oResponse.StatusCode == HttpStatusCode.OK)
                {
                    System.IO.Stream       responseStream = oResponse.GetResponseStream();
                    System.IO.StreamReader myStreamReader = new System.IO.StreamReader(responseStream);
                    strresponse = myStreamReader.ReadToEnd();

                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(strresponse);
                    System.Data.DataSet ds = new System.Data.DataSet();

                    ds.ReadXml(new System.Xml.XmlNodeReader(xmlDoc));
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        entity.Smid    = ds.Tables[0].Rows[0]["SMID"].ToString();
                        responseDetail = ds.Tables[0].Rows[0]["DETAIL"].ToString();
                        bool status = ps.InsetSMS(entity, true, requestDetail, responseDetail);
                    }
                    SMSResult.IsCompleted = true;
                    SMSResult.Message     = responseDetail;
                }
                else
                {
                    responseDetail = oResponse.StatusDescription.Trim().ToString();
                    ps.InsetSMS(entity, false, requestDetail, responseDetail);
                    SMSResult.IsCompleted = false;
                    SMSResult.Message     = responseDetail;
                }
            }
            catch (Exception Ex)
            {
                strResult      = Ex.Message.ToString();
                responseDetail = Ex.Message.ToString();
                ps.InsetSMS(entity, false, requestDetail, responseDetail);
                SMSResult.IsCompleted = false;
                SMSResult.Message     = responseDetail;

                info.end = DateTime.Now;
                Logger.Error(JsonConvert.SerializeObject(info), Ex);
            }
            return(SMSResult);
        }
Example #24
0
        public override SMSResult Login()
        {
            SMSResult result = new SMSResult();
            result.OpType = SMSType.LOGIN;
            string postdata = "&action=loginIn&uid=" + user + "&pwd=" + passwd;
            string html = getHTML(url, postdata);
            try
            {
                if (checkMsg(ref html) == true)
                {
                    token = html.Substring(html.IndexOf("|") + 1);
                    result.Status = true;
                    result.Result = token;
                }
                else
                {
                    result.Status = false;
                    result.Result = html;
                }
            }
            catch (System.Exception ex)
            {
                result.Status = false;
                result.Result = html+ex.Message+"登录失败!";
            }

            return result;
        }
Example #25
0
        public SMSResult haisms()
        {
            // update regid firebase
            // /api/smsapi/haisms
            var history = new APIHistory()
            {
                Id         = Guid.NewGuid().ToString(),
                CreateTime = DateTime.Now,
                APIUrl     = "/api/smsapi/haisms",
                Sucess     = 1
            };

            HttpRequestHeaders headers = Request.Headers;

            var authInfo = checkAuth(headers);

            if (authInfo.status == 0)
            {
                history.Sucess     = 0;
                history.ReturnInfo = new JavaScriptSerializer().Serialize(authInfo);

                db.APIHistories.Add(history);
                db.SaveChanges();

                return(authInfo);
            }
            else
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;
                var jsonserializer = new JavaScriptSerializer();


                SMSHistory smsHistory = new SMSHistory()
                {
                    CreateTime = DateTime.Now,
                    Id         = Guid.NewGuid().ToString()
                };

                SMSResult result = new SMSResult()
                {
                    status  = 0,
                    message = ""
                };
                history.Content = requestContent;


                try
                {
                    var        paser   = jsonserializer.Deserialize <SMSRequest>(requestContent);
                    SMSContent content = analysisContent(paser.content, paser.phone);

                    smsHistory.PhoneNumber = paser.phone;
                    smsHistory.ContentSend = paser.content;

                    if (content.status == 0)
                    {
                        result.status = 1;
                        // sai cu phap
                        result.message = "Cu phap nhan tin cua Quy Khach vua thuc hien khong dung. Chi tiet lien he NVTT hoac 1800577768";
                    }
                    else
                    {
                        if (content.isAgency)
                        {
                            smsHistory.AgencyType = "CII";
                            result = checkContent(content);
                        }
                        else
                        {
                            smsHistory.AgencyType = "FARMER";
                            result = checkContentFarmer(content);
                        }
                    }
                }
                catch (Exception e)
                {
                    result.status  = 0;
                    result.message = e.Message;
                }


                smsHistory.ContentReturn = result.message;

                db.SMSHistories.Add(smsHistory);

                history.ReturnInfo = new JavaScriptSerializer().Serialize(result);

                history.Sucess = result.status;

                db.APIHistories.Add(history);
                db.SaveChanges();

                return(result);
            }
        }
Example #26
0
        public override SMSResult GetPhoneNum()
        {
            SMSResult result = new SMSResult();
            result.OpType = SMSType.PHONENUM;
            string postdata = "action=getMobilenum&pid=" + projID + "&uid=" + user + "&token=" + token;
            string html = getHTML(url, postdata);
            string token1;
            if (checkMsg(ref html) == true)
            {
                try
                {
                    mobilenum = html.Substring(0, html.IndexOf("|"));
                    token1 = html.Substring(html.IndexOf("|") + 1);

                    result.Status = true;
                    result.Result = mobilenum;
                }
                catch (System.Exception ex)
                {
                    result.Status = false;
                    result.Result = html;
                }

            }
            else
            {
                result.Status = false;
                result.Result = html;
            }
            return result;
        }
Example #27
0
 public override SMSResult ReleaseAll()
 {
     SMSResult resp = new SMSResult();
      String result = "";
      resp.Status = true;
     //              try
     //              {
     //                  string postdata = "action=ReleaseMobile&uid=" + user + "&token=" + token;
     //                  result = send.HttpPost(url, postdata);
     //                  if (isNumber(result))
     //                  {
     //                      resp.Status = true;
     //                      resp.Result = result;
     //
     //                  }
     //                  else
     //                  {
     //                      resp.Status = false;
     //                      resp.Result = result;
     //                  }
     //
     //              }
     //              catch (Exception e)
     //              {
     //                  resp.Status = false;
     //              }
      return resp;
 }
Example #28
0
 public override SMSResult ReleasePhoneNum(string phoneNum)
 {
     SMSResult result = new SMSResult();
     string postdata = "Api/userReleasePhone?token=" + token + "&phoneList=" + mobilenum + "-" + projID;
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         result.Status = true;
         result.Result = html.Substring(html.LastIndexOf("|") + 1);
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #29
0
 public override SMSResult Login()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.LOGIN;
     string postdata = "Api/userLogin?uName=" + user + "&pWord=" + passwd;
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         token = html.Substring(0,html.IndexOf("&"));
         result.Status = true;
         result.Result = token;
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #30
0
 public override SMSResult GetPhoneNum()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.PHONENUM;
     string postdata = "Api/userGetPhone?ItemId=" + projID + "&token=" + token + "&PhoneType=0";
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         int idx = html.IndexOf(";");
         mobilenum = html;
         if (idx > 0)
         {
             mobilenum = html.Substring(0, html.IndexOf(";"));
         }
         result.Status = true;
         result.Result = mobilenum;
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #31
0
        private SMSResult checkContentFarmer(SMSContent paser)
        {
            var result = new SMSResult()
            {
                status = 1
            };

            try
            {
                // so

                var cInfo = db.CInfoCommons.Where(p => p.Phone == paser.phone).FirstOrDefault();

                if (cInfo == null)
                {
                    return new SMSResult {
                               status = 1, message = "So dien thoai Quy Khach vua nhan tin chua dang ky tham gia Chuong trinh nhan tin cung voi Cong ty HAI. Chi tiet lien he NVTT hoac 1800577768"
                    }
                }
                ;

                if (cInfo.CType != "FARMER")
                {
                    return new SMSResult {
                               status = 1, message = "So dien thoai Quy Khach vua nhan tin chua dang ky tham gia Chuong trinh nhan tin cung voi Cong ty HAI. Chi tiet lien he NVTT hoac 1800577768"
                    }
                }
                ;


                // lay danh sach sự kiện phù hợp với user (theo khu vực)
                List <EventInfo> listEventUser = new List <EventInfo>();

                //var eventArea = db.EventAreaFarmers.Where(p => p.AreaId == cInfo.AreaId && p.EventInfo.ESTT == 1).ToList();
                var dateNow   = DateTime.Now;
                var eventArea = (from log in db.EventAreaFarmers
                                 where log.AreaId == cInfo.AreaId && log.EventInfo.ESTT == 1 && (DbFunctions.TruncateTime(log.EventInfo.BeginTime)
                                                                                                 <= DbFunctions.TruncateTime(dateNow) && DbFunctions.TruncateTime(log.EventInfo.EndTime)
                                                                                                 >= DbFunctions.TruncateTime(dateNow))
                                 select log).ToList();

                foreach (var item in eventArea)
                {
                    var cusJoin = db.EventCustomerFarmers.Where(p => p.EventId == item.EventId && p.CInfoCommon.AreaId == item.AreaId).ToList();

                    if (cusJoin.Count() > 0)
                    {
                        var cJoin = cusJoin.Where(p => p.CInfoId == cInfo.Id).FirstOrDefault();
                        if (cJoin != null)
                        {
                            listEventUser.Add(item.EventInfo);
                        }
                    }
                    else
                    {
                        listEventUser.Add(item.EventInfo);
                    }
                }



                if (listEventUser.Count() == 0)
                {
                    return new SMSResult {
                               status = 4, message = "Quy khach dang dung hang chinh hang. Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI"
                    }
                }
                ;

                // kiem tra ma dung, ma sau
                List <ProductSeri> righCode = new List <ProductSeri>();

                foreach (var item in paser.products)
                {
                    // lây mã seri // eventCode or seri
                    var productSeri = db.ProductSeris.Where(p => p.Code == item && p.IsUse == 0 && p.SeriType == 2).FirstOrDefault();


                    if (productSeri == null)
                    {
                        return(new SMSResult {
                            status = 4, message = "Ma " + item + " khong dung. Vui long kiem tra lai ma so nhan tin. Xin cam on"
                        });
                    }
                    else if (productSeri.IsUse == 1)
                    {
                        return(new SMSResult {
                            status = 4, message = "Ma " + item + " da duoc su dung vao (" + productSeri.ModifyTime + "), Vui long kiem tra lai ma so nhan tin. Xin cam on"
                        });
                    }
                    else
                    {
                        righCode.Add(productSeri);
                    }
                }

                Hashtable map = new Hashtable();

                List <string> productAttend = new List <string>();

                result.status = 5;

                foreach (var item in righCode)
                {
                    try
                    {
                        // cap nhat lịch su
                        var hEvent = new MSGPoint()
                        {
                            Id         = Guid.NewGuid().ToString(),
                            AcceptTime = DateTime.Now,
                            CInfoId    = cInfo.Id,
                            UserLogin  = paser.code,
                            ProductId  = item.ProductId,
                            Barcode    = item.Code,
                            MSGType    = "SMS"
                        };

                        List <MSGPointEvent> listPointEvent = new List <MSGPointEvent>();

                        foreach (var userEvent in listEventUser)
                        {
                            // kiem tra san pham co trong su kien nay ko
                            var productEvent = userEvent.EventProducts.Where(p => p.ProductId == item.ProductId).FirstOrDefault();
                            if (productEvent != null)
                            {
                                var pointEvemt = new MSGPointEvent()
                                {
                                    EventId    = userEvent.Id,
                                    MSGPointId = hEvent.Id,
                                    Point      = productEvent.Point
                                };
                                listPointEvent.Add(pointEvemt);
                            }
                        }
                        //

                        if (listPointEvent.Count() > 0)
                        {
                            if (!productAttend.Contains(item.ProductId))
                            {
                                productAttend.Add(item.ProductId);
                            }

                            item.IsUse           = 1;
                            item.ModifyTime      = DateTime.Now;
                            db.Entry(item).State = System.Data.Entity.EntityState.Modified;

                            db.MSGPoints.Add(hEvent);

                            db.SaveChanges();

                            foreach (var pevent in listPointEvent)
                            {
                                if (map.ContainsKey(pevent.EventId))
                                {
                                    var oldPoint = Convert.ToInt32(map[pevent.EventId]);
                                    map[pevent.EventId] = oldPoint + pevent.Point;
                                }
                                else
                                {
                                    map.Add(pevent.EventId, Convert.ToInt32(pevent.Point));
                                }

                                db.MSGPointEvents.Add(pevent);



                                // luu diem cho khach hang
                                var agencyPoint = db.AgencySavePoints.Where(p => p.EventId == pevent.EventId && p.CInfoId == cInfo.Id).FirstOrDefault();

                                if (agencyPoint == null)
                                {
                                    var newAgencyPoint = new AgencySavePoint()
                                    {
                                        EventId    = pevent.EventId,
                                        CInfoId    = cInfo.Id,
                                        PointSave  = pevent.Point,
                                        CreateTime = DateTime.Now
                                    };
                                    db.AgencySavePoints.Add(newAgencyPoint);
                                }
                                else
                                {
                                    var newPoint = agencyPoint.PointSave + pevent.Point;
                                    agencyPoint.PointSave       = newPoint;
                                    agencyPoint.ModifyTime      = DateTime.Now;
                                    db.Entry(agencyPoint).State = System.Data.Entity.EntityState.Modified;
                                }

                                db.SaveChanges();
                            }
                        }
                    }
                    catch
                    {
                    }
                }
                //

                // phan qua
                string pointEvent = "";
                int    countPoint = 0;
                foreach (var item in map.Keys)
                {
                    var eventInfo = db.EventInfoes.Find(item);

                    var savePoint = eventInfo.AgencySavePoints.Where(p => p.CInfoCommon.CCode == paser.code).FirstOrDefault();
                    int?point     = 0;
                    if (savePoint != null)
                    {
                        point = savePoint.PointSave;
                    }

                    string aWard     = "";
                    var    listAward = eventInfo.AwardInfoes.OrderByDescending(p => p.Point).ToList();
                    foreach (var aWardItem in listAward)
                    {
                        if (aWardItem.Point <= point)
                        {
                            aWard = ConvertToUnsign3(aWardItem.Name);
                            break;
                        }
                    }

                    var nameEvent = ConvertToUnsign3(eventInfo.Name);

                    if (!String.IsNullOrEmpty(aWard))
                    {
                        pointEvent = " , " + aWard + " tu " + nameEvent;
                    }


                    countPoint += Convert.ToInt32(map[item]);
                }


                //
                string msgReturn = "Chuc mung Quy khach vua tich luy " + countPoint + " diem tu ";
                foreach (string item in productAttend)
                {
                    var productCheck = db.ProductInfoes.Find(item);
                    if (productCheck != null)
                    {
                        msgReturn += ConvertToUnsign3(productCheck.PName) + " ,";
                    }
                }

                msgReturn = msgReturn.Remove(msgReturn.Count() - 1, 1);

                msgReturn += ". Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI. ";


                if (!String.IsNullOrEmpty(pointEvent))
                {
                    pointEvent = pointEvent.Remove(0, 2);
                    msgReturn += "Chuc mung Quy khach nhan duoc " + pointEvent + ". Cam on Quy khach da tin dung & ung ho hang cua cong ty CPND HAI.";
                }

                result.message = msgReturn;
            }
            catch (Exception e)
            {
                result.status  = 0;
                result.message = e.Message;
            }

            return(result);
        }
Example #32
0
 public void SendNullSMS_Single()
 {
     Clockwork.API api    = new API(key);
     SMS           sms    = null;
     SMSResult     result = api.Send(sms);
 }
Example #33
0
        public override SMSResult ReleasePhoneNum(string phoneNum)
        {
            SMSResult resp = new SMSResult();
            String result = "";

            try
            {
                string postdata = "action=ReleaseMobile&mobile=" + phoneNum + "&token=" + token + "&uid=" + user;
                result = send.HttpPost(url,postdata);
                if (isNumber(result))
                {
                    resp.Status = true;
                    resp.Result = result;

                }
                else
                {
                    resp.Status = false;
                    resp.Result = result;
                }

            }
            catch (Exception e)
            {
                resp.Status = false;
            }
            return resp;
        }
Example #34
0
 public override SMSResult GetMessageAndRealase()
 {
     SMSResult result = new SMSResult();
     string postdata = "action=getVcodeAndReleaseMobile&mobile=" + mobilenum + "&token=" + token + "&uid=" + user;
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         result.Status = true;
         result.Result = html.Substring(html.LastIndexOf("|") + 1);
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #35
0
 public override SMSResult GetMessage()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.CHECKCODE;
     string postdata = "action=getVcodeAndReleaseMobile" + "&uid=" + user + "&mobile=" + mobilenum + "&token=" + token + "&pid="+projID+
          "&author_uid=spy2ym";
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         result.Status = true;
         result.Result = html.Substring(html.LastIndexOf("|") + 1);
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #36
0
 public override SMSResult Login()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.LOGIN;
     string postdata = "action=loginIn&uid=" + user + "&pwd=" + passwd;
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         token = html.Substring(html.IndexOf("|") + 1);
         result.Status = true;
         result.Result = token;
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #37
0
 public override SMSResult ReleaseAll()
 {
     SMSResult resp = new SMSResult();
      resp.Status = false;
      return resp;
 }
Example #38
0
 public override SMSResult ReleasePhoneNum(string phoneNum)
 {
     SMSResult resp = new SMSResult();
     resp.Status = false;
     return resp;
 }
Example #39
0
 public override SMSResult GetMessage()
 {
     SMSResult result = new SMSResult();
     result.OpType = SMSType.CHECKCODE;
     string postdata = "Api/userGetMessage?token=" + token;
     string html = getHTML(url, postdata);
     if (checkMsg(ref html) == true)
     {
         string startStr = "MSG&"+projID+"&"+mobilenum;
         if (html.Contains(startStr))
         {
             result.Status = true;
             result.Result = html.Substring(html.LastIndexOf("&") + 1);
         }
         else
         {
             result.Status = false;
             result.Result = html;
         }
     }
     else
     {
         result.Status = false;
         result.Result = html;
     }
     return result;
 }
Example #40
0
        public SMSResult SendSMS(Models.SmsRequest smsRequest)
        {
            //TODO: use HttpResponseMessage for returning
            Bogus.Faker faker  = new Bogus.Faker();
            SMSResult   result = new SMSResult()
            {
                Id = Guid.NewGuid(), ExternalId = smsRequest.messageExternalId
            };

            //try
            //{
            ApplyDelay();
            // simulate a random result behaviour
            // 50% to be ok
            if (faker.Random.Number(100) < 10)
            {
                result.Status = MessageStatus.OK;
            }
            else
            {
                // exclude ok
                result.Status = faker.Random.Enum(MessageStatus.OK);
            }

            switch (result.Status)
            {
            case MessageStatus.Error:
                result.ReturnedMessage = faker.System.Exception().Message;
                break;

            case MessageStatus.InvalidCredentials:
                result.ReturnedMessage = "Your credentials are invalid!";
                break;

            case MessageStatus.InvalidNumber:
                result.ReturnedMessage = "This mobile number is invalid!";
                break;

            case MessageStatus.MessageTooLong:
                result.ReturnedMessage = "This message is too long!";
                break;

            case MessageStatus.NotEnoughCredits:
                result.ReturnedMessage = "NotEnoughCredits";
                break;

            case MessageStatus.OK:
                DecreaseCredit();
                break;

            case MessageStatus.Pending:
                result.ReturnedMessage = "Pending....";
                break;
            }
            result.TimeStamp = DateTime.Now;
            return(result);
            //}
            //catch (Exception ex)
            //{

            //    return InternalServerError(ex);
            //}
        }
Example #41
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["telep"] = telephoneno.Text.ToString();
        string alphabets       = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
        string numbers         = "1234567890";

        string characters = numbers;

        characters += alphabets + small_alphabets + numbers;

        string otp = string.Empty;

        for (int i = 0; i < 10; i++)
        {
            string character = string.Empty;
            do
            {
                int index = new Random().Next(0, characters.Length);
                character = characters.ToCharArray()[index].ToString();
            } while (otp.IndexOf(character) != -1);
            otp += character;
        }
        Label1.Text = otp;

        con.Open();
        SqlCommand cmd = con.CreateCommand();

        cmd.CommandType = System.Data.CommandType.Text;
        cmd.CommandText = "insert into password values('" + telephoneno.Text + "','" + otp + "')";
        cmd.ExecuteNonQuery();
        con.Close();

        API    api = new API("42bfc956346c3dedd3f5a1910a3017b530cca2bf");
        string t   = telephoneno.Text;
        string msg = "Welcome to Real Time Information System ! OTP for your Number is :" + otp;

        //Response.Write(otp);
        //Response.Write(msg);
        try
        {
            SMSResult result = api.Send(new SMS {
                To = t, Message = msg
            });
            if (result.Success)
            {
                System.Diagnostics.Debug.WriteLine("SMS Sent to {0}, Clockwork ID: {1}", result.SMS.To, result.ID);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("SMS to {0} failed, Clockwork Error: {1}{2}", result.SMS.To, result.ErrorCode, result.ErrorMessage);
            }
        }

        catch (APIException ex)
        {
            // You’ll get an API exception for errors
            // such as wrong username or password
            System.Diagnostics.Debug.WriteLine("API Exception: " + ex.Message);
        }
        catch (System.Net.WebException ex)
        {
            // Web exceptions mean you couldn’t reach the Clockwork server
            System.Diagnostics.Debug.WriteLine("Web Exception: " + ex.Message);
        }
        catch (ArgumentException ex)
        {
            // Argument exceptions are thrown for missing parameters,
            // such as forgetting to set the username
            System.Diagnostics.Debug.WriteLine("Argument Exception: " + ex.Message);
        }
        catch (Exception ex)
        {
            // Something else went wrong, the error message should help
            System.Diagnostics.Debug.WriteLine("Unknown Exception: " + ex.Message);
        }
    }