Esempio n. 1
0
        /// <summary>
        /// <see cref="ISendShortMessageService.SendShortMessage"/>
        /// </summary>
        public SMSResponse SendShortMessage(ShortMessage shortmessage)
        {
            SMSResponse response = new SMSResponse();

            //CCPRestSDK.CCPRestSDK api = new CCPRestSDK.CCPRestSDK();
            ////ip格式如下,不带https://
            //bool isInit = api.init(SMSAccountInfo.Instance.SendAdress,
            //    SMSAccountInfo.Instance.CustomizedInfos[Constants.Port]);
            //api.setAccount(SMSAccountInfo.Instance.AccountSID,
            //    SMSAccountInfo.Instance.AuthToken);
            //api.setAppId(SMSAccountInfo.Instance.CustomizedInfos[Constants.APPID]);
            //if (isInit)
            //{
            //    var paras = shortmessage.Parameters == null ?
            //        new string[1] { shortmessage.Content } : shortmessage.Parameters;
            //    Dictionary<string, object> retData =
            //        api.SendTemplateSMS(shortmessage.ToPhoneNumber,
            //        SMSAccountInfo.Instance.CustomizedInfos[Constants.TemplateId], paras);
            //    if (string.Equals(retData[STatusCode].ToString(), "000000"))
            //    {
            //       response.statusCode = "200";
            //    }
            //    else
            //    {
            //        response.statusCode = "403";
            //    }
            //    response.ResponseData = getDictionaryData(retData);
            //}
            //else
            //{
            //    response.statusCode = "103";
            //    response.ResponseData = "初始化失败";
            //}
            return response;
        }
Esempio n. 2
0
        public static int UpdateUserNewPMCount(int uid, int olid)
        {
            //int newPMCount = BBX.Data.PrivateMessages.GetNewPMCount(uid);
            var newPMCount = ShortMessage.GetNewPMCount(uid);
            //OnlineUsers.UpdateNewPms(olid, newPMCount);
            var online = Online.FindByID(olid);

            if (online != null)
            {
                online.UpdateNewPms(newPMCount);
            }
            //return BBX.Data.Users.SetUserNewPMCount(uid, newPMCount);
            var user = User.FindByID(uid);

            if (user != null)
            {
                user.NewpmCount = newPMCount;
                user.Update();
            }
            return(1);
        }
Esempio n. 3
0
 private void CreatePM(int folder, int saveToSendBox, string url, string msg)
 {
     if (folder != 2)
     {
         User userInfo = Users.GetUserInfo(this.msgtoid);
         var  ug       = UserGroup.FindByID(this.usergroupid);
         if (!ug.Is管理团队 && ShortMessage.GetPrivateMessageCount(this.msgtoid, -1) >= UserGroup.FindByID(userInfo.GroupID).MaxPmNum)
         {
             base.AddErrLine("抱歉,接收人的短消息已达到上限,无法接收");
             return;
         }
         if (!Utils.InArray(userInfo.NewsLetter.ToInt().ToString(), "2,3,6,7"))
         {
             base.AddErrLine("抱歉,接收人拒绝接收短消息");
             return;
         }
     }
     if (url != "usercpinbox.aspx" && ShortMessage.GetPrivateMessageCount(this.userid, -1) >= this.usergroupinfo.MaxPmNum)
     {
         base.AddErrLine("抱歉,您的短消息已达到上限,无法保存到发件箱");
         return;
     }
     this.pm.Folder = (Int16)folder;
     if (CreditsFacade.SendPM(this.userid) == -1)
     {
         base.AddErrLine("您的积分不足, 不能发送短消息");
         return;
     }
     //this.pm.Pmid = PrivateMessages.CreatePrivateMessage(this.pm, saveToSendBox);
     pm.Create(saveToSendBox != 0);
     if (DNTRequest.GetString("emailnotify") == "on")
     {
         this.SendNotifyEmail(Users.GetUserInfo(this.msgtoid).Email.Trim(), this.pm);
     }
     base.SetUrl(url);
     base.SetMetaRefresh();
     base.SetShowBackLink(true);
     base.MsgForward("usercppostpm_succeed");
     base.AddMsgLine(msg);
 }
Esempio n. 4
0
 public void LoadMessage()
 {
     if (CurrentMessage != null)
     {
         ShortMessage msg = CurrentMessage;
         Subject   = msg.Subject;
         Content   = msg.Content;
         Receivers = msg.Receivers;
         SendTime  = msg.SendTime;
         if (msg.State == (int)MessageState.Draft)
         {
             ReSubject  = Subject;
             ReReceiver = Receivers;
             ReContent  = Content;
         }
         else
         {
             ReSubject  = "回复:" + Subject;
             ReReceiver = msg.AccountName;
         }
     }
 }
Esempio n. 5
0
        void SendMessage()
        {
            string[]       receivers = Receivers.Split(',');
            List <Account> accounts  = new List <Account>();

            foreach (string user in receivers)
            {
                Account acc = AccountHelper.GetAccountByLoginName(user);
                if (acc != null)
                {
                    accounts.Add(acc);
                }
                else
                {
                    Message = "收件人“" + user + "”不是合法用户,请检查再试!";
                    return;
                }
            }
            foreach (Account acc in accounts)
            {
                ShortMessage sm = new ShortMessage();
                sm.AccountID  = Security.CurrentAccountID;
                sm.ReceiverID = acc.ID;
                sm.Receivers  = acc.LoginName;
                sm.Subject    = Subject;
                sm.Content    = Content;
                sm.SendTime   = DateTime.Now;
                sm.State      = (int)MessageState.NewMessage;
                MessageHelper.AddMessage(sm);
                if (SavetoOutbox == "1")
                {
                    sm.State = (int)MessageState.Outbox;
                    MessageHelper.AddMessage(sm);
                }
            }

            Message = "短消息已成功发送!";
        }
Esempio n. 6
0
        public SarifErrorListItem(Run run, Notification notification, string logFilePath, ProjectNameCache projectNameCache) : this()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            _runId = CodeAnalysisResultManager.Instance.CurrentRunId;
            ReportingDescriptor rule;
            string ruleId = null;

            if (notification.AssociatedRule != null)
            {
                ruleId = notification.AssociatedRule.Id;
            }
            else if (notification.Descriptor != null)
            {
                ruleId = notification.Descriptor.Id;
            }

            run.TryGetRule(ruleId, out rule);
            Message      = notification.Message.Text.Trim();
            ShortMessage = ExtensionMethods.GetFirstSentence(notification.Message.Text);
            if (!Message.EndsWith("."))
            {
                ShortMessage = ShortMessage.TrimEnd('.');
            }
            Level       = notification.Level;
            LogFilePath = logFilePath;
            FileName    = SdkUIUtilities.GetFileLocationPath(notification.Locations?[0]?.PhysicalLocation?.ArtifactLocation, _runId) ?? "";
            ProjectName = projectNameCache.GetName(FileName);
            Locations.Add(new LocationModel()
            {
                FilePath = FileName
            });

            Tool             = run.Tool.ToToolModel();
            Rule             = rule.ToRuleModel(ruleId);
            Invocation       = run.Invocations?[0]?.ToInvocationModel();
            WorkingDirectory = Path.Combine(Path.GetTempPath(), _runId.ToString());
        }
Esempio n. 7
0
 protected override void ShowPage()
 {
     this.pagetitle = "短消息草稿箱";
     if (!base.IsLogin())
     {
         return;
     }
     if (DNTRequest.IsPost())
     {
         if (ShortMessage.DeletePrivateMessage(this.userid, DNTRequest.GetFormString("pmitemid")) <= 0)
         {
             base.AddErrLine("参数无效<br />");
             return;
         }
         base.SetMetaRefresh();
         base.SetShowBackLink(true);
         base.AddMsgLine("删除完毕");
     }
     else
     {
         base.BindPrivateMessage(2);
     }
     this.newnoticecount = Notice.GetNewNoticeCountByUid(this.userid);
 }
Esempio n. 8
0
        private void InputCallback(Win32Api.Api.HandleMidiIn hMidiIn, Win32Api.Api.MidiInMessage wMsg, UIntPtr dwInstance, UIntPtr dwParam1, UIntPtr dwParam2)
        {
            isInsideInputHandler = true;
            try
            {
                if (wMsg == Win32Api.Api.MidiInMessage.MIM_DATA)
                {
                    ShortMessage.DecodeMessage(dwParam1, out Channel channel, out UInt7 note, out UInt7 velocity);

                    if (ShortMessage.IsNoteOn(dwParam1))
                    {
                        this.NoteOn?.Invoke(new MidiMessage(this, channel, note, velocity));
                    }
                    else
                    {
                        throw new ArgumentOutOfRangeException();
                    }
                }
            }
            finally
            {
                isInsideInputHandler = false;
            }
        }
Esempio n. 9
0
        public async Task <bool> SendSMS(SendSMSRequest request)
        {
            _loggerService.LogInformation("SendSMS(SendSMSRequest request) - START", request);

            // Normally create a mapper here - in case sms provider requires diff info. (^_^)

            var clickaTellRequest = new ShortMessage()
            {
                CellNumberSendFrom = request.CellNumber,
                CellNumberSendTo   = request.SendTo,
                Message            = request.Message
            };

            // Normally have a gateway here in case sms provider changes (^_^)

            // No need to try catch, unless there's specific error type we want to look for.
            // Exception handling is done by middleware.

            var success = await _smsRepo.SendSMSClickaTell(clickaTellRequest);

            _loggerService.LogInformation("SendSMS(SendSMSRequest request) - END", request);

            return(success);
        }
Esempio n. 10
0
        /// <summary>
        /// Handles each tick of the poll timer
        /// </summary>
        /// <param name="sender">The timer that fired this event</param>
        /// <param name="e">The event arguments</param>
        private void UpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            int messageCount = CountSMSMessages();

            if (messageCount > 0)
            {
                //UpdateTimer.Stop();

                ShortMessageCollection messages = ReadSMS(Port, "AT+CMGL=\"ALL\"");
                foreach (ShortMessage message in messages)
                {
                    SmsMessages.Enqueue(message);
                }

                if (DeleteSMS(Port, "AT+CMGD=1,4"))
                {
                    // success on deletion!
                }
                else
                {
                    // failed to delete, which is bad, uh-oh...
                    throw new InvalidOperationException("Can't proceed - old SMS messages cannot be deleted.");
                }

                do
                {
                    if (SmsMessages.Count > 0)
                    {
                        ShortMessage message = SmsMessages.Dequeue();
                        ExecuteMessageContent(message);
                    }
                } while (SmsMessages.Count != 0);

                //UpdateTimer.Start();
            }
        }
