コード例 #1
0
        private void PushAndroid(string PackageName, string AppSecret, string ClientID, string Title, string Description, string Payload, long TimeToLive, string NotifyId)
        {
            try
            {
                MgoogpsWebClient mgoo = new MgoogpsWebClient();
                mgoo.RequestUrl         = HOST;
                mgoo.RequestMethodType  = "POST";
                mgoo.RequestContentType = "application/x-www-form-urlencoded";
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers.Add("Authorization", "key=" + AppSecret);          //  LrXeTJHe6tWQ0rOo2pcqbQ==
                StringBuilder sb = new StringBuilder();
                sb.Append("payload=" + Payload + "&");                     //	消息的内容。
                sb.Append("restricted_package_name=" + PackageName + "&"); //App的包名。
                sb.Append("pass_through=0&");                              //0 表示通知栏消息  1 表示透传消息
                sb.Append("title=" + Title + "&");                         //通知栏展示的通知的标题。
                sb.Append("description='" + Description + "'&");           //	通知栏展示的通知的描述。
                sb.Append("notify_type=" + this.DefaulSound + "&");        //DEFAULT_ALL = -1;  DEFAULT_SOUND  = 1;  // 使用默认提示音提示;DEFAULT_VIBRATE = 2;  // 使用默认震动提示;DEFAULT_LIGHTS = 4;   // 使用默认led灯光提示;
                sb.Append("time_to_live=" + TimeToLive + "&");             //1天 可选项。如果用户离线,设置消息在服务器保存的时间,单位:ms。服务器默认最长保留两周。
                sb.Append("notify_id=" + NotifyId + "&");
                // sb.Append("extra.notify_effect=3&");// 可选项 “3″:通知栏点击后打开网页(开发者还需要传入extra.web_uri)。
                //sb.Append("extra.web_uri=https://www.baidu.com&");//	可选项,打开某一个网页。参考2.2.3.3
                // sb.Append("extra.sound_uri=android.resource://com.mgoogps.oubaoyun/tuisong&");
                sb.Append("registration_id=" + ClientID + ""); //0czrCPue2ny19RfpAYNU44/n4niilHAHn48lNLWQTE0=

                //AcHKMOVNigJtkRluQU3FAyWnCbdsvoBYKGPdV1gLHJA=, rStPppMYedb5FCdnM/QPSWf0n+C61RhycDMz5JrFJBY=,SZzVN/bbQz0IhRSQ37M8EnvYPxYdaPOMj9F4M0QeivQ=,Sw/1lgU8KyA5zYiA3OrFT6cHoA5e7rpEuy5SAKdnn0g=,VOtpeNF2jSciN5cmDJFyVhkNCEvgMIr+weCzZPH7u94=
                mgoo.RequestPostData = Encoding.UTF8.GetBytes(sb.ToString());
                string reulst = mgoo.RequestSend(headers);
                Utils.log("Android---" + Title + ":" + reulst, "MiPush" + DateTime.Now.ToString("yyyyMM") + "-" + DateTime.Now.DayOfWeek + ".log");
            }
            catch (Exception ex)
            {
                Utils.log("PushAndroid Error:" + ex.Message + ",Source:" + ex.Source + ",StackTrace:" + ex.StackTrace);
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: mgoogps/mgoo
        private static void SMSSend()
        {
            string phone    = "18507480591";
            var    password = GetMD5("mgdz" + GetMD5("hI6eI2cN"));
            string content  = string.Format("【美谷科技】您的设备{0},在{1}触发了{2},请留意。", "测试", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "震动报警");

            string[] parsList = new string[4];
            parsList[0] = "username=mgdz";
            parsList[1] = "password="******"mobile=" + phone;
            parsList[3] = "content=" + content;// + HttpUtility.UrlEncode(content ,Encoding.UTF8) ;
            var postData = string.Join("&", parsList);

            Console.WriteLine(postData);

            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodType  = "POST";
            webClient.RequestPostData    = Encoding.UTF8.GetBytes(postData);
            webClient.RequestContentType = "application/x-www-form-urlencoded";
            webClient.RequestUrl         = server_host;// +"?"+postData;
            string res = webClient.RequestSend();


            // MG_BLL.Pay.WeixinPay.lib.HttpService.Post();
            Console.WriteLine(res);
            Console.Read();
        }
コード例 #3
0
 private void PushIOS(string AppSecret, string ClientID, string Title, string Body, long TimeToLive, string exceptionid)
 {
     try
     {
         MgoogpsWebClient mgoo = new MgoogpsWebClient();
         mgoo.RequestUrl         = HOST;
         mgoo.RequestMethodType  = "POST";
         mgoo.RequestContentType = "application/x-www-form-urlencoded";
         Dictionary <string, string> headers = new Dictionary <string, string>();
         headers.Add("Authorization", "key=" + AppSecret);
         StringBuilder sb = new StringBuilder();
         // sb.Append("description=" + "测试推送" + "&");
         sb.Append("aps_proper_fields.title=" + Title + "&");
         //sb.Append("payload=" + payload + "&"); //	消息的内容。
         // sb.Append("aps_proper_fields.subtitle=" + "测试subtitle" + "&");
         sb.Append("aps_proper_fields.body=" + Body + "&");
         sb.Append("time_to_live=" + TimeToLive + "&");
         //sb.Append("extra.badge=1&"); //可选项。通知角标。
         sb.Append("aps_proper_fields.mutable-content=" + exceptionid + "&");
         sb.Append("extra.sound_url=default&"); //可选项,自定义消息铃声。当值为空时为无声,default为系统默认声音。
         sb.Append("registration_id=" + ClientID + "");
         mgoo.RequestPostData = Encoding.UTF8.GetBytes(sb.ToString());
         string reulst = mgoo.RequestSend(headers);
         Utils.log("IOS---" + reulst, "MiPush" + DateTime.Now.ToString("yyyyMM") + "-" + DateTime.Now.DayOfWeek + ".log");
     }
     catch (Exception ex)
     {
         Utils.log("PushIOS Error:" + ex.Message + ",Source:" + ex.Source + ",StackTrace:" + ex.StackTrace);
     }
 }
コード例 #4
0
        public void PaySuccessPush(string OpenID, string DeviceName, string Fee, string PayDate, string Bank, string OrderNo)
        {
            string rulst = "";

            try
            {
                WeixinOper       wo           = new WeixinOper();
                string           access_token = wo.AccessToken();
                MgoogpsWebClient mwc          = new MgoogpsWebClient();
                mwc.RequestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
                SQLServerOperating          s   = new SQLServerOperating();
                Dictionary <string, string> dic = s.Selects("select ProductBody,tp.RenewalDate from Orders o inner join TariffPackages tp on tp.id=o.TariffID where OrderNo = @OrderNo", new SqlParameter[] { new SqlParameter("OrderNo", OrderNo) }).toDictionary();
                string pushContent = wo.GetPaySuccessText(OpenID, DeviceName, Fee, PayDate, OrderNo, Bank, dic["ProductBody"], dic["RenewalDate"]);
                mwc.RequestPostData = Encoding.UTF8.GetBytes(pushContent);
                rulst = mwc.RequestSend();
                Dictionary <string, string> res = Utils.ToDictionary(rulst);
                if (res["errcode"].Equals("0") && res["errmsg"].Equals("ok"))
                {
                    Utils.log("充值成功提醒推送成功:" + DeviceName);
                }
                else
                {
                    Utils.log("充值成功微信推送失败" + rulst, "WeChatExpirePush.log");
                }
            }
            catch (Exception ex)
            {
                Utils.log("PaySuccessPush Error:" + ex.Message + ",StackTrace:" + ex.StackTrace + ",Source:" + ex.Source + ",rulst:" + rulst);
            }
        }
コード例 #5
0
        private static void Send(string phone)
        {
            string server_host_test = "http://121.41.16.92/smsSend.do";
            string server_host      = "http://120.55.248.18/smsSend.do";


            string username = "******";
            MD5    md5      = MD5.Create("");
            var    md5Byte  = MD5.Create("mgdz" + "hI6eI2cN").ComputeHash(Encoding.UTF8.GetBytes(""));

            string password = System.BitConverter.ToString(md5Byte).Replace("-", "").ToUpper();

            string mobile = "18507480591";

            string content = string.Format("【美谷科技】您的设备{0},在{1}触发了{2},请留意。", "测试", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "震动报警");


            string[] parsList = new string[4];
            parsList[0] = "username=mgdz";
            parsList[1] = "password="******"mobile=" + phone;
            parsList[3] = "content=" + content;

            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodType  = "POST";
            webClient.RequestContentType = "application/x-www-form-urlencoded";
            webClient.RequestPostData    = Encoding.UTF8.GetBytes(string.Join("&", parsList));
            webClient.RequestUrl         = server_host;
            string res = webClient.RequestSend();
        }
コード例 #6
0
        public string GetDeviceList(string user, string devicename)
        {
            MgoogpsWebClient mwc = new MgoogpsWebClient();

            mwc.RequestMethodType = "GET";
            mwc.RequestMethodName = "/service/getdevices/?user=" + user;
            string json = mwc.RequestSend();


            JavaScriptSerializer js = new JavaScriptSerializer();

            js.MaxJsonLength = int.MaxValue;
            List <DeviceInfo> dList = js.Deserialize <List <DeviceInfo> >(json);
            List <DeviceInfo> resultList;

            if (!string.IsNullOrWhiteSpace(devicename))
            {
                resultList = new List <DeviceInfo>();
                for (int i = 0; i < dList.Count; i++)
                {
                    if (dList[i].Name.IndexOf(devicename) >= 0 || dList[i].Id.IndexOf(devicename) >= 0)
                    {
                        resultList.Add(dList[i]);
                    }
                }
                if (resultList != null)
                {
                    return(Utils.ToJson(resultList));
                }
            }
            return(Utils.ToJson(dList));
        }
コード例 #7
0
 /// <summary>
 /// 根据IMEI获取历史数据
 /// </summary>
 /// <param name="ID"></param>
 /// <param name="StartTime"></param>
 /// <param name="EndTime"></param>
 /// <returns></returns>
 public List <History> GetHistory(string ID, string StartTime, string EndTime)
 {
     try
     {
         MgoogpsWebClient mwc = new MgoogpsWebClient();
         mwc.RequestMethodName  = "/service/gethistory/?param=id," + ID + "&starttime," + Convert.ToDateTime(StartTime).Ticks + "&endtime," + Convert.ToDateTime(EndTime).Ticks;
         mwc.RequestPostData    = new byte[0];
         mwc.RequestContentType = "application/x-www-form-urlencoded";
         string data             = mwc.RequestSend();
         JavaScriptSerializer js = new JavaScriptSerializer();
         js.MaxJsonLength = Int32.MaxValue;
         List <History> his = js.Deserialize <List <History> >(data);
         List <History> retData = new List <History>();
         double         lat = 0, lng = 0;
         foreach (History item in his)
         {
             if (!string.IsNullOrWhiteSpace(item.Lat) || !string.IsNullOrWhiteSpace(item.Lon))
             {
                 Gps g = EvilTransform.PositionUtil.gcj02_To_Bd09(Convert.ToDouble(item.Lat), Convert.ToDouble(item.Lon));
                 lat      = g.getWgLat();
                 lng      = g.getWgLon();
                 item.Lat = lat.ToString(); item.Lon = lng.ToString();
                 retData.Add(item);
             }
         }
         return(retData);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
コード例 #8
0
        public string GetAlarmByDeviceID(string DeviceID, string StartTime, string EndTime)
        {
            MgoogpsWebClient mwc = new MgoogpsWebClient();

            mwc.RequestMethodName = "/service/getalarmhistorybydevice/?param=id," + DeviceID + "&starttime," + Convert.ToDateTime(StartTime).Ticks + "&endtime," + Convert.ToDateTime(EndTime).Ticks + "";
            return(mwc.RequestSend());
        }
コード例 #9
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public string GetUserInfo()
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodType = "GET";
            webClient.RequestMethodName = "/service/getuserinfo/?user=" + Utils.GetSessionUserID();
            return(webClient.RequestSend());
        }
コード例 #10
0
        /// <summary>
        /// 标记已读消息
        /// </summary>
        /// <param name="ObjectID">消息ID</param>
        /// <returns></returns>
        public string DeleteMsg(string ObjectID)
        {
            MgoogpsWebClient mwc = new MgoogpsWebClient();

            mwc.RequestMethodName = "/service/deletealarmone/?objectId=" + ObjectID;
            mwc.RequestMethodType = "DELETE";
            mwc.RequestPostData   = Encoding.UTF8.GetBytes("objectId=" + ObjectID);
            return(mwc.RequestSend());
        }
コード例 #11
0
        /// <summary>
        /// 根据IMEI号获取设备信息(实时跟踪也用此方法)
        /// </summary>
        /// <param name="Imei"></param>
        /// <returns></returns>
        public string GetDeviceData(string Imei)
        {
            try
            {
                MgoogpsWebClient mwc = new MgoogpsWebClient();
                mwc.RequestMethodName = "/service/getlocationbydevice/?id=" + Imei;
                mwc.RequestMethodType = "GET";
                string jsonStr                   = mwc.RequestSend();
                JavaScriptSerializer jss         = new JavaScriptSerializer();
                Entity.DeviceDetail  device      = jss.Deserialize <Entity.DeviceDetail>(jsonStr);
                DateTime             connectTime = Convert.ToDateTime(device.ConnectTime);

                if (connectTime < Convert.ToDateTime("0010-01-01"))
                {
                    device.DeviceStatus = (int)DeviceStatus.未激活 + "," + device.Speed;
                }
                else if ((DateTime.Now - connectTime).TotalMinutes > Utils.OffLineMinute)
                {
                    device.DeviceStatus = (int)DeviceStatus.离线 + "," + Convert.ToInt32((DateTime.Now - connectTime).TotalMinutes);
                }
                else if (Convert.ToInt32(device.Speed) > 0)
                {
                    device.DeviceStatus = (int)DeviceStatus.行驶 + "";
                }
                else if (Convert.ToInt32(device.Speed) <= 0 && (DateTime.Now - connectTime).TotalMinutes <= Utils.OffLineMinute)
                {
                    device.DeviceStatus = (int)DeviceStatus.停止 + "," + (DateTime.Now - Convert.ToDateTime(connectTime)).TotalMinutes;;
                }
                double lat = 0, lng = 0;
                if (!string.IsNullOrWhiteSpace(device.Lbs.toStringEmpty()))
                {
                    Dictionary <string, object> lbs = (Dictionary <string, object>)device.Lbs;
                    if (lbs["time"].toStringEmpty().toDateTime() > device.ConnectTime.toDateTime())
                    {
                        device.Lat = lbs["lat"].toStringEmpty(); device.Lon = lbs["lon"].toStringEmpty();
                    }
                    else if (device.Lat.toDouble() == 0.00 || device.Lon.toDouble() == 0.00)
                    {
                        device.Lat = lbs["lat"].toStringEmpty(); device.Lon = lbs["lon"].toStringEmpty();
                    }
                    device.DeviceTime = lbs["time"].toStringEmpty().toDateTime().AddHours(8).ToString();
                }
                Gps gps = EvilTransform.PositionUtil.gcj02_To_Bd09(double.Parse(device.Lat), double.Parse(device.Lon));
                lat        = gps.getWgLat();
                lng        = gps.getWgLon();
                device.Lat = lat + ""; device.Lon = lng + "";

                device.Address = bllGetAddress(double.Parse(device.Lat), double.Parse(device.Lon));
                return(jss.Serialize(device));
            }
            catch (Exception ex)
            {
                Utils.log("GetDeviceData方法出错:" + ex.Message + ", 堆栈信息:" + ex.StackTrace);
                throw ex;
            }
        }
コード例 #12
0
        public List <Dictionary <string, string> > GetUserZTree(String UserType = null)
        {
            MgoogpsWebClient mwc = new MgoogpsWebClient();

            mwc.RequestMethodType = "GET";
            mwc.RequestMethodName = "/service/getusers/?user=" + SessionOper.GetSessionUserID();

            String jsonStr = mwc.RequestSend();
            List <Dictionary <string, string> > zTreeList = Utils.ToList(jsonStr);

            return(zTreeList);
        }
コード例 #13
0
        /// <summary>
        /// 根据IMEI号获取设备的信息
        /// </summary>
        /// <param name="imei"></param>
        /// <returns></returns>
        public string GetDeviceInfo(string imei)
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodType = "GET";
            webClient.RequestMethodName = "/service/getdevicebyid/?id=" + imei;
            string str = webClient.RequestSend();
            JavaScriptSerializer js   = new JavaScriptSerializer();
            DeviceInfo           info = js.Deserialize <DeviceInfo>(str);

            return(js.Serialize(info));
        }
コード例 #14
0
        public string SetUserInfo(string user, string username, string email, string address)
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodName = "/service/modifyuser/?param=user," + user + "&username," + username + "&email," + email + "&address," + address;
            string str = webClient.RequestSend();

            if (str == "1")
            {
                Utils.SetSessionUserName(username);
            }
            return(str);
        }
コード例 #15
0
        /// <summary>
        /// 获取所有子用户的设备数量
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GetALLUser(string user)
        {
            MgoogpsWebClient mvc = new MgoogpsWebClient();

            mvc.RequestMethodType = "GET";
            mvc.RequestMethodName = "/service/getusers/?user="******"_id"]);

                allcount     += Convert.ToInt32(total["count"]);
                allonLine    += Convert.ToInt32(total["onLine"]);
                alloffLine   += Convert.ToInt32(total["offLine"]);
                allday       += Convert.ToInt32(total["days"]);
                allnotactive += Convert.ToInt32(total["overdue"]);
                allexpire    += Convert.ToInt32(total["expire"]);
            }
            Dictionary <string, string> dicc = new Dictionary <string, string>();

            dicc["allcount"]     = allcount + "";
            dicc["allonLine"]    = allonLine + "";
            dicc["alloffLine"]   = alloffLine + "";
            dicc["alldays"]      = allday + "";
            dicc["allnotactive"] = allnotactive + "";
            dicc["allexpire"]    = allexpire + "";
            Dictionary <string, string> DeivceCount = GetDeviceCount(user);

            dicc["count"]   = DeivceCount["count"];
            dicc["onLine"]  = DeivceCount["onLine"];
            dicc["offLine"] = DeivceCount["offLine"];
            dicc["days"]    = DeivceCount["days"];
            dicc["overdue"] = DeivceCount["overdue"];
            dicc["expire"]  = DeivceCount["expire"];

            return(Utils.ToJson(dicc)); //集合转JSon
        }
