Ejemplo n.º 1
0
 /// <summary>
 /// 跨线程访问控件 异步 (扩展方法)
 /// </summary>
 /// <param name="ctrl">控件</param>
 /// <param name="method">执行的方法</param>
 /// <param name="longTimeMethod">需要长时间执行的方法</param>
 public static void CrossThreadCallsSync(this Control ctrl, ParameterizedThreadStart method, LongTimeMethodDelegate longTimeMethod)
 {
     if (method == null)
     {
         return;                 //没有委托返回
     }
     try
     {
         CrossDelegate dl = new CrossDelegate(() =>
         {
             object obj = null;
             if (longTimeMethod != null)
             {
                 obj = longTimeMethod();
             }
             if (ctrl.IsHandleCreated)
             {
                 ctrl.Invoke(new ParameterizedThreadStart(method), obj);
             }
             else
             {
                 ctrl.HandleCreated += (object sender, EventArgs e) =>
                 {
                     ctrl.Invoke(new ParameterizedThreadStart(method), obj);
                 };
             }
         });
         dl.BeginInvoke(null, null);
     }
     catch (Exception ex)
     {
         TmoShare.WriteLog("CrossThreadCallsSync异常", ex);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 得到AppSettings中的配置int信息
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static int GetConfigInt(string key, int defaultValue = 0, bool createKeyAuto = false)
        {
            int    result = defaultValue;;
            string cfgVal = GetConfigString(key);

            if (!string.IsNullOrWhiteSpace(cfgVal))
            {
                try
                {
                    result = int.Parse(cfgVal);
                }
                catch
                {
                    TmoShare.WriteLog("读取配置文件int类型失败 节点:" + key + " ,值:" + cfgVal);
                }
            }
            else
            {
                if (createKeyAuto)
                {
                    if (cfgVal == null)
                    {
                        ConfigHelper.Addconfig(key, defaultValue.ToString());
                    }
                    else
                    {
                        ConfigHelper.UpdateConfig(key, defaultValue.ToString());
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 功能说明:发送邮件
        /// 开发人员:JAFly
        /// 创建日期:2011/11/28 10:40
        /// </summary>
        public static bool SendMail(string title, string Content, string sendToMail, string EmailAddress, string Smtp, string port, string EmailUserName, string EmailPassword)
        {
            try
            {
                #region 获取变量
                if (!Regex.IsMatch(sendToMail, TmoShare.EmailType))
                {
                    return(false);
                }

                sendMail     = EmailAddress;
                sendServer   = Smtp;
                sendPort     = Convert.ToInt32(port);
                sendServer   = sendServer == string.Empty ? "" : sendServer;
                mailPassword = EmailPassword;
                mailName     = EmailUserName;
                #endregion

                System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage();
                mm.From       = new MailAddress(sendMail, EmailUserName);
                mm.Subject    = title;
                mm.IsBodyHtml = true;
                string cbody = Content;
                Content = cbody == "" ? Content : cbody;
                mm.Body = Content;
                string[] sendTos = sendToMail.Split(',');
                for (int i = 0; i < sendTos.Length; i++)
                {
                    mm.To.Add(new MailAddress(sendTos[i]));
                }


                #region 发送邮件
                SmtpClient smtp = new SmtpClient();
                smtp.Host = sendServer;

                smtp.Port        = Convert.ToInt32(port);
                smtp.Credentials = new System.Net.NetworkCredential(EmailAddress, mailPassword);    //验证发信人
                //smtp.Credentials = new System.Net.NetworkCredential("*****@*****.**", "");//验证发信人

                smtp.Timeout = 60000;
                smtp.Send(mm);

                #endregion
                return(true);
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("电子邮件发送失败!服务器返回信息:" + ex.Message.ToString());
                return(false);
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 ///修改指定程序配置文件
 /// </summary>
 /// <param name="cname">The cname.</param>
 /// <param name="cvalue">The cvalue.</param>
 /// <param name="configPath">The config path.</param>
 public static void UpdateConfig(string cname, string cvalue, string configPath)
 {
     try
     {
         System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
         config.AppSettings.Settings[cname].Value = cvalue;
         config.Save(ConfigurationSaveMode.Modified);
         ConfigurationManager.RefreshSection("appSettings");//重新加载新的配置文件
     }
     catch
     {
         TmoShare.WriteLog("修改指定程序配置文件,程序配置文件路径:" + configPath + ",节点:" + cname + " ,值:" + cvalue);
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 对字符串进行解压缩
        /// </summary>
        /// <param name="str">待解压缩的字符串</param>
        /// <returns>解压缩后的字符串</returns>
        public static string DecompressString(string str)
        {
            string decompressString = str;

            try
            {
                byte[] decompressBeforeByte = Convert.FromBase64String(str);
                byte[] decompressAfterByte  = DecompressBytes(decompressBeforeByte);
                return(Encoding.UTF8.GetString(decompressAfterByte));
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("解压字符串报错!", ex);
                return(decompressString);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 对字符串进行压缩
        /// </summary>
        /// <param name="str">待压缩的字符串</param>
        /// <returns>压缩后的字符串</returns>
        public static string CompressString(string str)
        {
            string compressString = str;

            try
            {
                byte[] compressBeforeByte = Encoding.UTF8.GetBytes(str);
                byte[] compressAfterByte  = CompressBytes(compressBeforeByte);
                return(Convert.ToBase64String(compressAfterByte));
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("压缩字符串报错!", ex);
                return(compressString);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 功能说明:
        /// 开发人员:高新刚
        /// 创建日期:2011-4-13 9:19
        /// 修改日期:
        /// 备注信息:
        /// </summary>
        /// <param name="subject">邮件名称</param>
        /// <param name="msg">邮件文本内容</param>
        /// <param name="attachpath">The attachpath.</param>
        /// <param name="ProxyType">Type of the proxy.</param>
        /// <returns></returns>
        public bool SendMail(string subject, string msg, List <string> attachpathList, ProxyType ProxyType)
        {
            bool retbool = false;

            try
            {
                switch (ProxyType)
                {
                case ProxyType.http:

                    #region HTTP方式处理
                    string[] mails = Mails;
                    if (sendTcp == null)
                    {
                        string authstr = ProxyUID + ":" + ProxyPWD;

                        string authproxy = "CONNECT " + SendMailSmtpAdd + ":" + SendMailSmtpPort
                                           + " HTTP/1.0\r\nProxy-Authorization: Basic "
                                           + Convert.ToBase64String(Encoding.UTF8.GetBytes(authstr)) + "\r\n\r\n"; //代理服务器审核

                        bool testproxyflag = true;                                                                 //测试时候使用,设置成false可以不使用代理的Socket方式发邮件

                        if (testproxyflag)
                        {
                            sendTcp = new TcpClient(ProxyIP, ProxyPort);
                        }
                        else
                        {
                            sendTcp = new TcpClient(SendMailSmtpAdd, SendMailSmtpPort);    //注释1
                        }

                        NetworkStream stream = sendTcp.GetStream();

                        //发送代理验证
                        if (testproxyflag)
                        {
                            WriteToNetStream(ref stream, authproxy, false);
                        }

                        //获取验证反馈
                        string response = ReadFromNetStream(ref stream);

                        bool check = false;

                        if (testproxyflag)
                        {
                            check = CheckForError(response, "HTTP/1.0 200") ||
                                    CheckForError(response, "HTTP/1.1 200");

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:邮件代理连接失败");
                                throw new Exception("邮件代理连接失败\r\n");
                            }

                            string receive = ReadFromNetStream(ref stream);

                            check = CheckForError(receive, "220");

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:远端服务器连接失败");
                                throw new Exception("远端服务器连接失败\r\n");
                            }
                        }
                        else
                        {
                            check = CheckForError(response, "220");    //注释3

                            if (!check)
                            {
                                TmoShare.WriteLog("邮件发送失败 失败原因:远端服务器连接失败");
                                throw new Exception("远端服务器连接失败\r\n");
                            }
                        }
                    }

                    try
                    {
                        //发送邮件
                        MailScoketAlternation(mails, subject, msg, attachpathList);
                    }
                    catch (Exception ex)
                    {
                        sendTcp.Close();
                        sendTcp = null;
                        throw ex;
                    }
                    finally
                    {
                        if (sendTcp != null)
                        {
                            try
                            {
                                NetworkStream stream = sendTcp.GetStream();
                                WriteToNetStream(ref stream, "QUIT");
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                sendTcp.Close();
                                sendTcp = null;
                            }
                        }
                    }

                    #endregion

                    break;

                case ProxyType.SOCKS4:
                    //此种方式我软件没让他支持,如果大家想用可以使用CDO的方法试一下,我也没有试是否可行,但是Socket的方式肯定是可以的,只是要有一些变化,如果有人感兴趣可以给我留言。使用CDO需要在项目里引用Microsoft CDO for Windows 2000 Library和Microsoft ActiveX Data Objects 2.8 Library两个COM

                    #region SOCKS4方式处理--暂时不予支持

                    //CDO.Message oMsg = new CDO.Message();

                    //oMsg.From = clsParam.Param.SendMailAccount;
                    //oMsg.To = mails[0];
                    //oMsg.Subject = subject;

                    //oMsg.HTMLBody = msg;

                    //if (File.Exists(attachpath))
                    //{
                    //    oMsg.AddAttachment(attachpath, "", "");
                    //}

                    //CDO.IConfiguration iConfg = oMsg.Configuration;
                    //ADODB.Fields oFields = iConfg.Fields;

                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendusing"].Value = 2;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"].Value = 1;
                    ////value=0   代表Anonymous验证方式(不需要验证)
                    ////value=1   代表Basic验证方式(使用basic   (clear-text)   authentication.
                    ////The   configuration   sendusername/sendpassword   or   postusername/postpassword   fields   are   used   to   specify   credentials.)
                    ////Value=2   代表NTLM验证方式(Secure   Password   Authentication   in   Microsoft   Outlook   Express)
                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpserver"].Value = clsParam.Param.SendMailSmtpAdd;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendemailaddress"].Value = clsParam.Param.SendMailAccount;   //sender   mail
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendusername"].Value = clsParam.Param.SendMailAccount;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/sendpassword"].Value = clsParam.Param.SendMailPWD;

                    //oFields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"].Value = 5;
                    //oFields["http://schemas.microsoft.com/cdo/configuration/languagecode"].Value = 0x0804;

                    ////代理设置
                    ////oFields["http://schemas.microsoft.com/cdo/configuration/urlproxyserver"].Value = "182.1.1.200";
                    ////oFields["http://schemas.microsoft.com/cdo/configuration/proxyserverport"].Value = 8080;

                    //oFields.Update();
                    //oMsg.BodyPart.Charset = "gb2312";
                    //oMsg.HTMLBodyPart.Charset = "gb2312";

                    //oMsg.Send();
                    //oMsg = null;

                    #endregion

                    break;

                case ProxyType.Socks5:     //同Socket4的注释

                    #region SOCKS5方式处理--暂时不予支持

                    #endregion

                    break;
                }


                retbool = true;
            }
            catch (Exception ex)
            {
                TmoShare.WriteLog("发送邮件异常:" + ex.Message);

                retbool = false;
            }
            finally
            {
            }

            return(retbool);
        }
Ejemplo n.º 8
0
        public static string WXTemplateMsgSend(object[] infoValue)
        {
            string strRecode = "微信模板消息发送失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }

                string doc_code    = infoValue[0].ToString();       //取得参数中的值
                string openid      = infoValue[1].ToString();
                string template_id = infoValue[2].ToString();
                string url         = infoValue[3].ToString();
                string topcolor    = infoValue[4].ToString();
                string data        = infoValue[5].ToString();
                data = TmoCommon.JsonHelper.XMLToJSON(data);
                data = data.TrimStart('{').Remove(data.Length - 2);
                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     uri      = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + AccessToken;
                string     postdata = "{\"touser\":\"" + openid + "\",\"template_id\":\"" + template_id + "\",\"url\":\"" + url + "\",\"topcolor\":\"" + topcolor + "\"," + data + "}";
                WebRequest request  = WebRequest.Create(uri);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }

                var jsNodes = TmoCommon.JsonHelper.GetJsonValues(rtStr);
                if (jsNodes == null || jsNodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (jsNodes.ContainsKey("errcode"))
                {
                    string errcode = jsNodes["errcode"].Value.Trim();
                    if (errcode == "0")
                    {
                        //if (!AddWeiXinPushHistory(openid, data))
                        //{
                        //   TmoShare.WriteLog("WeiXin", "创建微信模板消息历史记录失败");
                        //    return "err_success_创建微信模板消息历史记录失败";
                        //}
                        if (jsNodes.ContainsKey("msgid"))
                        {
                            return("success_" + jsNodes["msgid"].Value.Trim()); //成功
                        }
                        else
                        {
                            return("err_success");
                        }
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + jsNodes["errmsg"].Value);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        ///获得模板ID
        /// </summary>
        /// <param name="infoValue">0-医生编号 1-模板库中的短ID</param>
        /// <returns></returns>
        public static string WXGetTemplateSetID(object[] infoValue)
        {
            string strRecode = "获得微信模板ID失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }
                string doc_code          = infoValue[0].ToString(); //取得参数中的值
                string template_id_short = infoValue[1].ToString();

                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     url      = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=" + AccessToken;
                string     postdata = "{\"template_id_short\":\"" + template_id_short + "\"}";
                WebRequest request  = WebRequest.Create(url);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }
                var nodes = TmoCommon.JsonHelper.JSONToObject <Dictionary <string, string> >(rtStr);
                if (nodes == null || nodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (nodes.ContainsKey("errcode"))
                {
                    string errcode = nodes["errcode"].Trim();
                    if (errcode == "0")
                    {
                        if (nodes.ContainsKey("template_id"))
                        {
                            string          template_id = nodes["template_id"].Trim();
                            WxTemplateID    template    = null;
                            BinaryFormatter bf          = new BinaryFormatter();
                            string          configValue = ConfigHelper.GetConfigString("wx_templateid");
                            if (!string.IsNullOrEmpty(configValue))
                            {
                                MemoryStream msr = new MemoryStream(Encoding.UTF8.GetBytes(configValue));
                                template = (WxTemplateID)bf.Deserialize(msr);
                                msr.Close();
                            }
                            if (template == null)
                            {
                                template = new WxTemplateID(TmoShare.WX_APP_ID);
                            }
                            template.AddTemplate(template_id_short, template_id);
                            byte[]       tmp = new byte[1024];
                            MemoryStream msw = new MemoryStream(tmp);
                            bf.Serialize(msw, template);
                            msw.Close();
                            configValue = Encoding.UTF8.GetString(tmp);
                            if (!ConfigHelper.UpdateConfig("wx_templateid", configValue, true))
                            {
                                ConfigHelper.GetConfigString("wx_templateid", configValue, true);
                            }
                            return(template_id); //成功
                        }
                        else
                        {
                            return("err_success");
                        }
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + nodes["errmsg"]);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///设置模板消息所属行业(每月仅可修改1次)
        /// </summary>
        /// <param name="infoValue">0-医生编号 1-主行业 2-副行业</param>
        /// <returns></returns>
        public static string WXTemplateSetIndustry(object[] infoValue)
        {
            string strRecode = "设置微信模板消息所属行业失败!-原因:{0}-当前医生:{1}";

            try
            {
                if (string.IsNullOrEmpty(infoValue[0].ToString()))  //参数缺少医生编号
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_002(参数中未找到医生编号)", "null"));
                    return("err_wx_002");
                }
                string doc_code     = infoValue[0].ToString();      //取得参数中的值
                string industry_id1 = infoValue[1].ToString();
                string industry_id2 = infoValue[2].ToString();
                #region 行业代码查询

                /*
                 *  主行业	        副行业	            代码
                 *  IT科技	        互联网/电子商务	    1
                 *  IT科技	        IT软件与服务	        2
                 *  IT科技	        IT硬件与设备	        3
                 *  IT科技	        电子技术	            4
                 *  IT科技	        通信与运营商	        5
                 *  IT科技	        网络游戏	            6
                 *  金融业	        银行                  7
                 *  金融业	        基金|理财|信托	    8
                 *  金融业	        保险                  9
                 *  餐饮              餐饮	                10
                 *  酒店旅游	        酒店	                11
                 *  酒店旅游	        旅游	                12
                 *  运输与仓储	    快递	                13
                 *  运输与仓储	    物流	                14
                 *  运输与仓储	    仓储	                15
                 *  教育	            培训	                16
                 *  教育	            院校	                17
                 *  政府与公共事业	学术科研	            18
                 *  政府与公共事业	交警	                19
                 *  政府与公共事业	博物馆	            20
                 *  政府与公共事业	公共事业|非盈利机构	21
                 *  医药护理	        医药医疗	            22
                 *  医药护理	        护理美容	            23
                 *  医药护理	        保健与卫生	        24
                 *  交通工具	        汽车相关	            25
                 *  交通工具	        摩托车相关	        26
                 *  交通工具	        火车相关	            27
                 *  交通工具	        飞机相关	            28
                 *  房地产	        建筑                  29
                 *  房地产	        物业	                30
                 *  消费品	        消费品	            31
                 *  商业服务	        法律	                32
                 *  商业服务	        会展                  33
                 *  商业服务	        中介服务	            34
                 *  商业服务	        认证                  35
                 *  商业服务	        审计	                36
                 *  文体娱乐	        传媒                  37
                 *  文体娱乐	        体育	                38
                 *  文体娱乐	        娱乐休闲	            39
                 *  印刷	            印刷	                40
                 *  其它	            其它	                41
                 */

                #endregion
                #region 发送命令
send:
                string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);
                if (string.IsNullOrEmpty(AccessToken) || AccessToken.StartsWith("err"))
                {
                    TmoShare.WriteLog(string.Format(strRecode, "err_wx_accessToken(获取accessToken失败:(" + AccessToken + "))", doc_code));
                    return("err_wx_accessToken");
                }
                string     url      = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=" + AccessToken;
                string     postdata = "{\"industry_id1\":\"" + industry_id1 + "\",\"industry_id2\":\"" + industry_id2 + "\"}";
                WebRequest request  = WebRequest.Create(url);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                Stream writer = request.GetRequestStream();
                byte[] pdarry = Encoding.UTF8.GetBytes(postdata);
                writer.Write(pdarry, 0, pdarry.Length);
                writer.Close();
                #endregion
                #region 取得命令返回值
                WebResponse  response = request.GetResponse();
                Stream       rpReader = response.GetResponseStream();
                StreamReader reader   = new StreamReader(rpReader, Encoding.UTF8);
                string       rtStr    = reader.ReadToEnd();
                reader.Close();
                rpReader.Close();
                response.Close();
                rtStr = rtStr.Replace("&lt;", "<").Replace("&gt;", ">");
                #endregion

                #region 结果处理
                if (string.IsNullOrEmpty(rtStr))
                {
                    return("err_wx_003");
                }

                var jsNodes = TmoCommon.JsonHelper.GetJsonValues(rtStr);
                if (jsNodes == null || jsNodes.Count == 0)
                {
                    return("err_json_converter");
                }
                if (jsNodes.ContainsKey("errcode"))
                {
                    string errcode = jsNodes["errcode"].Value.Trim();
                    if (errcode == "0")
                    {
                        return("success");                             //成功
                    }
                    else if (errcode == "40001" || errcode == "40002") //access_token问题
                    {
                        AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                        goto send;
                    }
                    else
                    {
                        return("err_" + errcode + "_" + jsNodes["errmsg"].Value);
                    }
                }
                else
                {
                    return("err_errcode_null");
                }
                #endregion
            }
            catch (Exception e)
            {
                TmoShare.WriteLog(string.Format(strRecode, "err_wx_001(未知异常失败)", infoValue[0]) + e.Message);
                return("err_wx_001");
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 微信消息保存入库
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string WXMsgToDB(object[] infoValue)
        //{
        //    string resStr = "";
        //    try
        //    {
        //        if (infoValue[0] != null && infoValue[0].ToString() != "")
        //        {
        //            if (WellDBBLL.well_weixin_contentManager.Instance.AddWeixinMsg(infoValue[0].ToString()))
        //            {
        //                #region 医生Tcp消息推送
        //                DataSet dsXml = TmoShare.getDataSetfromXML(infoValue[0].ToString());
        //                string token_open_id = dsXml.Tables[0].Rows[0]["token_open_id"].ToString();

        //                bool blDN = AddDocNotifycation(dsXml);
        //                #endregion
        //                DataSet ds = WMFEntityManager.Instance.GetEntityInfoByPKLiteWhere("well_weixin_content", "token_open_id", token_open_id, "create_time,-*",
        //                    "(is_answer=1 and create_time >'" + DateTime.Now.AddMinutes(-3).ToString("yyyy-MM-dd HH:mm:ss") + "' and create_time <'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        //                    + "') or "
        //                    + "(is_answer=2 and create_time >'" + DateTime.Now.AddMinutes(-1).ToString("yyyy-MM-dd HH:mm:ss") + "' and create_time <'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')");

        //                if (TmoShare.DataSetEmpty(ds))
        //                {
        //                    resStr = "msg_sucess";
        //                }
        //                else
        //                {
        //                    resStr = "msg_sucess_rep";//如果3分钟内医生回复过本人消息,则不重复提醒。
        //                }

        //            }
        //            else
        //            {
        //                resStr = "error";
        //            }
        //        }
        //        else
        //        {
        //            resStr = "error";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        TmoShare.WriteWXLog("微信消息相应", ex.Message);
        //        resStr = "error";
        //    }

        //    return resStr;
        //}

        //public static bool AddDocNotifycation(DataSet dsXml)
        //{
        //    #region 数据格式
        //    //            string WeiMsgStr = TmoShare.XML_TITLE +
        //    //  @"<wellweixincontent>
        //    //<well_weixin_content>
        //    //<doc_code></doc_code>
        //    //<token_open_id></token_open_id>
        //    //<message_content></message_content>
        //    //<create_time></create_time>
        //    //<input_time></input_time>
        //    //<is_look></is_look>
        //    //<is_answer></is_answer>
        //    //<is_fousc></is_fousc>
        //    //<wm_id></wm_id>
        //    //<is_del></is_del>
        //    //<r_mark></r_mark>
        //    //<wx_type></wx_type>
        //    //<media_id></media_id>
        //    //<MsgId></MsgId>
        //    //<format></format>
        //    //</well_weixin_content>
        //    //</wellweixincontent>";
        //    #endregion
        //    //提问者编号
        //    string push_id = TmoShare.GetGuidString();
        //    string token_open_id = dsXml.Tables[0].Rows[0]["token_open_id"].ToString();
        //    string user_code = "";
        //    DataSet dsToken = WMFEntityManager.Instance.GetEntityInfoByPKLite("well_reg_userinfo_token", "reg_login_token", token_open_id, "");
        //    if (TmoShare.DataSetIsNotEmpty(dsToken))
        //    {
        //        user_code = dsToken.Tables[0].Rows[0]["user_code"].ToString();
        //    }

        //    #region 寻找医生
        //    string doc_code = "admin";
        //    if (dsXml.Tables[0].Columns.Contains("doc_code") && dsXml.Tables[0].Rows[0]["doc_code"].ToString().Trim() != "")
        //    {
        //        doc_code = dsXml.Tables[0].Rows[0]["doc_code"].ToString();
        //    }
        //    else
        //    {
        //        DataSet ds = WMFEntityManager.Instance.GetEntityInfoByPKLite("well_reg_userinfo",
        //            "user_code", user_code, "doc_code,-*");
        //        if (TmoShare.DataSetIsNotEmpty(ds))
        //        {
        //            doc_code = ds.Tables[0].Rows[0]["doc_code"].ToString();
        //        }
        //        else
        //        {
        //            doc_code = "admin";
        //        }
        //    }
        //    #endregion

        //    string push_type = "1";//推送类型 1 用户对医生 2 医生对医生
        //    string to_doc_id = doc_code;
        //    string from_user_id = user_code;
        //    string content_type = "1";
        //    string content_title = "";
        //    string content_value = dsXml.Tables[0].Rows[0]["message_content"].ToString();
        //    string content_url = "";
        //    string content_key = "";
        //    string push_status = "1"; //推送状态 1 未推送  2 已推送 3 推送中
        //    string push_source = "6";
        //    string timestamp = dsXml.Tables[0].Rows[0]["timestamp"].ToString();


        //    string remark = string.Format("msg_r|token_open_id:{0}|to_doc_id:{1}|from_user_id:{2}|timestamp:{3}",
        //        token_open_id, to_doc_id, user_code, timestamp);
        //    bool blNotify = WMFEntityManager.Instance.SubmitEntityInfoByDictionaryLite("well_noitfycation_doc",
        //           new Dictionary<string, string>() {
        //                        { "push_id",  push_id },
        //                        { "push_type", push_type },
        //                        { "push_source", push_source },
        //                        { "to_doc_id", to_doc_id },
        //                        { "from_user_id", from_user_id },
        //                        { "content_type", content_type },
        //                        { "content_title", content_title },
        //                        { "content_value",content_value },
        //                        { "content_url",content_url },
        //                        { "content_key",content_key },
        //                        { "push_status",push_status },
        //                        { "push_count","0" },
        //                        { "push_time",TmoShare.DateTimeNow() },
        //                        { "doc_code",doc_code },
        //                        { "remark",remark }
        //                    },
        //                    "push_id", push_id);
        //    return blNotify;
        //}

        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string DeleWXMsg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        string aw_id = "";
        //        if (infoValue[1] != null && !string.IsNullOrEmpty(infoValue[1].ToString()))
        //        {
        //            aw_id = infoValue[1].ToString();
        //        }

        //        if (WellDBBLL.well_weixin_contentManager.Instance.DeleWXMsg(infoValue[0].ToString(), aw_id))
        //        {
        //            return "success";
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 更新消息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string UpdateWXMsg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = TmoShare.getDataSetfromXML(infoValue[0].ToString());
        //        if (WellDBBLL.well_weixin_contentManager.Instance.UpdateWXMsg(ds))
        //        {
        //            return "success";
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWxms(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxms(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWxmsByWhere(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxmsByWhere(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 获取分页数据信息
        /// </summary>
        /// <param name="infoValue"></param>
        /// <returns></returns>
        //public static string GetWxmBypage(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWxmBypage(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string DownloadImg(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "" && infoValue[1] != null)
        //    {

        //        return WellDBBLL.well_weixin_contentManager.Instance.DownloadImg(infoValue[0].ToString(), infoValue[1].ToString());

        //    }
        //    return "error";
        //}
        //public static string GetWx(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWx(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        //public static string GetWAsBypage(object[] infoValue)
        //{
        //    if (infoValue[0] != null && infoValue[0].ToString() != "")
        //    {
        //        DataSet ds = WellDBBLL.well_weixin_contentManager.Instance.GetWAsBypage(infoValue[0].ToString());
        //        if (ds != null && ds.Tables.Count > 0)
        //        {
        //            return TmoShare._GetXml(ds);
        //        }
        //        else
        //        {
        //            return "error";
        //        }
        //    }
        //    return "error";
        //}
        /// <summary>
        /// 发送微信消息
        /// </summary>
        /// <param name="infoValue">
        /// doc_code
        /// openID
        /// msgType
        /// msgContent
        /// </param>
        /// <returns></returns>
        public static string WXMsgSend(object[] infoValue)
        {
            string strRecode = "";

            try
            {
                if (infoValue[0].ToString() != "")
                {
                    string doc_code = infoValue[0].ToString();
                    string openID   = infoValue[1].ToString();
                    string msgType  = infoValue[2].ToString();

                    string msgContent = infoValue[3].ToString();

                    string AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, true);

                    string url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + AccessToken;

                    string postDataStr = "{\"touser\":\"" + openID + "\",\"msgtype\":\"text\",\"" + msgType + "\":{\"content\":\"" + msgContent + "\"}}";


                    System.Net.HttpWebRequest request;

                    request = (System.Net.HttpWebRequest)WebRequest.Create(url);
                    //Post请求方式
                    request.Method = "POST";
                    // 内容类型
                    request.ContentType = "application/x-www-form-urlencoded";
                    // 参数经过URL编码
                    //string paraUrlCoded = "";// System.Web.HttpUtility.UrlEncode("keyword");
                    //paraUrlCoded = System.Web.HttpUtility.UrlEncode(postDataStr);
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(postDataStr);
                    //设置请求的 ContentLength
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    System.Net.HttpWebResponse response;
                    // 获得响应流
                    response = (System.Net.HttpWebResponse)request.GetResponse();
                    System.IO.Stream data;
                    data = response.GetResponseStream();
                    string strValue = "";
                    using (StreamReader reader = new StreamReader(data, Encoding.Default))
                    {
                        strValue = reader.ReadToEnd().Trim();
                        data.Close();
                        reader.Close();
                    }


                    strValue = strValue.Replace("&lt;", "<");
                    strValue = strValue.Replace("&gt;", ">");


                    string retString = strValue;

                    #region 结果处理
                    if (string.IsNullOrEmpty(retString))
                    {
                        return("err_wx_003");
                    }

                    Dictionary <string, TmoCommon.JsonHelper.JsonNode> jsNodes = TmoCommon.JsonHelper.GetJsonValues(retString);
                    if (jsNodes != null || jsNodes.Count > 0)
                    {
                        if (jsNodes.ContainsKey("errcode"))
                        {
                            #region 返回参数解析格式
                            //                                            全局返回码说明如下:

                            //返回码  说明
                            //-1  系统繁忙
                            //0  请求成功
                            //40001  获取access_token时AppSecret错误,或者access_token无效
                            //40002  不合法的凭证类型
                            //40003  不合法的OpenID
                            //40004  不合法的媒体文件类型
                            //40005  不合法的文件类型
                            //40006  不合法的文件大小
                            //40007  不合法的媒体文件id
                            //40008  不合法的消息类型
                            //40009  不合法的图片文件大小
                            //40010  不合法的语音文件大小
                            //40011  不合法的视频文件大小
                            //40012  不合法的缩略图文件大小
                            //40013  不合法的APPID
                            //40014  不合法的access_token
                            //40015  不合法的菜单类型
                            //40016  不合法的按钮个数
                            //40017  不合法的按钮个数
                            //40018  不合法的按钮名字长度
                            //40019  不合法的按钮KEY长度
                            //40020  不合法的按钮URL长度
                            //40021  不合法的菜单版本号
                            //40022  不合法的子菜单级数
                            //40023  不合法的子菜单按钮个数
                            //40024  不合法的子菜单按钮类型
                            //40025  不合法的子菜单按钮名字长度
                            //40026  不合法的子菜单按钮KEY长度
                            //40027  不合法的子菜单按钮URL长度
                            //40028  不合法的自定义菜单使用用户
                            //40029  不合法的oauth_code
                            //40030  不合法的refresh_token
                            //40031  不合法的openid列表
                            //40032  不合法的openid列表长度
                            //40033  不合法的请求字符,不能包含\uxxxx格式的字符
                            //40035  不合法的参数
                            //40038  不合法的请求格式
                            //40039  不合法的URL长度
                            //40050  不合法的分组id
                            //40051  分组名字不合法
                            //41001  缺少access_token参数
                            //41002  缺少appid参数
                            //41003  缺少refresh_token参数
                            //41004  缺少secret参数
                            //41005  缺少多媒体文件数据
                            //41006  缺少media_id参数
                            //41007  缺少子菜单数据
                            //41008  缺少oauth code
                            //41009  缺少openid
                            //42001  access_token超时
                            //42002  refresh_token超时
                            //42003  oauth_code超时
                            //43001  需要GET请求
                            //43002  需要POST请求
                            //43003  需要HTTPS请求
                            //43004  需要接收者关注
                            //43005  需要好友关系
                            //44001  多媒体文件为空
                            //44002  POST的数据包为空
                            //44003  图文消息内容为空
                            //44004  文本消息内容为空
                            //45001  多媒体文件大小超过限制
                            //45002  消息内容超过限制
                            //45003  标题字段超过限制
                            //45004  描述字段超过限制
                            //45005  链接字段超过限制
                            //45006  图片链接字段超过限制
                            //45007  语音播放时间超过限制
                            //45008  图文消息超过限制
                            //45009  接口调用超过限制
                            //45010  创建菜单个数超过限制
                            //45015  回复时间超过限制
                            //45016  系统分组,不允许修改
                            //45017  分组名字过长
                            //45018  分组数量超过上限
                            //46001  不存在媒体数据
                            //46002  不存在的菜单版本
                            //46003  不存在的菜单数据
                            //46004  不存在的用户
                            //47001  解析JSON/XML内容错误
                            //48001  api功能未授权
                            //50001  用户未授权该api

                            #endregion

                            if (jsNodes["errcode"].Value.Trim() == "0")
                            {
                                return("success");
                            }
                            else if (jsNodes["errcode"].Value.Trim() == "40001" || jsNodes["errcode"].Value.Trim() == "40002")
                            {
                                AccessToken = WeChatHelper.WXGetAccessToken(new object[] { "admin" }, false);
                                if (AccessToken.StartsWith("err") || AccessToken == "")
                                {
                                    return("err_access_token_creat");
                                }
                            }
                            else if (jsNodes["errcode"].Value == "45015") //用户一定时间内没有和公众号沟通 回复受限
                            {
                                return("err_wx_time_limit");
                            }
                            else
                            {
                                strRecode = "err_" + jsNodes["errcode"].Value + "_" + jsNodes["errmsg"].Value;
                            }
                        }
                        else
                        {
                            strRecode = "err_errcode_null";
                        }
                    }
                    else
                    {
                        strRecode = "err_json_converter";
                    }

                    #endregion
                }
                else
                {
                    strRecode = "未传入医生编码!";
                    TmoShare.WriteLog(strRecode);
                    return("err_wx_002");
                }
            }
            catch (Exception e)
            {
                strRecode = "当前医生" + infoValue[0].ToString() + "获取列表失败! 原因:err_wx_001(未知异常失败)";
                TmoShare.WriteLog(strRecode + e.Message.ToString());
                return("err_wx_001");
            }
            return("");
        }
Ejemplo n.º 12
0
        //appID wx80b8ea65e4f18e65
        //appsecret b3c748800db56e4019814109a79dc06b

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        public static string WXGetAccessToken(object[] infoValue, bool useCache)
        {
            if (useCache)
            {
                TimeSpan ts = DateTime.Now - TmoShare.WX_ACCESS_TOKEN_TIME;
                if (ts.TotalSeconds <= 3600)
                {
                    return(TmoShare.WX_ACCESS_TOKEN);
                }
            }

            string strRecode = "";

            try
            {
                string appID     = TmoShare.WX_APP_ID;     // "wx80b8ea65e4f18e65";
                string appSecret = TmoShare.WX_APP_SECRET; //"b3c748800db56e4019814109a79dc06b";
                string url       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret + "";

                #region 特别注意
                //{"errcode":45009,"errmsg":"api freq out of limit"}
                //接口调用频率限制如下:
                //接口  每日限额
                //获取access_token  2000
                #endregion
                if (infoValue[0].ToString() != "")
                {
                    using (WebClient client = new WebClient())
                    {
                        try
                        {
                            Stream data = client.OpenRead(url);
                            using (StreamReader reader = new StreamReader(data, Encoding.Default))
                            {
                                string resultData = reader.ReadToEnd();
                                resultData = resultData.Trim();
                                data.Close();
                                reader.Close();
                                switch (resultData)
                                {
                                case "":
                                    strRecode = "err_null";
                                    break;

                                case "45009":
                                    TmoShare.WriteLog("调用WXGetAccessToken当天过于频繁! 详细信息:err_wx_45009");
                                    strRecode = "err_wx_45009";
                                    break;

                                case "40013":
                                    TmoShare.WriteLog("调用WXGetAccessToken当天过于频繁! 详细信息:err_wx_45009");
                                    strRecode = "err_wx_45009";
                                    break;

                                //{"errcode":40013,"errmsg":"invalid appid"}
                                default:
                                    Dictionary <string, TmoCommon.JsonHelper.JsonNode> jsNodes =
                                        TmoCommon.JsonHelper.GetJsonValues(resultData);
                                    if (jsNodes != null || jsNodes.Count > 0)
                                    {
                                        if (jsNodes.ContainsKey("access_token"))
                                        {
                                            TmoShare.WX_ACCESS_TOKEN = jsNodes["access_token"].Value;
                                            //string expires_in = jsNodes["expires_in"].Value;
                                            TmoShare.WX_ACCESS_TOKEN_TIME = DateTime.Now;
                                        }
                                        else if (jsNodes.ContainsKey("errcode"))
                                        {
                                            //{"errcode":40013,"errmsg":"invalid appid"}
                                            strRecode = "err_" + jsNodes["errcode"].Value + "_" + jsNodes["errmsg"].Value;
                                        }
                                        else
                                        {
                                            TmoShare.WX_ACCESS_TOKEN = "";
                                            //string expires_in = jsNodes["expires_in"].Value;
                                            TmoShare.WX_ACCESS_TOKEN_TIME = DateTime.Now;
                                        }
                                    }
                                    else
                                    {
                                        strRecode = "err_json_converter";
                                    }
                                    break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            TmoShare.WriteLog("调用WXGetAccessToken接口发生未知错误! 详细信息:" + ex.Message);
                            strRecode = "err_002";
                        }
                    }
                }
                else
                {
                    strRecode = "err_wx_003";
                    TmoShare.WriteLog("调用WXGetAccessToken未传入医生编码!");
                }
            }
            catch (Exception e)
            {
                strRecode = "err_wx_001";
                TmoShare.WriteLog("当前医生" + infoValue[0].ToString() + "获取列表失败! 原因:err_cdp_001(未知异常失败)" + e.Message.ToString());
            }
            strRecode = TmoShare.WX_ACCESS_TOKEN;
            return(strRecode);
        }