Esempio n. 11
0
        private ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
            Match m = r.Match(input);

            string[] mySplit = input.Split(new string[] { "+CMGL:" }, StringSplitOptions.None);
            int num = mySplit.Length - 1;
            for (int i = 1; i <= num; i++)
            {
                string sms = mySplit[i].Replace("\r\nOK\r", "");
                sms = sms.Replace("\r\n", "");
                sms = sms.Replace(",\"", ",");
                sms = sms.Replace("\"", ",");
                sms = sms.Replace("\r\n", ",");
                string[] mess = sms.Split(',');

                if (mess.Length > 4)
                {
                    for (int y = 5; y < mess.Length; y++)
                        mess[4] += ","+mess[y];
                }

                ShortMessage msg = new ShortMessage();
                msg.Index = int.Parse(mess[0]);
                msg.Status = mess[1];
                msg.Sender = mess[3];
                msg.Alphabet = "";
                msg.Sent = DateTime.Now.ToString();
                if (mess[4].IndexOf("\n") > -1) mess[4].Replace("\n", "");
                msg.Message = mess[4];
                messages.Add(msg);
            }

            return messages;
        }
Esempio n. 12
0
        private void BindNew()
        {
            if (userid > 0)
            {
                base.AddErrLine("当前已有用户登录,无法注册");
                return;
            }
            //if (config.Regstatus < 1 || cloudconfig.Allowconnectregister == 0)
            //{
            //    base.AddErrLine("论坛当前禁止新的QQ会员登录");
            //    return;
            //}
            string username = DNTRequest.GetString(config.Antispamregisterusername);
            string email    = DNTRequest.GetString(config.Antispamregisteremail).Trim().ToLower();
            string birthday = DNTRequest.GetString("bday").Trim();
            string errinfo  = "";

            if (!Users.PageValidateUserName(username, out errinfo) || !Users.PageValidateEmail(email, false, out errinfo))
            {
                base.AddErrLine(errinfo);
                return;
            }
            if (!Utils.IsDateString(birthday) && !string.IsNullOrEmpty(birthday))
            {
                base.AddErrLine("生日格式错误, 如果不想填写生日请置空");
                return;
            }
            if (Users.GetUserId(username) > 0)
            {
                base.AddErrLine("请不要重复提交!");
                return;
            }

            var connect = QzoneConnectContext.Current;

            var storedToken = QzoneConnectToken.FindByOpenId(connect.Token.OpenId);

            if (storedToken != null)
            {
                var url = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Host, BaseConfigInfo.Current.Forumpath + qzconfig.QzoneConnectPage + "?act=access");
                XTrace.WriteLine("BindNew -> redirect -> " + url);
                Response.Redirect(url);
                return;
            }

            User userInfo = this.CreateUser(username, connect.GetQqNickname(), email, birthday);

            connect.Token.Uid = userInfo.ID;
            connect.Token.Save();
            //QzoneConnectToken.Insert(connect.Token);

            XTrace.WriteLine("BindNew -> success, uid=" + connect.Token.Uid);

            if (this.config.Welcomemsg == 1)
            {
                var msg = new ShortMessage
                {
                    Message   = this.config.Welcomemsgtxt,
                    Subject   = "欢迎您的加入! (请勿回复本信息)",
                    Msgto     = userInfo.Name,
                    MsgtoID   = userInfo.ID,
                    Msgfrom   = "系统",
                    MsgfromID = 0,
                    Folder    = 0
                };
                msg.Create(false);
            }
            //Sync.UserRegister(userInfo.ID, userInfo.Name, userInfo.Password, "");
            if (qzconfig.AllowUseQZAvater && DNTRequest.GetString("use_qzone_avatar") == "1")
            {
                var qZoneAvatar = new QZoneAvatar();
                qZoneAvatar.AsyncGetAvatar(connect);
            }
            LoginUser(userInfo);
            //Statistics.ReSetStatisticsCache();
            Statistic.Reset();
            if (this.config.Regverify != 2)
            {
                CreditsFacade.UpdateUserCredits(userInfo.ID);
                Online.UpdateAction(this.olid, UserAction.Register, 0, this.config.Onlinetimeout);
                base.AddMsgLine("QQ登录成功,继续浏览");
            }
            else
            {
                base.AddMsgLine("QQ数据绑定完成, 但需要系统管理员审核您的帐户后才可登录使用");
            }
            base.SetUrl(connect.Callback);
            base.SetMetaRefresh();
            base.SetShowBackLink(false);

            XTrace.WriteLine("BindNew -> finish, uid=" + connect.Token.Uid);
        }
Esempio n. 13
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
                Match m = r.Match(input);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = ConvertRusFromUCS2(m.Groups[3].Value);
                    msg.Alphabet = m.Groups[4].Value;
                    DateTime sourceDate = DateTime.ParseExact(m.Groups[5].Value, "dd/M/yy,HH:mm:ss+ff", CultureInfo.InvariantCulture);
                    msg.SentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, sourceDate.Hour, sourceDate.Minute, sourceDate.Second, sourceDate.Millisecond);

                    msg.Text = ConvertRusFromUCS2(m.Groups[6].Value);

                    messages.Add(msg);
                    m = m.NextMatch();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Ошибка парсинга сообщений: " + ex.Message);
            }
            return messages;
        }
Esempio n. 14
0
        /// <summary>发送短信</summary>
        /// <param name="message">短信</param>
        public string Send(ShortMessage message)
        {
            //
            //curl -X POST 'http://gw.api.taobao.com/router/rest' \
            //-d 'app_key=12129701' \
            //-d 'format=json' \
            //-d 'method=alibaba.aliqin.fc.sms.num.send' \
            //-d 'partner_id=apidoc' \
            //-d 'sign=1504970E2D634D872A5EED23FF091BC3' \
            //-d 'sign_method=hmac' \
            //-d 'timestamp=2015-12-08+20%3A19%3A29' \
            //-d 'v=2.0' \
            //-d 'extend=123456' \
            //-d 'rec_num=13000000000' \
            //-d 'sms_free_sign_name=%E9%98%BF%E9%87%8C%E5%A4%A7%E9%B1%BC' \
            //-d 'sms_param=%7B%5C%22code%5C%22%3A%5C%221234%5C%22%2C%5C%22product%5C%22%3A%5C%22alidayu%5C%22%7D' \
            //-d 'sms_template_code=SMS_585014' \
            //-d 'sms_type=normal'

            // http://gw.api.taobao.com/router/rest?app_key={0}&amp;sign={1}&amp;sign_method=hmac&amp;timestamp={2}&amp;rec_num={3}&amp;sms_free_sign_name={4}&amp;sms_param={5}&amp;sms_template_code={6}&amp;sms_type=normal&amp;v=2.0&amp;method=alibaba.aliqin.fc.sms.num.send&amp;format=json


            string result = null;

            string url = SMSConfigurationView.Instance.SendUrl;

            IDictionary <string, string> parameters = new Dictionary <string, string>();

            parameters.Add("app_key", SMSConfigurationView.Instance.Username);
            parameters.Add("sign_method", "md5");
            parameters.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            parameters.Add("rec_num", message.PhoneNumber);
            parameters.Add("sms_free_sign_name", SMSConfigurationView.Instance.SignName);
            parameters.Add("sms_param", message.MessageTemplateParam);
            parameters.Add("sms_template_code", message.MessageTemplateCode);
            parameters.Add("sms_type", "normal");
            parameters.Add("v", "2.0");
            parameters.Add("method", "alibaba.aliqin.fc.sms.num.send");
            parameters.Add("format", "xml");
            // parameters.Add("partner_id", "x3platform");

            string sign = SignTopRequest(parameters, SMSConfigurationView.Instance.Password, true);

            parameters.Add("sign", sign);

            StringBuilder httpParams = new StringBuilder();

            foreach (KeyValuePair <string, string> arg in parameters)
            {
                httpParams.AppendFormat("{0}={1}&", arg.Key, HttpUtility.UrlEncode(arg.Value, Encoding.UTF8));
            }

            httpParams = StringHelper.TrimEnd(httpParams, "&");

            byte[] data = Encoding.UTF8.GetBytes(httpParams.ToString());

            try
            {
                HttpWebRequest request = null;

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = CertificateManager.GetCallback(true);
                    request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
                }
                else
                {
                    request = (HttpWebRequest)WebRequest.Create(url);
                }

                request.ServicePoint.Expect100Continue = false;

                request.Headers["Accept-Encoding"] = "gzip";

                request.Method           = "POST";
                request.KeepAlive        = true;
                request.UserAgent        = "top-sdk-net";
                request.Accept           = "text/xml,text/javascript";
                request.Timeout          = 20000;
                request.ReadWriteTimeout = 60000;
                request.ContentType      = "application/x-www-form-urlencoded;charset=utf-8";
                request.ContentLength    = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            StreamReader reader = null;
                            if (response.ContentEncoding == "gzip")
                            {
                                GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress);
                                reader = new StreamReader(gzipStream, Encoding.UTF8);
                            }
                            else
                            {
                                reader = new StreamReader(stream, Encoding.UTF8);
                            }

                            result = reader.ReadToEnd();
                        }
                    }
                }

                IDictionary <string, string> dict = ToDictionary(result);

                if (dict["returnCode"] != "0")
                {
                    // 返回错误时,记录错误信息
                    KernelContext.Log.Error("request:" + url + "?" + httpParams.ToString() + "\nresponse:" + result);
                }

                return(dict["returnCode"]);
            }
            catch (Exception ex)
            {
                KernelContext.Log.Error(ex.ToString());
            }

            return(string.Empty);
        }
        public static async Task <PeerShotMessage> AddUserMessage(string chatHubId, string userId, string peerId, string replyId, string message, bool record)
        {
            var cntx = Cntx;
            UserServiceProxy usvc = new UserServiceProxy();
            var u = await usvc.LoadEntityByKeyAsync(cntx, userId);

            var peer = await usvc.LoadEntityByKeyAsync(cntx, peerId);

            ShortMessageServiceProxy msvc = new ShortMessageServiceProxy();
            PeerShotMessage          m    = new PeerShotMessage();
            var          now = DateTime.UtcNow;
            ShortMessage msg = new ShortMessage
            {
                ID            = Guid.NewGuid().ToString(),
                ApplicationID = AppId,
                TypeID        = 1,
                GroupID       = null,
                FromID        = userId,
                ToID          = peerId,
                ReplyToID     = string.IsNullOrEmpty(replyId) ? null : replyId,
                CreatedDate   = now,
                LastModified  = now,
                MsgText       = message
            };

            if (record)
            {
                var r = await msvc.AddOrUpdateEntitiesAsync(cntx, new ShortMessageSet(), new ShortMessage[] { msg });

                var _msg = r.ChangedEntities[0].UpdatedItem;
                _msg.User_FromID = u;
                m.msg            = GetJsonMessage(_msg, userId, peer, false);
            }
            else
            {
                msg.User_FromID = u;
                m.msg           = GetJsonMessage(msg, userId, peer, false);
            }
            UserAssociationServiceProxy uasvc = new UserAssociationServiceProxy();
            var utop = await uasvc.LoadEntityByKeyAsync(cntx, userId, peerId, ApplicationContext.ChatAssocTypeId);

            if (utop != null)
            {
                utop.InteractCount = utop.InteractCount == null ? 1 : utop.InteractCount + 1;
                utop.LastInteract  = DateTime.UtcNow;
                await uasvc.AddOrUpdateEntitiesAsync(cntx, new UserAssociationSet(), new UserAssociation[] { utop });
            }
            MembershipPlusServiceProxy svc = new MembershipPlusServiceProxy();
            DateTime dt = DateTime.UtcNow.AddMinutes(-ApplicationContext.OnlineUserInactiveTime);
            MemberCallbackServiceProxy mcbsvc = new MemberCallbackServiceProxy();
            var qexpr = new QueryExpresion();

            qexpr.OrderTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "UserID"
                },
                new QToken {
                    TkName = "asc"
                }
            });
            qexpr.FilterTks = new List <QToken>(new QToken[] {
                new QToken {
                    TkName = "HubID == \"" + chatHubId + "\" && ChannelID == \"" + userId + "\" && ConnectionID is not null && IsDisconnected == false"
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "ApplicationID == \"" + AppId + "\" && UserID == \"" + peerId + "\""
                },
                new QToken {
                    TkName = "&&"
                },
                new QToken {
                    TkName = "UserAppMemberRef.LastActivityDate > " + svc.FormatRepoDateTime(dt)
                }
            });
            MemberCallbackServiceProxy cbsv = new MemberCallbackServiceProxy();

            m.peer = (await cbsv.QueryDatabaseAsync(cntx, new MemberCallbackSet(), qexpr)).SingleOrDefault();
            return(m);
        }
 public void Warning(ShortMessage message, Uri url = null, DetailedMessage detailed = null, string instanceName = null)
 {
     Inner.Warning(message, url, detailed, instanceName ?? InstanceName);
 }