コード例 #16
0
        /// <summary>
        /// 修改指定设备的信息
        /// </summary>
        /// <param name="id">IMEI</param>
        /// <param name="name">设备名称</param>
        /// <param name="carnumber">车牌号</param>
        /// <param name="contact">联系人</param>
        /// <param name="cellphone">联系号码</param>
        /// <param name="image">图像名称</param>
        /// <param name="islbs">是否启用lbs</param>
        /// <returns></returns>
        public string SetDeviceInfo(string id, string name, string carnumber, string contact, string cellphone, string image = null, string islbs = null)
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestMethodType = "POST";
            string par = "/service//modifydevice/?param=id," + id + "&name," + name + "&carnumber," + carnumber + "&contact," + contact + "&cellphone," + cellphone;

            if (image != null)
            {
                par += "&image," + image;
            }
            if (islbs != null)
            {
                par += "&islbs," + islbs;
            }
            webClient.RequestMethodName = par;
            return(webClient.RequestSend());
        }
コード例 #17
0
ファイル: BllLogin.cs プロジェクト: mgoogps/mgoo
        public bool WebSystemLogin_Bll(string loginName, string passWord, string loginType)
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            try
            {
                webClient.RequestMethodName  = "/account/login";
                webClient.RequestPostData    = Encoding.UTF8.GetBytes("loginName=" + loginName + "&passWord="******"application/x-www-form-urlencoded";
                string data = webClient.RequestSend();
                if (data.IndexOf("error") > 0)
                {
                    return(false);
                }
                else
                {
                    MG_DAL.LoginUserInfo        _loginUserInfo = new MG_DAL.LoginUserInfo();
                    Dictionary <string, object> d = (Dictionary <string, object>)Utils.ToObject(data);

                    Dictionary <string, object> loginUserDic = (Dictionary <string, object>)d["UserInfo"];

                    _loginUserInfo.ToKen   = d["Token"].toStringEmpty();
                    MgoogpsWebClient.ToKen = d["Token"].toStringEmpty();

                    _loginUserInfo.UserID    = loginUserDic["_id"].toStringEmpty();
                    _loginUserInfo.UserName  = loginUserDic["username"].toStringEmpty();
                    _loginUserInfo.Address   = loginUserDic["address"].toStringEmpty();
                    _loginUserInfo.EMail     = loginUserDic["email"].toStringEmpty();
                    _loginUserInfo.LoginTime = DateTime.Now;
                    _loginUserInfo.LoginType = LoginType.User;
                    SessionOper.SetSession(_loginUserInfo, SessionOper.SessionName);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Utils.log("登录出错:" + loginName + "," + passWord + " --异常信息:" + ex.Message + ",堆栈信息:" + ex.StackTrace);
                Utils.log(ex.Message + "-" + webClient.RequestUrl + "-" + webClient.RequestMethodName);
                //  throw new Exception(ex.Message+"-"+webClient.RequestUrl+"-" + webClient.RequestMethodName);
                throw ex;
            }
        }
コード例 #18
0
        /// <summary>
        /// 获取用户下所有设备的报警信息
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        public List <Alarms> GetAlarms(string UserID)
        {
            MgoogpsWebClient mwc = new MgoogpsWebClient();

            mwc.RequestMethodName = "/service/getalarms/?user="******"GET";
            string jsonStr = mwc.RequestSend();
            JavaScriptSerializer js = new JavaScriptSerializer();
            List <Alarms>        list = js.Deserialize <List <Alarms> >(jsonStr);
            double lat = 0, lng = 0;

            for (int i = 0; i < list.Count; i++)
            {
                Gps g = EvilTransform.PositionUtil.gcj02_To_Bd09(Convert.ToDouble(list[i].Lat), Convert.ToDouble(list[i].Lon));
                lat         = g.getWgLat();
                lng         = g.getWgLon();
                list[i].Lat = lat.ToString(); list[i].Lon = lng.ToString();
            }
            return(list);
        }
コード例 #19
0
        public string AddGroups(string id, string parent, string username, string password, string cellphone, string address, string path, string email, string weixin)
        {
            MgoogpsWebClient webClient = new MgoogpsWebClient();

            webClient.RequestPostData = Encoding.UTF8.GetBytes(string.Format("_id={0}&parent={1}&username={2}&password={3}&cellphone={4}&address={5}&path={6}&email={6}&weixin={7}"
                                                                             , id, parent, username, "123456", "135445", "东莞", "path", "weixin")); // //

            webClient.RequestMethodName = "account/AddAccount/";
            string str = webClient.RequestSend();

            //public string _id { get; set; }
            //public string cellphone { get; set; }
            //public string username { get; set; }
            //public string password { get; set; }
            //public string address { get; set; }
            //public string parent { get; set; }
            //public string path { get; set; }
            //public string email { get; set; }
            //public string weixin { get; set; }

            return(str);
        }
コード例 #20
0
        public string AccessToken()
        {
            string           result = "";
            MgoogpsWebClient mwc    = new MgoogpsWebClient();

            try
            {
                //string token = ConfigurationManager.AppSettings["token"].ToStringEmpty();
                //if (!this.bool_token)
                //{
                //    return Utils.GetResult("token错误!", statusCode.Code.failure);
                //}


                string wx_access_token = Utils.GetCache <string>("access_token");
                if (string.IsNullOrEmpty(wx_access_token))
                {
                    mwc.RequestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + this.wx_appid + "&secret=" + this.wx_secret;

                    mwc.RequestMethodType = "GET";
                    result = mwc.RequestSend();
                    // {"access_token":"dV2gTgBkohEiOm8rnC6eJ2YHFTNdBXe5vFizvwJShc2z0lLLuE9TvidwWFQNuezOJ3IGswlV5tPLAbASteP8myaahTbA7zLrnzeaF17KCgwVZX0SV1bbnNDLl31ULqb3JMKgCEAUXV","expires_in":7200}
                    Dictionary <string, string> res = Utils.ToDictionary(result);
                    wx_access_token = res["access_token"];
                    if (!string.IsNullOrEmpty(wx_access_token))
                    {
                        Utils.SetCache("access_token", wx_access_token, Convert.ToDouble(res["expires_in"]) / 60);
                        return(wx_access_token);
                    }
                    return(string.Empty);
                }
                return(wx_access_token);
            }
            catch (Exception ex)
            {
                Utils.log("WeixinOper.AccessToken:" + ex.Message);
                return(string.Empty);
            }
        }
コード例 #21
0
        private string Getjsapi_ticket()
        {
            MgoogpsWebClient mwc             = new MgoogpsWebClient();
            string           wx_jsapi_ticket = Utils.GetCache <string>("jsapi_ticket");

            if (string.IsNullOrEmpty(wx_jsapi_ticket))
            {
                string wx_access_token = AccessToken();
                mwc.RequestUrl        = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + wx_access_token + "&type=jsapi";
                mwc.RequestMethodType = "GET";
                string result = mwc.RequestSend();
                //{"errcode":0,"errmsg":"ok","ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA","expires_in":7200}
                Dictionary <string, string> res = Utils.ToDictionary(result);
                wx_jsapi_ticket = res["ticket"];
                if (!string.IsNullOrEmpty(wx_jsapi_ticket))
                {
                    Utils.SetCache("jsapi_ticket", wx_jsapi_ticket, Convert.ToDouble(res["expires_in"]) / 60);
                    return(wx_jsapi_ticket);
                }
                return(string.Empty);
            }
            return(wx_jsapi_ticket);
        }
コード例 #22
0
        public string AccessToken()
        {
            try
            {
                //string token = ConfigurationManager.AppSettings["token"].ToStringEmpty();
                //if (!this.bool_token)
                //{
                //    return Utils.GetResult("token错误!", statusCode.Code.failure);
                //}

                MgoogpsWebClient mwc             = new MgoogpsWebClient();
                string           wx_access_token = (string)HttpRuntime.Cache.Get("access_token");// Utils.GetCache<string>("access_token");
                if (string.IsNullOrEmpty(wx_access_token))
                {
                    mwc.RequestUrl        = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxda27104d229a3608&secret=a754e16403dd067372dbfe2f17a6c587";
                    mwc.RequestMethodType = "GET";
                    string result = mwc.RequestSend();
                    // {"access_token":"dV2gTgBkohEiOm8rnC6eJ2YHFTNdBXe5vFizvwJShc2z0lLLuE9TvidwWFQNuezOJ3IGswlV5tPLAbASteP8myaahTbA7zLrnzeaF17KCgwVZX0SV1bbnNDLl31ULqb3JMKgCEAUXV","expires_in":7200}
                    Dictionary <string, string> res = MG_BLL.Utils.ToDictionary(result);
                    wx_access_token = res["access_token"];
                    if (!string.IsNullOrEmpty(wx_access_token))
                    {
                        HttpRuntime.Cache.Insert("access_token", wx_access_token, null, DateTime.Now.AddMinutes(Convert.ToDouble(res["expires_in"]) / 60), TimeSpan.Zero);

                        return(wx_access_token);
                    }
                    return(string.Empty);
                }
                return(wx_access_token);
            }
            catch (Exception ex)
            {
                Utils.log("WeixinOper.AccessToken:" + ex.Message);
                return(string.Empty);
            }
        }
コード例 #23
0
        //获得当前登录用户的设备数量
        public Dictionary <string, string> GetDeviceCount(string user)
        {
            try
            {
                MgoogpsWebClient mwc = new MgoogpsWebClient();
                mwc.RequestMethodType = "GET";
                //  http://api.mgoogps.com/service/getusers/?user=
                mwc.RequestMethodName = "/service/getlocations?user="******"locatlist"] as ArrayList;

                //获取过期设备
                MgoogpsWebClient mvc = new MgoogpsWebClient();
                mvc.RequestMethodType = "GET";
                mvc.RequestMethodName = "/service/getdevices?user="******"activetime"]);
                    if ((DateTime.Now - d).TotalDays > 7 && d > DateTime.MinValue.AddHours(8))
                    {
                        days++;
                    }
                }

                int onLine  = 0;
                int offLine = 0;
                int overdue = 0;
                int expire  = 0;
                Dictionary <string, object> dic;
                for (int i = 0; i < list.Count; i++)
                {
                    dic = list[i] as Dictionary <string, object>;
                    DateTime act         = Convert.ToDateTime(totall[i]["activetime"]);
                    DateTime connectTime = Convert.ToDateTime(dic["connecttime"]);
                    DateTime endtime     = Convert.ToDateTime(dic["endtime"]);
                    //int days = Convert.ToInt32( activetime);
                    //在线设备
                    if ((DateTime.Now - connectTime).TotalMinutes < Utils.OffLineMinute)
                    {
                        onLine++;
                    }
                    //离线设备
                    if ((DateTime.Now - connectTime).TotalMinutes > Utils.OffLineMinute && connectTime > DateTime.MinValue.AddHours(8))
                    {
                        offLine++;
                    }
                    //未激活设备
                    //小于当前时间并且不等于0001-01-01

                    if (act <= DateTime.MinValue.AddHours(8))
                    {
                        overdue++;
                    }
                    if (endtime < DateTime.Now && endtime > DateTime.MinValue.AddHours(8))
                    {
                        expire++;
                    }
                }
                Dictionary <string, string> dicTotal = new Dictionary <string, string>();
                dicTotal["count"]   = list.Count + "";
                dicTotal["onLine"]  = onLine + "";
                dicTotal["offLine"] = offLine + "";
                dicTotal["days"]    = days + "";
                dicTotal["overdue"] = overdue + "";
                dicTotal["expire"]  = expire + "";

                return(dicTotal);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #24
