轮询信息表然后进行钉钉消息推送代码示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using System.Data.Common;
using TechExcel.Project.DataAccess;
using TechExcel.Project.DataAccess.Service;
using TechExcel.Project.DataAccess.Utility;
using TechExcel.Project.DSTCommonData;
using System.Reflection;
using System.Xml;
using System.Security.Cryptography;
using System.IO;
using TechExcel.DataAccess;
using TechExcel.Project.Utility;
using TechExcel.Project.ServiceUtil;
using TechExcel.SuiteLogic;
using System.Net;
using System.Data.SqlClient;
using System.Timers;
using Newtonsoft.Json;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Text;
using TechExcel.Project.DataAccess;
using System.Threading;

namespace TechExcel.PPM.ProjectWeb
{
    public class DevsuiteEastHopeSyncService : System.Web.UI.Page
    {
        public void GoSyncService()
        {
            //第一步,每隔10秒钟轮询一次信息表
            /*
            //利用多线程的方式
            ThreadStart easthope= new ThreadStart(getTimeEvent);
            Thread childThread = new Thread(easthope);
            childThread.Start();
            while (true)
            {
                Thread.Sleep(10000);
                //System.Threading.Thread.CurrentThread.Join(10000);
            }*/
            //getTimeEvent();
            //利用timer的方式

            System.Timers.Timer t = new System.Timers.Timer(15000);//实例化Timer类,设置时间间隔为1000
            t.Elapsed += getTimeEvent;//到达时间的时候执行事件
            t.AutoReset = true;//设置是执行一次(false)还是一直执行(true)
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件,为true表示开始执行,false表示停止

        }
        //第二步,每次轮询都获取到信息表的数据
        public void getTimeEvent(Object source, ElapsedEventArgs e)
        //public void getTimeEvent()
        {

            string corpid = "ding5e122b5e9fdd53e5";
            string corpSecret = "bb4cA29hkVNBb2OsUFUiznoccBT2jdArEA3Wvz3mOymUc7BmiNVu25Grb3_wBxhT";
            try
            {
                DataSet ds = new ExternalReportHandler().GetEastHopeEmail();
                DataTable dt = ds.Tables[0];
                if (dt.Rows.Count == 0)//如果表中没有数据,就不执行推送
                {
                    return;
                }
                else
                {
                    //获取钉钉里企业所有员工的userid
                    List<Userlist> userList = new List<Userlist>();
                    GetEastHopeHandle easthope = new GetEastHopeHandle();
                    userList = easthope.GetUserInfoList(corpid, corpSecret);
                    //判断devsuite里更新的的userid和钉钉里的哪一个userid相对应,如果对应就往那个账号推送信息
                    if (userList != null)
                    {
                        easthope.IsUseridExist(userList, dt, corpid, corpSecret);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("[ERROR] 数据库操作出现异常:" + ex.Message);
                return;
            }
            finally
            {
            }
        }
    }
    public class GetEastHopeHandle
    {
        public int SetTableStatus(int okstatus, int id, string receiver)
        {
            return new ExternalReportHandler().UpdateEastHopeT(okstatus, id, receiver);
        }
        public string IsUseridExist(List<Userlist> userlistT, DataTable dtResult, string appId, string secrect)
        {
            if (userlistT.Count > 0)
            {
                for (int i = 0; i < dtResult.Rows.Count; i++)
                    for (int j = 0; j < userlistT.Count; j++)
                    {
                        if (userlistT[j].name == "邹海鹏")
                        {
                            string thenphone = userlistT[j].mobile;
                        }
                        //判断表中是否有新添加的信息,如果有就再判断该用户是否为钉钉用户
                        if (userlistT[j].mobile == dtResult.Rows[i]["Receiver"].ToString() && int.Parse(dtResult.Rows[i]["Status"].ToString()) == 0)
                        {
                            string strName = dtResult.Rows[i]["Receiver"].ToString();
                            string strContent = dtResult.Rows[i]["Content"].ToString();
                            int id = int.Parse(dtResult.Rows[i]["ID"].ToString());
                            string phoneNumber = userlistT[j].mobile;
                            //如果devsuite的useid和钉钉里的userid相同,并且Status的值为0,就往钉钉接口推送信息
                            int result = Send(userlistT[j].userid, strContent, appId, secrect, id, phoneNumber);
                            if (result == 0)
                            {
                                Console.Write(DateTime.Now.ToString() + ":未知错误,请查看错误源");
                            }
                            else if (result == 1)
                            {
                                Console.Write(DateTime.Now.ToString() + ":数据已经成功发送");
                            }
                            else if (result == 2)
                            {
                                Console.Write(DateTime.Now.ToString() + ":发送不成功但是已将该表行的status的值重新置为0");
                            }
                            else if (result == 3)
                            {
                                Console.Write(DateTime.Now.ToString() + ":发送不成功并且已将该表行的status的值置为1,未能重新置为0,若发生某种问题,请联系开发人员解决");
                            }
                            else
                            {
                            }
                        }
                    }
            }
            return null;
        }
        private string GetResponseData(string postData, string url)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证证书
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                //设置由 ServicePointManager 对象管理的 ServicePoint 对象所使用的安全协议。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                request.KeepAlive = false;
                //获取或设置一个 Boolean 值,该值指示是否根据证书颁发机构吊销列表检查证书。
                //如果检查证书吊销列表,则为 true;否则为 false。
                ServicePointManager.CheckCertificateRevocationList = true;
                //设置 ServicePoint 对象所允许的最大并发连接数。
                ServicePointManager.DefaultConnectionLimit = 100;
                //若要启用 100-Continue 行为,则为 true。 默认值为 true。
                ServicePointManager.Expect100Continue = false;
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }
            request.Method = "POST"; //使用POST方式发送数据
            request.ContentType = "application/json";
            request.Referer = null;
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Accept = "*/*";

            byte[] data = Encoding.UTF8.GetBytes(postData);
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }
            return result;
        }

        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受 
        }
        private string GetResponseDataForGet(string Url)
        {
            WebRequest request = WebRequest.Create(Url);
            request.Method = "GET";
            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            Encoding encode = Encoding.UTF8;
            StreamReader reader = new StreamReader(stream, encode);
            string strResult = reader.ReadToEnd();
            stream.Dispose();
            reader.Dispose();
            return strResult;
        }
        //根据企业提供的企业ID和企业应用的凭证秘钥获取到access_token
        public string GetAccess_Token(string appId, string secrect)
        {
            try
            {
                string url = "https://oapi.dingtalk.com/gettoken?corpid=" + appId + "&corpsecret=" + secrect;
                string str = GetResponseDataForGet(url);
                if (str.Contains("access_token"))
                {
                    AccessTokenResult accessTokenResult = JsonConvert.DeserializeObject<AccessTokenResult>(str);
                    return accessTokenResult.access_token;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }

        }
        /// <summary>
        /// 获取部门信息
        /// </summary>
        public DepartmentResult GetDepartmentInfo(string appId, string secrect)
        {
            try
            {
                string access_token = GetAccess_Token(appId, secrect);
                string url = "https://oapi.dingtalk.com/department/list?access_token=" + access_token;
                string str = GetResponseDataForGet(url);
                DepartmentResult departmentResult = JsonConvert.DeserializeObject<DepartmentResult>(str);
                return departmentResult;
            }
            catch (Exception ex)
            {

                return null;
            }
        }
        /// <summary>
        /// 根据企业部门ID和企业应用的凭证密钥获取企业下所有人员的信息
        /// </summary>
        public List<Userlist> GetUserInfoList(string appId, string secrect)
        {
            try
            {
                string access_token = GetAccess_Token(appId, secrect);
                if (string.IsNullOrEmpty(access_token)) return null;
                DepartmentResult departmentResult = GetDepartmentInfo(appId, secrect);
                if (departmentResult.errcode != 0 || departmentResult.department.Count <= 0)
                    return null;
                List<Userlist> userListall = new List<Userlist>();
                foreach (Department item in departmentResult.department)
                {
                    //根据部门ID获取部门人员详情
                    string url = "https://oapi.dingtalk.com/user/list?access_token=" + access_token + "&department_id=" + item.id;
                    string str = GetResponseDataForGet(url);
                    UserResult userResult = JsonConvert.DeserializeObject<UserResult>(str);
                    if (int.Parse(userResult.errcode) == 0 && userResult.userlist != null)
                    {
                        userListall.AddRange(userResult.userlist);//添加人员信息到集合中
                    }
                }
                return userListall;
            }
            catch (Exception ex)
            {

                return null;
            }
        }
        /// <summary>
        /// 发送钉钉消息
        /// </summary>
        /// <param name="userId">电话号码,多个用逗号隔开</param>
        /// <param name="content">发送内容</param>
        /// <param name="appId">企业ID</param>
        /// <param name="secrect">企业应用的凭证密钥</param>
        /// <returns></returns>
        public int Send(string userId, string content, string appId, string secrect, int id, string phoneNumber)
        {
            try
            {
                /*
                List<Userlist> userList = GetUserInfoList(appId, secrect);
                string[] phoneNoArray = userId.Split(',');
                string toUser = "";
                foreach (string item in phoneNoArray)
                {
                    Userlist user = userList.Where(i => i.mobile == item).FirstOrDefault();
                    if (user != null)
                    {
                        toUser += user.userid + "|";
                    }
                }
                toUser = toUser.Trim('|');
                 */
                string JSONData = "{\"touser\":\"" + userId + "\",\"toparty\":\"\",\"agentid\":\"196175936\",\"msgtype\":\"action_card\",\"action_card\":{\"title\":\"DevSuite消息\",\"markdown\":\"**<font size=7 face=\'黑体\'>DevSuite待办事项: </font>**        \n  \n " + content + "      \n " + DateTime.Now.ToString() + "\",\"single_title\": \"查看详情\",\"single_url\": \"https://almteam.techexcel.com\"}}";
                int status = 1;
                if (SetTableStatus(status, id, phoneNumber) == 1)
                {
                    string access_token = GetAccess_Token(appId, secrect);
                    string url = "https://oapi.dingtalk.com/message/send?access_token=" + access_token;
                    string str = GetResponseData(JSONData, url);
                    SendMessageResult result = JsonConvert.DeserializeObject<SendMessageResult>(str);
                    if (result != null && result.errcode == 0)
                    {
                        return 1;
                    }
                    else
                    {
                        status = 0;
                        if (SetTableStatus(status, id, phoneNumber) == 1)
                        {
                            //如果发送不成功但是已将数据库的status的值修改为1,就将status的值变为0(成功),并且返回2
                            return 2;
                        }
                        else
                        {
                            //如果发送不成功但是已将数据库的status的值修改为1,就将status的值变为0(失败),并且返回0
                            return 0;
                        }
                    }
                }
                return 0;
            }
            catch (Exception ex)
            {
                return 3;
            }

        }
    }
    public class AccessTokenResult
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string access_token { get; set; }
    }
    public class Department
    {
        public string id { get; set; }
        public string name { get; set; }
        public string parentid { get; set; }
        public string createDeptGroup { get; set; }
        public string autoAddUser { get; set; }
    }

    public class DepartmentResult
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public List<Department> department { get; set; }
    }

    public class Extattr
    {
        public string 爱好 { get; set; }
        public string 年龄 { get; set; }
    }

    public class Userlist
    {
        public string userid { get; set; }
        public string unionid { get; set; }
        public string mobile { get; set; }
        public string tel { get; set; }
        public string workPlace { get; set; }
        public string remark { get; set; }
        public string order { get; set; }
        public string isAdmin { get; set; }
        public string isBoss { get; set; }
        public string isHide { get; set; }
        public string isLeader { get; set; }
        public string name { get; set; }
        public string active { get; set; }
        //public List<DepartmentArr> department { get; set; }
        public string position { get; set; }
        public string email { get; set; }
        public string avatar { get; set; }
        public string jobnumber { get; set; }
        public Extattr extattr { get; set; }
    }
    public class DepartmentArr
    {
    }

    public class UserResult
    {
        public string errcode { get; set; }
        public string errmsg { get; set; }
        public string hasMore { get; set; }
        public List<Userlist> userlist { get; set; }
    }
    public class SendMessageResult
    {
        public int errcode { get; set; }
        public string errmsg { get; set; }
        public string invaliduser { get; set; }
        public string invalidparty { get; set; }
        public string forbiddenUserId { get; set; }
        public string messageId { get; set; }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值