Esempio n. 17
0
        public async Task <string> NextPageBlock(string sourceId, string set, string qexpr, string prevlast)
        {
            JavaScriptSerializer jser = new JavaScriptSerializer();
            dynamic       sobj        = jser.DeserializeObject(set) as dynamic;
            EntitySetType type;

            if (Enum.TryParse <EntitySetType>(sobj["set"], out type))
            {
                switch (type)
                {
                case EntitySetType.User:
                {
                    DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
                    DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(User));
                    DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(UserPageBlock));
                    System.IO.MemoryStream     strm = new System.IO.MemoryStream();
                    byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
                    strm.Write(sbf, 0, sbf.Length);
                    strm.Position = 0;
                    var _qexpr            = ser1.ReadObject(strm) as QueryExpresion;
                    UserServiceProxy svc  = new UserServiceProxy();
                    UserSet          _set = new UserSet();
                    _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
                    _set.PageSize_     = int.Parse(sobj["pageSize"]);
                    if (sobj.ContainsKey("setFilter"))
                    {
                        _set.SetFilter = sobj["setFilter"];
                    }
                    User _prevlast = null;
                    if (!string.IsNullOrEmpty(prevlast))
                    {
                        strm = new System.IO.MemoryStream();
                        sbf  = System.Text.Encoding.UTF8.GetBytes(prevlast);
                        strm.Write(sbf, 0, sbf.Length);
                        strm.Position = 0;
                        _prevlast     = ser2.ReadObject(strm) as User;
                    }
                    var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast);

                    strm = new System.IO.MemoryStream();
                    ser3.WriteObject(strm, result);
                    string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                    return(json);
                }

                case EntitySetType.Role:
                {
                    DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
                    DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(Role));
                    DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(RolePageBlock));
                    System.IO.MemoryStream     strm = new System.IO.MemoryStream();
                    byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
                    strm.Write(sbf, 0, sbf.Length);
                    strm.Position = 0;
                    var _qexpr            = ser1.ReadObject(strm) as QueryExpresion;
                    RoleServiceProxy svc  = new RoleServiceProxy();
                    RoleSet          _set = new RoleSet();
                    _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
                    _set.PageSize_     = int.Parse(sobj["pageSize"]);
                    if (sobj.ContainsKey("setFilter"))
                    {
                        _set.SetFilter = sobj["setFilter"];
                    }
                    Role _prevlast = null;
                    if (!string.IsNullOrEmpty(prevlast))
                    {
                        strm = new System.IO.MemoryStream();
                        sbf  = System.Text.Encoding.UTF8.GetBytes(prevlast);
                        strm.Write(sbf, 0, sbf.Length);
                        strm.Position = 0;
                        _prevlast     = ser2.ReadObject(strm) as Role;
                    }
                    var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast);

                    strm = new System.IO.MemoryStream();
                    ser3.WriteObject(strm, result);
                    string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                    return(json);
                }

                case EntitySetType.MemberNotification:
                {
                    DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
                    DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(MemberNotification));
                    DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(MemberNotificationPageBlock));
                    System.IO.MemoryStream     strm = new System.IO.MemoryStream();
                    byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
                    strm.Write(sbf, 0, sbf.Length);
                    strm.Position = 0;
                    var _qexpr = ser1.ReadObject(strm) as QueryExpresion;
                    MemberNotificationServiceProxy svc  = new MemberNotificationServiceProxy();
                    MemberNotificationSet          _set = new MemberNotificationSet();
                    _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
                    _set.PageSize_     = int.Parse(sobj["pageSize"]);
                    if (sobj.ContainsKey("setFilter"))
                    {
                        _set.SetFilter = sobj["setFilter"];
                    }
                    MemberNotification _prevlast = null;
                    if (!string.IsNullOrEmpty(prevlast))
                    {
                        strm = new System.IO.MemoryStream();
                        sbf  = System.Text.Encoding.UTF8.GetBytes(prevlast);
                        strm.Write(sbf, 0, sbf.Length);
                        strm.Position = 0;
                        _prevlast     = ser2.ReadObject(strm) as MemberNotification;
                    }
                    var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast);

                    strm = new System.IO.MemoryStream();
                    ser3.WriteObject(strm, result);
                    string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                    return(json);
                }

                case EntitySetType.ShortMessage:
                {
                    DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(QueryExpresion));
                    DataContractJsonSerializer ser2 = new DataContractJsonSerializer(typeof(ShortMessage));
                    DataContractJsonSerializer ser3 = new DataContractJsonSerializer(typeof(ShortMessagePageBlock));
                    System.IO.MemoryStream     strm = new System.IO.MemoryStream();
                    byte[] sbf = System.Text.Encoding.UTF8.GetBytes(qexpr);
                    strm.Write(sbf, 0, sbf.Length);
                    strm.Position = 0;
                    var _qexpr = ser1.ReadObject(strm) as QueryExpresion;
                    var svc    = new ShortMessageServiceProxy();
                    var _set   = new ShortMessageSet();
                    _set.PageBlockSize = int.Parse(sobj["pageBlockSize"]);
                    _set.PageSize_     = int.Parse(sobj["pageSize"]);
                    if (!sobj.ContainsKey("setFilter"))
                    {
                        throw new Exception("The page is not properly parameterized!");
                    }
                    else
                    {
                        Func <string, string, int> count = (s, p) =>
                        {
                            int _cnt = 0;
                            int i    = 0;
                            while ((i = s.IndexOf(p, i)) != -1)
                            {
                                _cnt++;
                                i += p.Length;
                            }
                            return(_cnt);
                        };
                        string filter = sobj["setFilter"];
                        if (filter.Contains("ToID is null") && filter.Contains("___usergroups___") && count(filter, "||") == 0)
                        {
                            string[] mbgrpIds = await GroupChatViewContext.UserGroupChatMembers(System.Web.HttpContext.Current.User.Identity.GetUserId());

                            if (mbgrpIds == null || mbgrpIds.Length == 0)
                            {
                                throw new Exception(ResourceUtils.GetString("234038e6185f013e25d0213c06f5a0e9", "You are not a member of any chat group."));
                            }
                            string groupexpr = "";
                            foreach (var gid in mbgrpIds)
                            {
                                groupexpr += (groupexpr != "" ? " || " : "") + "GroupID == \"" + gid + "\"";
                            }
                            _set.SetFilter = filter.Replace("___usergroups___", groupexpr);
                        }
                        else if (filter.EndsWith("&& ToID is not null && GroupID is null && ( ToID == \"{0}\" || FromID == \"{0}\" )") && count(filter, "||") == 1)
                        {
                            filter         = string.Format(filter, System.Web.HttpContext.Current.User.Identity.GetUserId());
                            _set.SetFilter = filter;
                        }
                        else
                        {
                            throw new Exception("The page is not properly parameterized!");
                        }
                    }
                    ShortMessage _prevlast = null;
                    if (!string.IsNullOrEmpty(prevlast))
                    {
                        strm = new System.IO.MemoryStream();
                        sbf  = System.Text.Encoding.UTF8.GetBytes(prevlast);
                        strm.Write(sbf, 0, sbf.Length);
                        strm.Position = 0;
                        _prevlast     = ser2.ReadObject(strm) as ShortMessage;
                    }
                    var result = await svc.NextPageBlockAsync(ApplicationContext.ClientContext, _set, _qexpr, _prevlast);

                    strm = new System.IO.MemoryStream();
                    ser3.WriteObject(strm, result);
                    string json = System.Text.Encoding.UTF8.GetString(strm.ToArray());
                    return(json);
                }
                }
            }
            return(null);
        }