0
        /// <summary>
        /// 根据用户ID获取设备列表,包括该用户ID的报警消息条目
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="msgCount"></param>
        /// <returns></returns>
        public List <Entity.Devices> GetDevicesByUserID_Bll(String UserID, ref string msgCount)
        {
            List <Entity.Devices> deviceList = new List <Entity.Devices>();

            try
            {
                MgoogpsWebClient mwc = new MgoogpsWebClient();
                mwc.RequestMethodName = "/service/getlocations?user="******"GET";
                String jsonStr = mwc.RequestSend();
                JavaScriptSerializer        js  = new JavaScriptSerializer();
                Dictionary <string, object> dic = js.Deserialize <Dictionary <string, object> >(jsonStr);
                if (dic.Count < 2)
                {
                    throw new ArgumentNullException(dic["error"].ToString());
                }
                msgCount = Convert.ToString(dic["alertcount"]);
                ArrayList list = dic["locatlist"] as ArrayList;

                DateTime       connectTime;
                double         lat, lng;
                Entity.Devices device;

                for (int i = 0; i < list.Count; i++)
                {
                    device      = new Entity.Devices();
                    dic         = list[i] as Dictionary <string, object>;
                    lat         = 0; lng = 0;
                    connectTime = Convert.ToDateTime(dic["connecttime"]);
                    if (!string.IsNullOrWhiteSpace(dic["lbs"].toStringEmpty()))
                    {
                        Dictionary <string, object> lbs = (Dictionary <string, object>)dic["lbs"];
                        if (lbs["time"].toStringEmpty().toDateTime() > connectTime)
                        {
                            dic["lat"] = lbs["lat"]; dic["lon"] = lbs["lon"];
                        }
                        else if (Convert.ToDouble(dic["lat"]) == 0.00 || Convert.ToDouble(dic["lon"]) == 0.00)
                        {
                            dic["lat"] = lbs["lat"]; dic["lon"] = lbs["lon"];
                        }
                        device.ConnectTime = lbs["time"].toStringEmpty().toDateTime().AddHours(8).ToString();
                    }
                    Gps g = EvilTransform.PositionUtil.gcj02_To_Bd09(Convert.ToDouble(dic["lat"]), Convert.ToDouble(dic["lon"]));
                    lat        = g.getWgLat();
                    lng        = g.getWgLon();
                    device.Lat = lat + ""; device.Lon = lng + "";

                    device.ConnectTime = connectTime.ToString("yyyy-MM-dd HH:mm:ss");
                    device.Id          = Convert.ToString(dic["id"]);
                    device.Name        = Convert.ToString(dic["name"]);
                    device.EndTime     = Convert.ToString(dic["endtime"]); device.DeviceTime = Convert.ToString(dic["devicetime"]);
                    device.Direction   = Convert.ToString(dic["direction"]);
                    device.Speed       = Convert.ToString(dic["speed"]); device.Status = Convert.ToString(dic["status"]);
                    device.OnLine      = !((DateTime.Now - connectTime).TotalMinutes > Utils.OffLineMinute);

                    if (connectTime < Convert.ToDateTime("0010-01-01"))
                    {
                        device.DeviceStatus = (int)DeviceStatus.未激活 + "," + device.Speed;
                    }
                    else if ((DateTime.Now - connectTime).TotalMinutes > Utils.OffLineMinute)
                    {
                        device.DeviceStatus = (int)DeviceStatus.离线 + "," + Convert.ToInt32((DateTime.Now - connectTime).TotalMinutes);
                    }
                    else if (Convert.ToInt32(device.Speed) > 0)
                    {
                        device.DeviceStatus = (int)DeviceStatus.行驶 + "," + Convert.ToDouble(device.Speed) + "km";
                    }
                    else if (Convert.ToInt32(device.Speed) <= 0 && (DateTime.Now - connectTime).TotalMinutes <= Utils.OffLineMinute)
                    {
                        device.DeviceStatus = (int)DeviceStatus.停止 + "," + (DateTime.Now - Convert.ToDateTime(connectTime)).TotalMinutes;
                    }
                    deviceList.Add(device);
                }
                return(deviceList);
            }
            catch (Exception ex)
            {
                Utils.log("GetDevicesByUserID_Bll方法出错:" + ex.Message + ", 堆栈信息:" + ex.StackTrace);
                return(deviceList);
            }
        }
コード例 #25
0
        public string GetMileage(string DeviceID, string StartTime, string EndTime)
        {
            if (string.IsNullOrWhiteSpace(DeviceID) || DeviceID == "null")
            {
                return("");
            }
            long       sticks = Convert.ToDateTime(StartTime).Ticks;
            long       eticks = Convert.ToDateTime(EndTime).Ticks;
            BllMonitor bm     = new BllMonitor();

            try
            {
                List <History> his = bm.GetHistory(DeviceID, StartTime, EndTime);
                DataTable      dt  = new DataTable();
                dt.Columns.Add("time"); dt.Columns.Add("lat"); dt.Columns.Add("lon");
                int stopCount = 0; DateTime tempTime = default(DateTime);
                for (int i = 0; i < his.Count; i++)
                {
                    History h = his[i];
                    if (h.Speed < Utils.SpeedFilter)
                    {
                        continue;
                    }
                    DataRow dr = dt.NewRow();
                    dr["time"] = h.DeviceTime;
                    dr["lat"]  = h.Lat;
                    dr["lon"]  = h.Lon;
                    dt.Rows.Add(dr);
                }

                MgoogpsWebClient myWeb = new MgoogpsWebClient();
                myWeb.RequestMethodName = "/service/getalarmhistorybydevice/?param=id," + DeviceID + "&starttime," + sticks + "&endtime," + eticks;
                string json = myWeb.RequestSend();
                List <Dictionary <string, string> > alarmList = js.Deserialize <List <Dictionary <string, string> > >(json);
                Hashtable hb = new Hashtable();
                Dictionary <string, string> retu = new Dictionary <string, string>();
                string key = "";
                for (int i = 0; i < alarmList.Count; i++)
                {
                    Dictionary <string, string> dicAlarm = alarmList[i];
                    dicAlarm["alarmtime"] = Convert.ToDateTime(dicAlarm["alarmtime"]).ToString("yyyy-MM-dd");
                    key = dicAlarm["alarmtime"];// + "," + dicAlarm["alarmtype"];
                    if (retu.ContainsKey(key))
                    {
                        retu[key] = (Convert.ToInt32(retu[key]) + 1) + "";
                    }
                    else
                    {
                        retu[key] = "1";
                    }
                }
                Dictionary <string, string> rJson = new Dictionary <string, string>();
                foreach (KeyValuePair <string, string> item in retu)
                {
                    List <Dictionary <string, string> > points         = new List <Dictionary <string, string> >();
                    Dictionary <string, string>         alarmTypeCount = new Dictionary <string, string>();
                    key = item.Key.ToString();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DateTime t = Convert.ToDateTime(dt.Rows[i]["time"]);//.ToString();
                        if (key == t.ToString("yyyy-MM-dd"))
                        {
                            if (tempTime != default(DateTime))
                            {
                                double stopTime = (Convert.ToDateTime(dt.Rows[i]["time"]) - Convert.ToDateTime(tempTime)).TotalSeconds;
                                if (stopTime > Utils.StopSeconds)
                                {
                                    stopCount++;
                                    tempTime = default(DateTime);
                                }
                            }
                            tempTime = t;
                            Dictionary <string, string> point = new Dictionary <string, string>();
                            point.Add("lat", dt.Rows[i]["lat"].ToString()); point.Add("lon", dt.Rows[i]["lon"].ToString());
                            points.Add(point);
                        }
                    }
                    Dictionary <string, string> ss = new Dictionary <string, string>();
                    ss.Add("alarmcount", retu[key]); ss.Add("stopcount", stopCount + ""); ss.Add("points", Utils.ToJson(points));
                    rJson[key] = Utils.ToJson(ss);
                    stopCount  = 0;
                }
                return(Utils.ToJson(rJson));
            }
            catch
            {
                return("");
            }
        }