Esempio n. 18
0
 /// <summary>
 /// Sends the specified message to the device this queue is performing updates for.
 /// </summary>
 /// <param name="message">The message to send.</param>
 protected virtual void SendMessage(ShortMessage message) => _outputDevice.SendShort(message.Message);
Esempio n. 19
0
 /// <remarks/>
 public void notifyRecivedShortMessagesAsync(ShortMessage[] in0, object userState)
 {
     if ((this.notifyRecivedShortMessagesOperationCompleted == null)) {
         this.notifyRecivedShortMessagesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnnotifyRecivedShortMessagesOperationCompleted);
     }
     this.InvokeAsync("notifyRecivedShortMessages", new object[] {
                 in0}, this.notifyRecivedShortMessagesOperationCompleted, userState);
 }
Esempio n. 20
0
 /// <remarks/>
 public void notifyRecivedShortMessagesAsync(ShortMessage[] in0)
 {
     this.notifyRecivedShortMessagesAsync(in0, null);
 }
Esempio n. 21
0
 public void notifyRecivedShortMessages(ShortMessage[] in0)
 {
     this.Invoke("notifyRecivedShortMessages", new object[] {
                 in0});
 }
Esempio n. 22
0
 /// <remarks/>
 public System.IAsyncResult BeginnotifyRecivedShortMessages(ShortMessage[] in0, System.AsyncCallback callback, object asyncState)
 {
     return this.BeginInvoke("notifyRecivedShortMessages", new object[] {
                 in0}, callback, asyncState);
 }
Esempio n. 23
0
 public override void OnSMSReceived(ShortMessage msg)
 {
     base.OnSMSReceived(msg);
     txtResponse.Text += "Tin nhắn từ " + msg.Sender + ", nội dung: " + msg.Message;
 }