コード例 #26
0
        public string Pushed(string UserID, string DeviceName, string Message, string Date, string Lat, string Lng, string Remark, string exceptionid, string DeviceID)
        {
            try
            {
                int tryIndex              = 0;
                SQLServerOperating s      = GetSQLServerOperating();
                string             strSql = "select ID, UserID,LoginName, OpenID, CreateTime, UpdateTime from WechatUsers where UserID = @UserID and Deleted=0";
                DataTable          dt     = s.Selects(strSql, new SqlParameter[] { new SqlParameter("UserID", UserID) });
                if (dt.Rows.Count > 0)
                {
                    string           _lat         = Lat;
                    string           _lng         = Lng;
                    MgoogpsWebClient mwc          = new MgoogpsWebClient();
                    string           access_token = AccessToken();
                    if (string.IsNullOrEmpty(access_token))
                    {
                        return("未获取到access_token.");
                    }
                    int    count   = 0;
                    string rulst   = "";
                    string key     = Utils.GetAmapKey();
                    string logName = "PushedMessage" + DateTime.Now.ToString("yyyyMM") + ".log";
                    if (Lat.toDouble() == -1.0 && Lng.toDouble() == -1.0)
                    {
                        Dictionary <string, string> dic = s.Selects("select OLat,OLng from lklocation where deviceid=@DeviceID", new SqlParameter[] { new SqlParameter("DeviceID", DeviceID) }).toDictionary();
                        Lat = dic["OLat"];
                        Lng = dic["OLng"];
                    }
                    Gps g = Utils.gps84_To_Gcj02(Lat, Lng, key);
                    mwc.RequestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
                    string time = Date.toDateTime().ToString("yyyy-MM-dd HH:mm:ss");

                    //List<Task> taskList = new List<Task>();
                    // TaskFactory taskFactory = new TaskFactory();
                    // List<string> openids = new List<string>();
                    foreach (DataRow item in dt.Rows)
                    {
                        DataRow row = item;

                        //Task task = taskFactory.StartNew(() =>
                        // {
                        string openid      = row["OpenID"].toStringEmpty();
                        string pushContent = GetAlarmPushText(openid, DeviceName, Message, time, g.Address, Remark, exceptionid);
                        mwc.RequestPostData = Encoding.UTF8.GetBytes(pushContent);
                        rulst = mwc.RequestSend();
                        Dictionary <string, string> res = Utils.ToDictionary(rulst);
                        Utils.log(string.Format("{0},{1},{2},{3},{4},{5}", UserID, row["LoginName"], DeviceName, openid, time, Message), logName);
                        if (res["errcode"].Equals("0") && res["errmsg"].Equals("ok"))
                        {
                            count++;
                            continue;
                            //return Utils.GetResult("发送成功.", statusCode.Code.success);
                        }
                        else if (res["errcode"] == "40001") //获取access_token时AppSecret错误,或者access_token无效。请开发者认真比对AppSecret的正确性,或查看是否正在为恰当的公众号调用接口
                        {
                            if (tryIndex < 1)
                            {
                                Utils.SetCache("access_token", "");
                                AccessToken();
                                tryIndex++;
                                return(Pushed(UserID, DeviceName, Message, time, _lat, _lng, Remark, exceptionid, DeviceID));
                            }
                        }
                        else if (res["errcode"] == "43004") //接收者没有关注公众号
                        {
                            string sql = "delete from wechatusers where OpenID=@OpenID";
                            s.ExecuteSql(sql, new SqlParameter[] { new SqlParameter("OpenID", openid) });
                        }
                        Utils.log(string.Format("----发送失败 :{0},{1},{2},{3},{4},{5}", UserID, row["LoginName"], DeviceName, openid, time, Message), logName);
                        Utils.log("----rulst :" + rulst, logName);
                        // openids.Add(openid);
                        // return Utils.GetResult("发送失败.", statusCode.Code.failure);
                        //  });
                        //  taskList.Add(task);
                    }
                    //Task.WaitAll(taskList.ToArray());

                    if (count > 0)
                    {
                        return(Utils.GetResult("发送成功.", statusCode.Code.success));
                    }
                    else
                    {
                        return(Utils.GetResult("发送失败.", statusCode.Code.failure, rulst));
                    }
                }
                return(Utils.GetResult("该用户未绑定微信.", statusCode.Code.failure));
            }
            catch (Exception ex)
            {
                Utils.log("Pushed ERROR:" + ex.Message + ",堆栈:" + ex.StackTrace);
                throw ex;
            }
        }