Esempio n. 24
0
        private void ShowMessageGM862(ShortMessage data)
        {
            setFullBar(false);
                // Received message
                string toWrite = "";
                toWrite = data.Message;
                string dt = data.Sent;
                if (data.Message.IndexOf("$GPRMC") > -1)
                {
                    validGPS(data.Message, data.Sender, dt, true);
                    Output(dt + " Ricevuto posizione del terminale: " + data.Sender);
                    makeLog(data.Sender, "Ricevuto posizione del terminale: " + data.Sender);
                    saveNewPosition(data.Sender, data.Message);
                }
                if (data.Message.IndexOf("KTA") > -1 || data.Message.IndexOf("POS") > -1 || data.Message.IndexOf("LOGIN") > -1)
                {
                    if (data.Message.IndexOf("LOGIN") > -1)
                    {
                        string login = "******" + searchDevice(data.Sender).Description + " riuscito.";
                        makeLog(data.Sender, login);
                        frmAllarm.addNewAllarm(dt, data.Sender, login);
                        smartrack sm = searchDevice(data.Sender);
                        Output(dt + " Login del dispositivo: " + sm.Description + " (" + data.Sender + ")");
                    }
                    else
                    {
                        parseKFTString(data.Message, data.Sender, dt, true);
                        Output(dt + " Ricevuto posizione del terminale: " + data.Sender);
                        makeLog(data.Sender, "Ricevuto posizione del terminale: " + data.Sender);
                        saveNewPosition(data.Sender, data.Message);
                        frmAllarm.addNewAllarm(dt, data.Sender, "Ricevuto posizione del terminale: " + data.Sender);
                    }
                }
                if (data.Message.IndexOf("\nHP=") > -1)
                {
                    parseCP100string(data.Message, data.Sender, dt, true);
                    makeLog(data.Sender, "Ricevuto posizione del terminale: " + data.Sender);
                    saveNewPosition(data.Sender, data.Message);
                }
                if (data.Message.IndexOf("VKT%") > -1)
                {
                    string TipoMessaggio = data.Message.Substring(data.Message.LastIndexOf("VKT%") + 4, 4);
                    string[] Mess = data.Message.Split(':');
                    string Messaggio = Mess[Mess.Length - 1];
                    string m = "";
                    m = getMessage(Messaggio);
                    if (m != "")
                    {
                        frmAllarm.addNewAllarm(dt, data.Sender, m);
                    }
                }

                makeLog(data.Sender, toWrite);
                if (Mode == 1)
                    showFlotta();
                return;
        }
        public List <ShortMessageRequest> LoadMany(ISqlConnectionInfo connection, SqlQueryParameters parameters)
        {
            IDatabase database = connection.Database;

            if (database == null)
            {
                throw new ArgumentNullException("database", "Error initializing database connection.");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            string sqlCmdText = string.Empty;

            try
            {
                sqlCmdText = "SELECT {0} " +
                             ShortMessageRequestTable.GetColumnNames("[smr]") +
                             (this.Depth > 0 ? "," + ShortMessageTable.GetColumnNames("[smr_sm]") : string.Empty) +
                             (this.Depth > 1 ? "," + ActionContextTable.GetColumnNames("[smr_sm_ac]") : string.Empty) +
                             (this.Depth > 1 ? "," + ServiceTable.GetColumnNames("[smr_sm_s]") : string.Empty) +
                             (this.Depth > 1 ? "," + MobileOperatorTable.GetColumnNames("[smr_sm_mo]") : string.Empty) +
                             (this.Depth > 1 ? "," + CustomerTable.GetColumnNames("[smr_sm_c]") : string.Empty) +
                             (this.Depth > 0 ? "," + UserTable.GetColumnNames("[smr_u]") : string.Empty) +
                             (this.Depth > 1 ? "," + UserTypeTable.GetColumnNames("[smr_u_ut]") : string.Empty) +
                             " FROM [core].[ShortMessageRequest] AS [smr] ";
                if (this.Depth > 0)
                {
                    sqlCmdText += "INNER  JOIN [core].[ShortMessage] AS [smr_sm] ON [smr].[ShortMessageID] = [smr_sm].[ShortMessageID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[ActionContext] AS [smr_sm_ac] ON [smr_sm].[ActionContextID] = [smr_sm_ac].[ActionContextID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[Service] AS [smr_sm_s] ON [smr_sm].[ServiceID] = [smr_sm_s].[ServiceID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[MobileOperator] AS [smr_sm_mo] ON [smr_sm].[MobileOperatorID] = [smr_sm_mo].[MobileOperatorID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "INNER  JOIN [core].[Customer] AS [smr_sm_c] ON [smr_sm].[CustomerID] = [smr_sm_c].[CustomerID] ";
                }
                if (this.Depth > 0)
                {
                    sqlCmdText += "INNER  JOIN [core].[User] AS [smr_u] ON [smr].[UserID] = [smr_u].[UserID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "INNER  JOIN [core].[UserType] AS [smr_u_ut] ON [smr_u].[UserTypeID] = [smr_u_ut].[UserTypeID] ";
                }


                sqlCmdText = parameters.BuildQuery(sqlCmdText);
                SqlCommand sqlCmd = database.Add(sqlCmdText) as SqlCommand;
                foreach (KeyValuePair <string, object> argument in parameters.Arguments)
                {
                    sqlCmd.Parameters.AddWithValue("@" + argument.Key, argument.Value);
                }

                SqlDataReader sqlReader = database.Add(sqlCmd) as SqlDataReader;

                if (!sqlReader.HasRows || !sqlReader.Read())
                {
                    IMessageBuilder builder = new DbLogMessageBuilder(new LogErrorCode("smr", "customloadmany", "notfound"), "ShortMessageRequest list could not be loaded using custom logic as no items were found.", sqlCmdText, this, connection, parameters);
                    if (this.Logger.IsDebugEnabled)
                    {
                        this.Logger.Debug(builder.ToString());
                    }
                    sqlReader.Close();
                    return(new List <ShortMessageRequest>());
                }

                SqlQuery query = new SqlQuery(sqlReader);

                ShortMessageRequestTable smrTable       = new ShortMessageRequestTable(query);
                ShortMessageTable        smr_smTable    = (this.Depth > 0) ? new ShortMessageTable(query) : null;
                ActionContextTable       smr_sm_acTable = (this.Depth > 1) ? new ActionContextTable(query) : null;
                ServiceTable             smr_sm_sTable  = (this.Depth > 1) ? new ServiceTable(query) : null;
                MobileOperatorTable      smr_sm_moTable = (this.Depth > 1) ? new MobileOperatorTable(query) : null;
                CustomerTable            smr_sm_cTable  = (this.Depth > 1) ? new CustomerTable(query) : null;
                UserTable     smr_uTable    = (this.Depth > 0) ? new UserTable(query) : null;
                UserTypeTable smr_u_utTable = (this.Depth > 1) ? new UserTypeTable(query) : null;

                List <ShortMessageRequest> result = new List <ShortMessageRequest>();
                do
                {
                    ActionContext       smr_sm_acObject = (this.Depth > 1) ? smr_sm_acTable.CreateInstance() : null;
                    Service             smr_sm_sObject  = (this.Depth > 1) ? smr_sm_sTable.CreateInstance() : null;
                    MobileOperator      smr_sm_moObject = (this.Depth > 1) ? smr_sm_moTable.CreateInstance() : null;
                    Customer            smr_sm_cObject  = (this.Depth > 1) ? smr_sm_cTable.CreateInstance() : null;
                    ShortMessage        smr_smObject    = (this.Depth > 0) ? smr_smTable.CreateInstance(smr_sm_acObject, smr_sm_sObject, smr_sm_moObject, smr_sm_cObject) : null;
                    UserType            smr_u_utObject  = (this.Depth > 1) ? smr_u_utTable.CreateInstance() : null;
                    User                smr_uObject     = (this.Depth > 0) ? smr_uTable.CreateInstance(smr_u_utObject) : null;
                    ShortMessageRequest smrObject       = (this.Depth > -1) ? smrTable.CreateInstance(smr_smObject, smr_uObject) : null;
                    result.Add(smrObject);
                } while (sqlReader.Read());
                sqlReader.Close();

                return(result);
            }
            catch (Exception ex)
            {
                database.HandleException(ex);
                IMessageBuilder builder = new DbLogMessageBuilder(new LogErrorCode("smr", "customloadmany", "exception"), "ShortMessageRequest list could not be loaded using custom logic. See exception for details.", sqlCmdText, ex, this, connection, parameters);
                if (this.Logger.IsErrorEnabled)
                {
                    this.Logger.Error(builder.ToString(), ex);
                }
                throw new DataOperationException(DataOperation.Load, "ShortMessageRequest", "Exception while loading (custom/many) ShortMessageRequest object from database. See inner exception for details.", ex);
            }
        }
        protected override ShortMessageRequest LoadInternal(ISqlConnectionInfo connection, int id)
        {
            IDatabase database = connection.Database;

            if (database == null)
            {
                throw new ArgumentNullException("database", "Error initializing database connection.");
            }
            string sqlCmdText = string.Empty;

            try
            {
                sqlCmdText = "SELECT " +
                             ShortMessageRequestTable.GetColumnNames("[smr]") +
                             (this.Depth > 0 ? "," + ShortMessageTable.GetColumnNames("[smr_sm]") : string.Empty) +
                             (this.Depth > 1 ? "," + ActionContextTable.GetColumnNames("[smr_sm_ac]") : string.Empty) +
                             (this.Depth > 1 ? "," + ServiceTable.GetColumnNames("[smr_sm_s]") : string.Empty) +
                             (this.Depth > 1 ? "," + MobileOperatorTable.GetColumnNames("[smr_sm_mo]") : string.Empty) +
                             (this.Depth > 1 ? "," + CustomerTable.GetColumnNames("[smr_sm_c]") : string.Empty) +
                             (this.Depth > 0 ? "," + UserTable.GetColumnNames("[smr_u]") : string.Empty) +
                             (this.Depth > 1 ? "," + UserTypeTable.GetColumnNames("[smr_u_ut]") : string.Empty) +
                             " FROM [core].[ShortMessageRequest] AS [smr] ";
                if (this.Depth > 0)
                {
                    sqlCmdText += "INNER  JOIN [core].[ShortMessage] AS [smr_sm] ON [smr].[ShortMessageID] = [smr_sm].[ShortMessageID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[ActionContext] AS [smr_sm_ac] ON [smr_sm].[ActionContextID] = [smr_sm_ac].[ActionContextID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[Service] AS [smr_sm_s] ON [smr_sm].[ServiceID] = [smr_sm_s].[ServiceID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "LEFT OUTER  JOIN [core].[MobileOperator] AS [smr_sm_mo] ON [smr_sm].[MobileOperatorID] = [smr_sm_mo].[MobileOperatorID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "INNER  JOIN [core].[Customer] AS [smr_sm_c] ON [smr_sm].[CustomerID] = [smr_sm_c].[CustomerID] ";
                }
                if (this.Depth > 0)
                {
                    sqlCmdText += "INNER  JOIN [core].[User] AS [smr_u] ON [smr].[UserID] = [smr_u].[UserID] ";
                }
                if (this.Depth > 1)
                {
                    sqlCmdText += "INNER  JOIN [core].[UserType] AS [smr_u_ut] ON [smr_u].[UserTypeID] = [smr_u_ut].[UserTypeID] ";
                }
                sqlCmdText += "WHERE [smr].[ShortMessageRequestID] = @ShortMessageRequestID;";

                SqlCommand sqlCmd = database.Add(sqlCmdText) as SqlCommand;
                sqlCmd.Parameters.AddWithValue("@ShortMessageRequestID", id);
                SqlDataReader sqlReader = database.Add(sqlCmd) as SqlDataReader;

                if (!sqlReader.HasRows || !sqlReader.Read())
                {
                    IMessageBuilder builder = new DbLogMessageBuilder(new LogErrorCode("smr", "loadinternal", "notfound"), "ShortMessageRequest could not be loaded by id as it was not found.", sqlCmdText, this, connection, id);
                    if (this.Logger.IsWarnEnabled)
                    {
                        this.Logger.Warn(builder.ToString());
                    }
                    sqlReader.Close();
                    return(null);
                }

                SqlQuery query = new SqlQuery(sqlReader);

                ShortMessageRequestTable smrTable       = new ShortMessageRequestTable(query);
                ShortMessageTable        smr_smTable    = (this.Depth > 0) ? new ShortMessageTable(query) : null;
                ActionContextTable       smr_sm_acTable = (this.Depth > 1) ? new ActionContextTable(query) : null;
                ServiceTable             smr_sm_sTable  = (this.Depth > 1) ? new ServiceTable(query) : null;
                MobileOperatorTable      smr_sm_moTable = (this.Depth > 1) ? new MobileOperatorTable(query) : null;
                CustomerTable            smr_sm_cTable  = (this.Depth > 1) ? new CustomerTable(query) : null;
                UserTable     smr_uTable    = (this.Depth > 0) ? new UserTable(query) : null;
                UserTypeTable smr_u_utTable = (this.Depth > 1) ? new UserTypeTable(query) : null;


                ActionContext       smr_sm_acObject = (this.Depth > 1) ? smr_sm_acTable.CreateInstance() : null;
                Service             smr_sm_sObject  = (this.Depth > 1) ? smr_sm_sTable.CreateInstance() : null;
                MobileOperator      smr_sm_moObject = (this.Depth > 1) ? smr_sm_moTable.CreateInstance() : null;
                Customer            smr_sm_cObject  = (this.Depth > 1) ? smr_sm_cTable.CreateInstance() : null;
                ShortMessage        smr_smObject    = (this.Depth > 0) ? smr_smTable.CreateInstance(smr_sm_acObject, smr_sm_sObject, smr_sm_moObject, smr_sm_cObject) : null;
                UserType            smr_u_utObject  = (this.Depth > 1) ? smr_u_utTable.CreateInstance() : null;
                User                smr_uObject     = (this.Depth > 0) ? smr_uTable.CreateInstance(smr_u_utObject) : null;
                ShortMessageRequest smrObject       = smrTable.CreateInstance(smr_smObject, smr_uObject);
                sqlReader.Close();

                return(smrObject);
            }
            catch (Exception ex)
            {
                database.HandleException(ex);
                IMessageBuilder builder = new DbLogMessageBuilder(new LogErrorCode("smr", "loadinternal", "exception"), "ShortMessageRequest could not be loaded by id. See exception for details.", sqlCmdText, ex, this, connection, id);
                if (this.Logger.IsErrorEnabled)
                {
                    this.Logger.Error(builder.ToString(), ex);
                }
                throw new DataOperationException(DataOperation.Load, "ShortMessageRequest", "Exception while loading ShortMessageRequest object from database. See inner exception for details.", ex);
            }
        }
        /// <summary>发送短信</summary>
        /// <param name="message">短信</param>
        public string Send(ShortMessage message)
        {
            // url:http://smsapi.ums86.com:8899/sms/Api/Send.do?SpCode={0}&amp;LoginName={1}&amp;Password={2}&amp;MessageContent={5}&amp;UserNumber={4}&amp;SerialNumber={6}&amp;ScheduleTime=&amp;f=1

            string result = null;

            string url = string.Format(SMSConfigurationView.Instance.SendUrl,
                                       SMSConfigurationView.Instance.EnterpriseCode,
                                       SMSConfigurationView.Instance.Username,
                                       SMSConfigurationView.Instance.Password,
                                       message.MessageContent,
                                       message.PhoneNumber,
                                       message.SerialNumber).Trim();


            int markIndex = url.IndexOf("?");

            Uri uri = new Uri(url.Substring(0, markIndex));

            byte[] data = Encoding.GetEncoding("GBK").GetBytes(url.Substring(markIndex + 1, url.Length - markIndex - 1));

            try
            {
                WebRequest request = WebRequest.Create(uri);

                request.Method        = "POST";
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;

                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                    stream.Close();
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            var reader = new StreamReader(stream, Encoding.Default);
                            result = reader.ReadToEnd();
                        }
                    }
                }

                StringDictionary dict = GetResult(result);

                if (dict["result"] != "0")
                {
                    // 返回错误时,记录错误信息
                    KernelContext.Log.Error("request:" + url + "\nresponse:" + result);
                }

                return(dict["result"]);
            }
            catch (Exception ex)
            {
                KernelContext.Log.Error(ex.ToString());
            }

            return(string.Empty);
        }
Esempio n. 28
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            try
            {
                //Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");

                String inputAux = input;
                inputAux = inputAux.Replace("\r\n", @"\x");
                inputAux = inputAux.Replace("\n", "");
                inputAux = inputAux.Replace(@"\x", "\r\n");
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n"); ;
                Match m = r.Match(inputAux);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();
                    //msg.Index = int.Parse(m.Groups[1].Value);
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = m.Groups[3].Value;
                    msg.Alphabet = m.Groups[4].Value;
                    msg.Sent = m.Groups[5].Value;
                    msg.Message = m.Groups[6].Value;
                    messages.Add(msg);

                    m = m.NextMatch();
                }

            }
            catch (Exception ex)
            {
                //_logger.Error("ParseMessages", ex);
                _causa = ex.Message;
                Console.WriteLine("ParseMessages " + ex.Message);
            }
            return messages;
        }
 /// <summary>·¢ËͶÌÐÅ</summary>
 /// <param name="message">¶ÌÐÅ</param>
 public string Send(ShortMessage message)
 {
     return(string.Empty);
 }
 public void CannotRun(ShortMessage message, Uri url = null, DetailedMessage detailed = null, string instanceName = null)
 {
     Inner.CannotRun(message, url, detailed, instanceName ?? InstanceName);
 }