コード例 #27
0
ファイル: Program.cs プロジェクト: mgoogps/mgoo
        private static void WeChatExpirePush()
        {
            try
            {
                MG_DAL.SQLServerOperating s = new MG_DAL.SQLServerOperating(connectionString);
                string strSql = @"select chat.OpenID,chat.UserID,d.DeviceName,d.DeviceID,d.SerialNumber,d.HireExpireDate,epr.WeChatLastPushTime from 
                                WeChatUsers chat inner join Devices d  on d.UserID=chat.UserID 
                                LEFT OUTER JOIN dbo.ExpiredPushRecord AS epr ON epr.DeviceID = d.DeviceID
                                where d.Deleted = 0  
                                AND d.HireExpireDate > GETDATE()  
                                AND chat.UpdateTime>DATEADD(MM,-2,GETDATE()) 
                              ";///  AND d.UserID in (6,7)
                //一个月内过期的设备并且是7天内没有推送过期通知的设备
                string monthWhere = " AND d.HireExpireDate < DATEADD(MM, 1, GETDATE()) AND(DATEDIFF(day, epr.WeChatLastPushTime, GETDATE()) >= 7 or epr.WeChatLastPushTime IS NULL) ";
                //7天内过期的设备,一天推送一次
                string    weekWhere = " AND d.HireExpireDate < DATEADD(DAY, 7, GETDATE()) AND(DATEDIFF(day, epr.WeChatLastPushTime, GETDATE()) >= 1 or epr.WeChatLastPushTime IS NULL) ";
                string    logText   = "";
                DataTable dt        = s.Selects(strSql + weekWhere);
                logText = "7天内过期设备: " + dt.Rows.Count + " 台";
                WeixinOper       wo           = new WeixinOper();
                string           access_token = wo.AccessToken();
                MgoogpsWebClient mwc          = new MgoogpsWebClient();
                mwc.RequestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
                string rulst = "";

                foreach (DataRow row in dt.Rows)
                {
                    string DeviceName  = string.IsNullOrEmpty(row["DeviceName"].ToString()) ? row["SerialNumber"].ToString() : row["DeviceName"].ToString();
                    string pushContent = wo.GetExpiresPushText(row["OpenID"].ToString(), row["DeviceID"].ToString(), DeviceName, row["HireExpireDate"].ToString());
                    mwc.RequestPostData = Encoding.UTF8.GetBytes(pushContent);
                    rulst = mwc.RequestSend();
                    Console.WriteLine(rulst);
                    Dictionary <string, string> res = Utils.ToDictionary(rulst);
                    if (res["errcode"].Equals("0") && res["errmsg"].Equals("ok"))
                    {
                        ExpiredPushRecord(row["UserID"].ToString(), row["DeviceID"].ToString(), row["HireExpireDate"].ToString(), "wechat");
                    }
                    else
                    {
                        Utils.log("7天内过期推送失败" + rulst, log_name);
                    }
                }

                dt       = s.Selects(strSql + monthWhere);
                logText += "        30天内过期设备: " + dt.Rows.Count + " 台";
                foreach (DataRow row in dt.Rows)
                {
                    string DeviceName  = string.IsNullOrEmpty(row["DeviceName"].ToString()) ? row["SerialNumber"].ToString() : row["DeviceName"].ToString();
                    string pushContent = wo.GetExpiresPushText(row["OpenID"].ToString(), row["DeviceID"].ToString(), DeviceName, row["HireExpireDate"].ToString());
                    mwc.RequestPostData = Encoding.UTF8.GetBytes(pushContent);
                    rulst = mwc.RequestSend();
                    Dictionary <string, string> res = Utils.ToDictionary(rulst);
                    if (res["errcode"].Equals("0") && res["errmsg"].Equals("ok"))
                    {
                        ExpiredPushRecord(row["UserID"].ToString(), row["DeviceID"].ToString(), row["HireExpireDate"].ToString(), "wechat");
                    }
                    else
                    {
                        Utils.log("30天内过期推送失败" + rulst, log_name);
                    }
                }
                Utils.log(logText, log_name);
            }
            catch (Exception ex)
            {
                Utils.log("WeChatExpirePush Error:" + ex.Message, log_name);
            }
        }