Esempio n. 31
0
 private MidiMessage HandleShortMessage(ShortMessage message)
 {
     return(new ShortMessageAdapter(message));
 }
        public void CannotRun(ShortMessage message, Uri url, DetailedMessage detailed, string instanceName)
        {
            Assert.ArgumentNotNull(message, nameof(message));

            AddResult(TestResultState.CannotRun, url, message, detailed, instanceName);
        }
Esempio n. 33
0
 /// <summary>
 /// 添加短信发送历史
 /// </summary>
 /// <param name="l">短信发送历史</param>
 public void AddMessage(ShortMessage l)
 {
     l.Created = DateTime.Now;
     l.ID      = We7Helper.CreateNewID();
     Assistant.Insert(l);
 }
Esempio n. 34
0
        private List <MidiTimestampPair> ReadMidiMessages(MidiCommandHeader midiCommandHeader, DataInputStream midiInputStream)
        {
            List <MidiTimestampPair> result = new List <MidiTimestampPair>();

            int status = -1;
            ByteArrayOutputStream sysexDataStream = null;
            int deltaTimeSum = midiCommandHeader.RtpHeader.Timestamp;

            while (midiInputStream.Available() > 0)
            {
                int deltaTime;
                if (midiCommandHeader.Z)
                {
                    deltaTime = ReadDeltaTime(midiInputStream);
                }
                else
                {
                    deltaTime = 0;
                }
                deltaTimeSum += deltaTime;

                byte midiOctet1          = (byte)midiInputStream.ReadByte();
                bool systemCommonMessage = (midiOctet1 & 0xF0) == 0xF0;
                int  possibleStatus      = midiOctet1 & 0xFF;
                if (systemCommonMessage)
                {
                    if (midiOctet1 == (byte)SysexMessage.SYSTEM_EXCLUSIVE)
                    {
                        sysexDataStream = new ByteArrayOutputStream();
                        sysexDataStream.Write(midiOctet1);
                        bool partial = ReadSysexData(midiInputStream, sysexDataStream);
                        if (!partial)
                        {
                            result.Add(new MidiTimestampPair(deltaTimeSum,
                                                             new SysexMessage(sysexDataStream.ToByteArray(), sysexDataStream.Size())));
                        }
                    }
                    else
                    if (midiOctet1 == (byte)SysexMessage.SPECIAL_SYSTEM_EXCLUSIVE)
                    {
                        bool partial = ReadSysexData(midiInputStream, sysexDataStream);
                        if (!partial)
                        {
                            result.Add(new MidiTimestampPair(deltaTimeSum,
                                                             new SysexMessage(sysexDataStream.ToByteArray(), sysexDataStream.Size())));
                        }
                    }
                    else
                    if (midiOctet1 == (byte)0xF4)
                    {
                        sysexDataStream.Reset();
                    }
                    else
                    {
                        ShortMessage shortMessage = null;
                        switch (possibleStatus)
                        {
                        case ShortMessage.TUNE_REQUEST:
                        case ShortMessage.TIMING_CLOCK:
                        case ShortMessage.START:
                        case ShortMessage.STOP:
                        case ShortMessage.ACTIVE_SENSING:
                        case ShortMessage.SYSTEM_RESET:
                            status       = possibleStatus;
                            shortMessage = new ShortMessage((byte)(status & 0xFF));
                            break;

                        case ShortMessage.MIDI_TIME_CODE:
                        case ShortMessage.SONG_SELECT:
                            status       = possibleStatus;
                            shortMessage = new ShortMessage((byte)(status & 0xFF), (byte)midiInputStream.ReadByte());
                            break;

                        case ShortMessage.SONG_POSITION_POINTER:
                            status       = possibleStatus;
                            shortMessage = new ShortMessage((byte)(status & 0xFF), (byte)midiInputStream.ReadByte(),
                                                            (byte)midiInputStream.ReadByte());
                            break;

                        default:
                            Log.Error("RtpMidi", "Invalid Message-status: {}", possibleStatus);
                            break;
                        }
                        if (shortMessage != null)
                        {
                            result.Add(new MidiTimestampPair(deltaTimeSum, shortMessage));
                        }
                    }
                }
                else
                {
                    ShortMessage shortMessage = null;
                    switch (midiOctet1 & 0xF0)
                    {
                    case ShortMessage.NOTE_OFF:
                    case ShortMessage.NOTE_ON:
                    case ShortMessage.POLY_PRESSURE:
                    case ShortMessage.CONTROL_CHANGE:
                    case ShortMessage.PITCH_BEND:
                        status       = possibleStatus;
                        shortMessage = new ShortMessage((byte)(status & 0xFF), (byte)midiInputStream.ReadByte(),
                                                        (byte)midiInputStream.ReadByte());
                        break;

                    case ShortMessage.PROGRAM_CHANGE:
                    case ShortMessage.CHANNEL_PRESSURE:
                        status       = possibleStatus;
                        shortMessage = new ShortMessage((byte)(status & 0xFF), (byte)midiInputStream.ReadByte());
                        break;

                    default:
                        Log.Error("rtpMidi", "Invalid ShortMessage-status: {}", midiOctet1 & 0xF0);
                        break;
                    }
                    if (shortMessage != null)
                    {
                        result.Add(new MidiTimestampPair(deltaTimeSum, shortMessage));
                    }
                }
            }
            return(result);
        }
Esempio n. 35
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();

            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
                Match m = r.Match(input);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();

                    //msg.Index = int.Parse(m.Groups[1].Value);
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = m.Groups[3].Value;
                    msg.Alphabet = m.Groups[4].Value;
                    msg.Sent = m.Groups[5].Value;
                    msg.Message = m.Groups[6].Value;

                    messages.Add(msg);

                    m = m.NextMatch();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return messages;
        }
Esempio n. 36
0
        public SarifErrorListItem(Run run, Result result, string logFilePath, ProjectNameCache projectNameCache) : this()
        {
            if (!SarifViewerPackage.IsUnitTesting)
            {
#pragma warning disable VSTHRD108 // Assert thread affinity unconditionally
                ThreadHelper.ThrowIfNotOnUIThread();
#pragma warning restore VSTHRD108 // Assert thread affinity unconditionally
            }
            _runId = CodeAnalysisResultManager.Instance.CurrentRunId;
            ReportingDescriptor rule = result.GetRule(run);
            Tool         = run.Tool.ToToolModel();
            Rule         = rule.ToRuleModel(result.RuleId);
            Invocation   = run.Invocations?[0]?.ToInvocationModel();
            Message      = result.GetMessageText(rule, concise: false).Trim();
            ShortMessage = result.GetMessageText(rule, concise: true).Trim();
            if (!Message.EndsWith("."))
            {
                ShortMessage = ShortMessage.TrimEnd('.');
            }
            FileName    = result.GetPrimaryTargetFile(run);
            ProjectName = projectNameCache.GetName(FileName);
            Category    = result.GetCategory();
            Region      = result.GetPrimaryTargetRegion();
            Level       = result.Level != FailureLevel.Warning ? result.Level : Rule.FailureLevel;

            if (result.Suppressions?.Count > 0)
            {
                VSSuppressionState = VSSuppressionState.Suppressed;
            }

            LogFilePath = logFilePath;

            if (Region != null)
            {
                LineNumber   = Region.StartLine;
                ColumnNumber = Region.StartColumn;
            }

            Tool             = run.Tool.ToToolModel();
            Rule             = rule.ToRuleModel(result.RuleId);
            Invocation       = run.Invocations?[0]?.ToInvocationModel();
            WorkingDirectory = Path.Combine(Path.GetTempPath(), _runId.ToString());

            if (result.Locations?.Any() == true)
            {
                // Adding in reverse order will make them display in the correct order in the UI.
                for (int i = result.Locations.Count - 1; i >= 0; --i)
                {
                    Locations.Add(result.Locations[i].ToLocationModel(run));
                }
            }

            if (result.RelatedLocations?.Any() == true)
            {
                for (int i = result.RelatedLocations.Count - 1; i >= 0; --i)
                {
                    RelatedLocations.Add(result.RelatedLocations[i].ToLocationModel(run));
                }
            }

            if (result.CodeFlows != null)
            {
                foreach (CodeFlow codeFlow in result.CodeFlows)
                {
                    CallTree callTree = codeFlow.ToCallTree(run);
                    if (callTree != null)
                    {
                        CallTrees.Add(callTree);
                    }
                }

                CallTrees.Verbosity = 100;
                CallTrees.IntelligentExpand();
            }

            if (result.Stacks != null)
            {
                foreach (Stack stack in result.Stacks)
                {
                    Stacks.Add(stack.ToStackCollection());
                }
            }

            if (result.Fixes != null)
            {
                foreach (Fix fix in result.Fixes)
                {
                    Fixes.Add(fix.ToFixModel());
                }
            }
        }
Esempio n. 37
0
        public ActionResult API()
        {
            string orderCode = Server.UrlDecode(Request.QueryString["orderid"]);//订单编号
            string strMsg = "";
            SqlTransaction transaction = null;

            try
            {
                string username = Server.UrlDecode(Request.QueryString["username"]);//ERP昵称
                string password = Server.UrlDecode(Request.QueryString["password"]);//ERP密码
                string key = Server.UrlDecode(Request.QueryString["key"]);//公钥
                string sign = Server.UrlDecode(Request.QueryString["sign"]);//检验码
                string method = Server.UrlDecode(Request.QueryString["method"]);//调用接口

                #region 访问日志

                try
                {
                    new OrderERPLogService().AddHwLog(new Hw_Log { Content = Request.Url.ToString(), Number = orderCode }, null);
                    LogUtils.Log(string.Format("成功写入ERP系统访问日志,订单编号:{0},日志信息:{1}", orderCode, Request.Url.ToString()), "ERP订单回写", Category.Error);
                }
                catch (Exception exception)
                {
                    LogUtils.Log(string.Format("写入ERP系统访问日志失败,订单编号:{0},日志信息:{1},错误信息:{2}", orderCode, Request.Url.ToString(), exception.Message + "/" + exception.InnerException), "ERP订单回写", Category.Error);
                }

                #endregion

                #region 基本参数验证
                if (string.IsNullOrEmpty(username))
                {
                    strMsg = SetMsg("0", "昵称不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(orderCode))
                {
                    strMsg = SetMsg("0", "订单不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (username != "hongware")
                {
                    strMsg = SetMsg("0", "昵称不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(password))
                {
                    strMsg = SetMsg("0", "密码不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (password != "bir19ming19ham")
                {
                    strMsg = SetMsg("0", "密码不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(key))
                {
                    strMsg = SetMsg("0", "公钥不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (key != "g1w9j1r9w")
                {
                    strMsg = SetMsg("0", "公钥不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(sign))
                {
                    strMsg = SetMsg("0", "检验码不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(orderCode))
                {
                    strMsg = SetMsg("0", "订单编号不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                string sign_Md5 = Encrypt.HwErpMd5(username + password + orderCode + key);
                if (sign != sign_Md5)
                {
                    strMsg = SetMsg("0", "检验码不正确", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                if (string.IsNullOrEmpty(method))
                {
                    strMsg = SetMsg("0", "调用方法名不能为空", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                method = method.ToLower();
                #endregion

                #region 订单当前状态

                var orderService = new OrderService();
                var orderTracking = new OrderStatusTrackingService();

                var order = orderService.QueryByOrderCode(orderCode);

                if (order == null || order.ID < 1)
                {
                    strMsg = SetMsg("0", "未查到此订单号,请核实", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);
                }
                int OrderID = order.ID;
                int State = order.Status;
                #endregion

                if (method == "api.order.send")
                {
                    #region 订单发货
                    if (State == 0)
                    {
                        strMsg = SetMsg("0", "订单还未确认", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 2)
                    {
                        strMsg = SetMsg("0", "订单已发货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 3)
                    {
                        strMsg = SetMsg("0", "订单已签收", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 4 || State == 5 || State == 8)
                    {
                        strMsg = SetMsg("0", "订单已取消", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    string expressno = string.Empty;
                    expressno = Server.UrlDecode(Request.QueryString["expressno"]);//快递代码
                    string expressnum = Server.UrlDecode(Request.QueryString["expressnum"]);//快递单号
                    string deliverydate = Server.UrlDecode(Request.QueryString["deliverydate"]);//发货日期

                    #region 参数验证
                    if (string.IsNullOrEmpty(expressno))
                    {
                        strMsg = SetMsg("0", "快递代码不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    if (string.IsNullOrEmpty(expressnum))
                    {
                        strMsg = SetMsg("0", "快递单号不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    if (string.IsNullOrEmpty(deliverydate))
                    {
                        strMsg = SetMsg("0", "发货日期不能为空", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    #endregion

                    Config_Delivery_Corporation deliveryCorporation = null;

                    #region 更新订单发货状态
                    /*
                     订单发货:
                     * 1.更改订单状态,
                     * 2.更改订单跟踪状态
                     */
                    try
                    {
                        var deliveryCorporations = new ConfigDeliveryCorporationService().QueryAllConfigDeliveryCorporations();

                        if (deliveryCorporations != null && deliveryCorporations.Count > 1)
                        {
                            deliveryCorporation =
                                deliveryCorporations.Find(dc => expressno.Equals(dc.Number, StringComparison.OrdinalIgnoreCase));

                        }

                        if (deliveryCorporation == null)
                        {
                            deliveryCorporation = new Config_Delivery_Corporation();
                            LogUtils.Log("没有获取到代号为:" + expressno.ToUpper() + "的配送公司", "API", Category.Warn);
                        }

                        var tracking = new Order_Status_Tracking();

                        tracking.MailNo = expressnum;
                        tracking.ExpressNumber = expressno.ToUpper();
                        tracking.OrderID = OrderID;
                        tracking.Status = 2;
                        tracking.EmployeeID = 0;
                        tracking.UserID = 0;
                        tracking.Remark = string.Format(
                            "订单已发货,配送单位:{0} {1}; 快递单号:{2}",
                            deliveryCorporation.Name,
                            deliveryCorporation.URL,
                            expressnum);

                        tracking.CreateTime = Convert.ToDateTime(deliverydate);

                        orderService.SqlServer.BeginTransaction();
                        transaction = orderService.SqlServer.Transaction;

                        orderTracking.Add(tracking, transaction);

                        order.Status = 2;
                        order.DeliveryCorporationID = deliveryCorporation.ID;
                        orderService.Edit(order, transaction);

                        transaction.Commit();
                    }
                    catch (Exception exception)
                    {
                        if (transaction != null)
                        {
                            transaction.Rollback();
                        }

                        LogUtils.Log(
                            string.Format(
                                "[Order_ERP]ERP回写发货订单时发生错误,订单编号:{0},错误消息:{1}",
                                orderCode,
                                exception.Message + "/" + exception.InnerException),
                            "[Order_ERP]ERP订单发货回写官网",
                            Category.Error);

                        strMsg = SetMsg("0", "更新订单发货状态发生异常", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    finally
                    {
                        if (transaction != null && transaction.Connection != null
                            && transaction.Connection.State != ConnectionState.Closed)
                        {
                            transaction.Connection.Close();
                        }
                    }
                    #endregion

                    #region 短信发送

                    try
                    {
                        var orderReceiver = new UserReceiveAddressService().QueryByID(order.UserID);

                        if (orderReceiver != null && orderReceiver.Mobile != null)
                        {
                            var moList = new List<string>();
                            moList.Add(orderReceiver.Mobile);

                            var sm = new ShortMessage
                            {
                                ReceiveMobiles = moList,
                                Content =
                                    string.Format(
                                        "亲爱的购酒网会员,您的订单(订单号:{0})支付方式为:{1},已经发货,配送公司:{2}, 单号:{3}。请注意保持手机畅通。",
                                        orderCode,
                                        order.PaymentMethodName,
                                        deliveryCorporation.Name,
                                        deliveryCorporation.Number)
                            };
                            sm.Send();
                            LogUtils.Log(
                                "用户:" + orderReceiver.Consignee + "电话:" + orderReceiver.Mobile + "成功发送短信",
                                "SendSms",
                                Category.Info,
                                Session.SessionID);

                        }
                        else
                        {
                            LogUtils.Log("[Order_ERP]由于没有获取到订单收货人或收货人的手机号不存在,因此订单(" + order.OrderCode + ")发货,未发送通知短信", "[Order_ERP]订单发货回写发送短信SendSms", Category.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtils.Log("[Order_ERP]ERP订单发货发送短信发生错误,错误消息:" + ex.Message + "/" + ex.InnerException, "[Order_ERP]订单发货回写发送短信SendSms", Category.Error);
                    }

                    #endregion

                    strMsg = SetMsg("1", "订单状态更新成功", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);

                    #endregion
                }
                else if (method == "api.order.cancel")
                {
                    #region 订单取
                    if (State == 0)
                    {
                        strMsg = SetMsg("0", "订单还未确认", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 2)
                    {
                        strMsg = SetMsg("0", "订单已发货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 3)
                    {
                        strMsg = SetMsg("0", "订单已确认收货", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }
                    else if (State == 4 || State == 5 || State == 8)
                    {
                        strMsg = SetMsg("0", "订单已取消", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    try
                    {
                        orderService.SetInvalidByERP(order.ID, "订单作废");
                    }
                    catch (Exception exception)
                    {

                        LogUtils.Log(
                            string.Format(
                                "[Order_ERP]ERP订单取消回写发生错误,订单号:{0},错误消息:{1}",
                                orderCode,
                                exception.Message + "/" + exception.InnerException),
                            "[Order_ERP]ERP订单取消回写",
                            Category.Error);

                        strMsg = SetMsg("0", "订单作废发生错误", orderCode);
                        //Response.Write(strMsg);
                        return this.Content(strMsg);
                    }

                    strMsg = SetMsg("1", "订单作废成功", orderCode);
                    //Response.Write(strMsg);
                    return this.Content(strMsg);

                    #endregion
                }

                strMsg = SetMsg("0", "调用方法名不正确", orderCode);
                //Response.Write(strMsg);
                return this.Content(strMsg);
            }
            catch (Exception)
            {
                strMsg = SetMsg("0", "订单回写发生异常", orderCode);
                //Response.Write(strMsg);
                return this.Content(strMsg);
            }
        }
Esempio n. 38
0
        private void BindPure()
        {
            if (this.userid > 0)
            {
                base.AddErrLine("当前已有用户登录,无法注册");
                return;
            }
            //if (this.config.Regstatus < 1 || this.cloudconfig.Allowconnectregister == 0)
            //{
            //    base.AddErrLine("论坛当前禁止新的QQ会员登录");
            //    return;
            //}

            var connect = QzoneConnectContext.Current;

            var storedToken = QzoneConnectToken.FindByOpenId(connect.Token.OpenId);

            if (storedToken != null)
            {
                var url = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Host, BaseConfigInfo.Current.Forumpath + qzconfig.QzoneConnectPage + "?act=access");
                XTrace.WriteLine("BindNew -> redirect -> " + url);
                Response.Redirect(url);
                return;
            }

            var  nickName = connect.GetQqNickname();
            User userInfo = this.CreateUser(connect.Token.AccessToken.Substring(0, 10), nickName, "", "");

            //修复bug,保存后才能有userid
            connect.Token.Uid = userInfo.ID;

            // 更新用户名为友好名称,优先使用QQ昵称
            if (BBX.Entity.User.FindByName(nickName) == null)
            {
                userInfo.Name = nickName;
            }
            else
            {
                userInfo.Name = "QQ#" + userInfo.ID;
            }
            userInfo.Update();

            connect.Token.IsPure = true;
            connect.Token.Save();
            //QzoneConnectToken.Insert(connect.Token);

            XTrace.WriteLine("BindPure -> success, uid=" + connect.Token.Uid);

            //Statistic.UpdateStatisticsLastUserName(userInfo.ID, userInfo.Name);
            Statistic.Reset();

            if (this.config.Welcomemsg == 1)
            {
                var msg = new ShortMessage
                {
                    Message   = this.config.Welcomemsgtxt,
                    Subject   = "欢迎您的加入! (请勿回复本信息)",
                    Msgto     = userInfo.Name,
                    MsgtoID   = userInfo.ID,
                    Msgfrom   = "系统",
                    MsgfromID = 0,
                    Folder    = 0
                };
                msg.Create();
            }
            //Sync.UserRegister(userInfo.ID, userInfo.Name, userInfo.Password, "");
            LoginUser(userInfo);
            //Statistics.ReSetStatisticsCache();
            Statistic.Reset();
            if (this.config.Regverify != 2)
            {
                CreditsFacade.UpdateUserCredits(userInfo.ID);
                Online.UpdateAction(this.olid, UserAction.Register, 0, this.config.Onlinetimeout);
                base.AddMsgLine("QQ登录成功,继续浏览");
            }
            else
            {
                base.AddMsgLine("QQ数据绑定完成, 但需要系统管理员审核您的帐户后才可登录使用");
            }
            base.SetUrl(connect.Callback);
            base.SetMetaRefresh();
            base.SetShowBackLink(false);

            XTrace.WriteLine("BindPure -> finish, uid=" + connect.Token.Uid);
        }
Esempio n. 39
0
        /// <summary>
        /// Envia o SMS
        /// </summary>
        /// <param name="incidentKey"></param>
        /// <param name="company"></param>
        /// <returns></returns>
        public IncidentAssessment SendSMS(string incidentKey, Company company)
        {
            try
            {
                //valida se existe o incident
                var incidentAssessment = new IncidentAssessment(incidentKey);

                //busca o incident
                incidentAssessment = this._workRepository.IncidentAssessmentRepository.Find(incidentAssessment.Id);

                //valida se existe o incident
                if (incidentAssessment == null)
                {
                    throw new Exception("Registro não encontrado");
                }

                //caso seja um incident criado atualiza para pendente - Inicio o processo de Avaliação
                if (incidentAssessment.Status == StatusIncidentAssessment.Created)
                {
                    //Alterar o status para pendente
                    incidentAssessment.Status = StatusIncidentAssessment.Pending;
                }

                // Configura nome da Companhia de acordo cultura informada
                string strCompanyName = CultureInfo.GetCultureInfo("pt-BR").TextInfo.ToTitleCase(incidentAssessment?.InsuranceCompany?.Name?.ToLower());

                // Configura message do SMS
                string smsMessage = $"{strCompanyName}: Prezado, acesse este link para classificar o tipo de avarias{Environment.NewLine}{this._urlIncidentAssessment}{incidentAssessment.Key}";

                // Carrega informaçãoes do SMS que será enviada ao prestador
                ShortMessage shortMessage = new ShortMessage()
                {
                    Fone = incidentAssessment?.TowTruckDriver?.Mobile != null
                            ? incidentAssessment?.TowTruckDriver?.Mobile
                            : incidentAssessment.TowTruckDriverMobile,

                    Message = smsMessage
                };

                if (string.IsNullOrEmpty(shortMessage.Fone))
                {
                    throw new Exception("Motorista não possui telefone");
                }

                // Envia mensagem SMS via API de Terceiros
                var result = this._shortMessageService.Send(shortMessage);

                // Carrega Código retornado pela API após envio de SMS
                incidentAssessment.ShortMessageCode = result.ShortMessageCode;

                //abre a transação
                this._workRepository.BeginTransaction();

                // Atualiza o Incidente na base de dados após envio de SMS ao prestador
                this._workRepository.IncidentAssessmentRepository.Update(incidentAssessment);

                //adiciona histório de envio de sms
                this.CreateHistory(incidentAssessment, this.LogHistoryUser, TypeOperation.SendSms, this._workRepository);

                //commit da transação
                this._workRepository.Commit();

                //retorna o objeto
                return(incidentAssessment);
            }
            catch (Exception ex)
            {
                //rollback
                this._workRepository.RollBack();

                throw ex;
            }
        }
Esempio n. 40
0
 public void UpdateMessage(ShortMessage l, string[] fields)
 {
     Assistant.Update(l, fields);
 }
Esempio n. 41
0
        public void Register()
        {
            base.SetShowBackLink(true);
            var inviteCodeInfo = this.allowinvite ? this.ValidateInviteInfo() : null;

            if (base.IsErr())
            {
                return;
            }
            string username = DNTRequest.GetString(this.config.Antispamregisterusername);
            string email    = (this.config.Regverify == 1) ? this.verifyinfo.Email : DNTRequest.GetString(this.config.Antispamregisteremail).Trim().ToLower();
            string bday     = DNTRequest.GetString("bday").Trim();

            if (String.IsNullOrEmpty(bday))
            {
                bday = string.Format("{0}-{1}-{2}", DNTRequest.GetString("bday_y").Trim(), DNTRequest.GetString("bday_m").Trim(), DNTRequest.GetString("bday_d").Trim());
            }
            if (bday == "--")
            {
                bday = "";
            }
            this.ValidateUserInfo(username, email, bday);
            if (base.IsErr())
            {
                return;
            }

            if (Users.GetUserId(username) > 0)
            {
                base.AddErrLine("请不要重复提交!");
                return;
            }
            var userInfo = this.CreateUser(username, email, bday);

            if (this.config.Regverify == 1)
            {
                //Users.DeleteVerifyRegisterInfo(this.verifyinfo.RegId);
                //var vi = VerifyReg.FindByID(verifyinfo.ID);
                verifyinfo.Delete();
            }
            if (inviteCodeInfo != null)
            {
                //Invitation.UpdateInviteCodeSuccessCount(inviteCodeInfo.InviteId);
                inviteCodeInfo.SuccessCount++;
                if (this.config.Regstatus == 3 && inviteCodeInfo.SuccessCount + 1 >= inviteCodeInfo.MaxCount)
                {
                    //Invitation.DeleteInviteCode(inviteCodeInfo.InviteId);
                    inviteCodeInfo.IsDeleted = true;
                }
                inviteCodeInfo.Save();
            }
            if (this.config.Welcomemsg == 1)
            {
                var msg = new ShortMessage
                {
                    Message   = this.config.Welcomemsgtxt,
                    Subject   = "欢迎您的加入! (请勿回复本信息)",
                    Msgto     = userInfo.Name,
                    MsgtoID   = userInfo.ID,
                    Msgfrom   = "系统",
                    MsgfromID = 0,
                    Folder    = 0
                };
                msg.Create();
            }
            Sync.UserRegister(userInfo.ID, userInfo.Name, userInfo.Password, "");
            base.SetUrl("index.aspx");
            base.SetShowBackLink(false);
            base.SetMetaRefresh((this.config.Regverify != 2) ? 2 : 5);
            //Statistic.ReSetStatisticsCache();
            //Statistic.UpdateStatisticsLastUserName(userInfo.ID, userInfo.Name);
            Statistic.Reset();
            if (this.config.Regverify != 2)
            {
                CreditsFacade.UpdateUserCredits(userInfo.ID);
                ForumUtils.WriteUserCookie(userInfo, -1, this.config.Passwordkey);
                Online.UpdateAction(this.olid, UserAction.Register, 0, this.config.Onlinetimeout);
                base.MsgForward("register_succeed");
                base.AddMsgLine("注册成功, 返回登录页");
            }
            else
            {
                base.AddMsgLine("注册成功, 但需要系统管理员审核您的帐户后才可登录使用");
            }
            this.agree = "yes";
        }
Esempio n. 42
0
        /// <summary>
        /// 发送短信.
        /// </summary>
        /// <param name="smsID">
        /// 短信编号.
        /// </param>
        public void SendSms(int smsID)
        {
            this.userMessageSmsService = new UserMessageSmsService();
            var userMessageSms = this.userMessageSmsService.QueryByID(smsID);
            this.userService = new UserService();
            var paging = this.TempData["paging"] as Paging;
            this.TempData["paging"] = paging;
            if (paging == null)
            {
                return;
            }

            var list = this.userService.QueryMobile(paging);
            if (list != null)
            {
                try
                {
                    var sm = new ShortMessage { ReceiveMobiles = list, Content = userMessageSms.Content };
                    sm.Send();
                    LogUtils.Log("用户" + this.SystemUserSession.LoginName + "成功发送短信", "SendSms", Category.Info, Session.SessionID);
                    Response.Write("发送成功!");
                }
                catch (Exception exception)
                {
                    Response.Write("发送失败!");
                    throw new Exception(exception.Message);
                }

                try
                {
                    this.userMessageSendRecordService = new UserMessageSendRecordService();
                    var userMessageSendRecord = new User_Message_SendRecord
                                                    {
                                                        EmployeeID =
                                                            this.SystemUserSession.EmployeeID,
                                                        MessageID = userMessageSms.ID,
                                                        MessageTypeID = 2,
                                                        UserCount = list.Count,
                                                        CreateTime = DateTime.Now
                                                    };
                    userMessageSendRecord.ID = this.userMessageSendRecordService.Add(userMessageSendRecord);
                }
                catch (Exception exception)
                {
                    throw new Exception(exception.Message, exception);
                }
            }
        }
Esempio n. 43
0
        private IncomeClientSMS SaveIncomeClientSMS(ShortMessage message, ServicePhone ServicePhone, IncomeSMS incomeSMS, Client client, SMSContext context)
        {
            try
            {

                IncomeClientSMS incomeClientSMS = new IncomeClientSMS()
                {
                    Client = client,
                    ClientId = client.ClientId,
                    DateTime = message.SentDate,
                    Text = message.Text,
                    SenderNumber = client.PhoneNumber,
                    RecipientNumber = ServicePhone.PhoneNumber,
                    Status = IncomeClientSMS.IncomeClientSMSStatus.Received,
                    SecretKey = incomeSMS.SecretKey,
                    MessageId = incomeSMS.MessageId
                };

                context.IncomeClientSMS.Add(incomeClientSMS);
                context.SaveChanges();

                return incomeClientSMS;
            }
            catch (Exception e)
            {
                logger.Error("Ошибка записи  в базу данных. Не удалось добавить сообщение клиента с ответом.\r\nТекст ошибки:", e);
                return null;
            }
        }