Пример #1
0
        /// <summary>
        /// 获取模板ID
        /// </summary>
        /// <param name="template_id_short">模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式</param>
        /// <returns></returns>
        public static string GetTemplateID(string template_id_short)
        {
            string templateID = string.Empty;

            try
            {
                string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token();
                string url          = string.Format("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token={0}", access_token);
                string json         = "{\"template_id_short\":\"" + template_id_short + "\"}";
                string resultJson   = HttpUtils.Ins.POST(url, json);
                Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson);
                if (reslut["errcode"].TryToInt(0) == 0)
                {
                    templateID = reslut["template_id"].TryToString();
                }
                else
                {
                    ClassLoger.Fail("WeChatTemplateAPI.GetTemplateID", resultJson);
                }
            } catch (Exception ex)
            {
                ClassLoger.Error("WeChatTemplateAPI.GetTemplateID", ex);
            }
            return(templateID);
        }
Пример #2
0
        /**
         *
         * 转换短链接
         * 该接口主要用于扫码原生支付模式一中的二维码链接转成短链接(weixin://wxpay/s/XXXXXX),
         * 减小二维码数据量,提升扫描速度和精确度。
         * @param WxPayData inputObj 提交给转换短连接API的参数
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回,其他抛异常
         */
        public static WxPayData ShortUrl(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/tools/shorturl";

            //检测必填参数
            if (!inputObj.IsSet("long_url"))
            {
                throw new WxPayException("需要转换的URL,签名用原串,传输需URL encode!");
            }

            inputObj.SetValue("appid", SystemSet.Serviceappid); //公众账号ID
            inputObj.SetValue("mch_id", SystemSet.Mch_id);      //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign());     //签名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;//请求开始时间

            ClassLoger.DEBUG("WxPayApi", "ShortUrl request : " + xml);
            string response = HttpService.Post(xml, url, false, timeOut);

            ClassLoger.DEBUG("WxPayApi", "ShortUrl response : " + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();

            result.FromXml(response);
            ReportCostTime(url, timeCost, result);//测速上报

            return(result);
        }
 /// <summary>
 /// 用户扫码授权回调
 /// </summary>
 /// <param name="code"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 // GET: WeChatLoginCallBack
 public ActionResult Index(string state, string code)
 {
     ClassLoger.Error("WeChatCallBackController.get.uid:", code, state);
     ThreadPool.QueueUserWorkItem(new WaitCallback(p => {
         try
         {
             if (!string.IsNullOrEmpty(code))
             {
                 getUserinfo(code, state);
             }
             else
             {
                 SaveNoUserinfo(state);
             }
         } catch (Exception ex)
         {
             ClassLoger.Error("WeChatLoginCallBack", ex);
         }
     }), null);
     //WxPayData res = new WxPayData();
     //res.SetValue("return_code", "SUCCESS");
     //res.SetValue("return_msg", "OK");
     ////ClassLoger.Info(this.GetType().ToString(), "order query success : " + res.ToXml());
     //Response.Write(res.ToXml());
     //Response.End();
     return(View());
 }
Пример #4
0
        /**
         *
         * 撤销订单API接口
         * @param WxPayData inputObj 提交给撤销订单API接口的参数,out_trade_no和transaction_id必填一个
         * @param int timeOut 接口超时时间
         * @throws WxPayException
         * @return 成功时返回API调用结果,其他抛异常
         */
        public static WxPayData Reverse(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/reverse";

            //检测必填参数
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("撤销订单API接口中,参数out_trade_no和transaction_id必须填写一个!");
            }

            inputObj.SetValue("appid", SystemSet.Serviceappid); //公众账号ID
            inputObj.SetValue("mch_id", SystemSet.Mch_id);      //商户号
            inputObj.SetValue("nonce_str", GenerateNonceStr()); //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign());     //签名
            string xml = inputObj.ToXml();

            var start = DateTime.Now;//请求开始时间

            ClassLoger.DEBUG("WxPayApi", "Reverse request : " + xml);

            string response = HttpService.Post(xml, url, true, timeOut);

            ClassLoger.DEBUG("WxPayApi", "Reverse response : " + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);

            WxPayData result = new WxPayData();

            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//测速上报

            return(result);
        }
        void ClearQC()
        {
            ClassLoger.Info("ClearQCPicJob.ClearQC", "定时清理图片文件任务启动");

            string key = CacheKey.GetQrCodeKey(DateTime.Now.AddDays(-1));

            if (RedisBase.ContainsKey(key))
            {
                int i = 0;
                while (IsWork)
                {
                    List <string> qcimageList = RedisBase.List_GetList <string>(key, i, 1000);
                    foreach (string pathStr in qcimageList)
                    {
                        try
                        {
                            if (File.Exists(pathStr))
                            {
                                File.Delete(pathStr);
                            }
                        }
                        catch (Exception ex) { }
                    }
                    i++;
                    if (qcimageList == null || qcimageList.Count == 0)
                    {
                        break;
                    }
                }

                RedisBase.List_RemoveAll <string>(key);
            }

            ClassLoger.Info("ClearQCPicJob.ClearQC", "图片文件清理完毕");
        }
Пример #6
0
        public static List <WeChatTags> GetAllGroup()
        {
            List <WeChatTags> grouplist = new List <WeChatTags>();

            try
            {
                string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token();
                string url          = string.Format("https://api.weixin.qq.com/cgi-bin/tags/get?access_token={0}", access_token);
                string json         = HttpUtils.Ins.GET(url);
                if (json.Contains("errcode"))
                {
                    ClassLoger.Fail("WeChatTagsAPI.GetAllGroup", json);
                    return(null);
                }
                Dictionary <string, object>         dic    = JsonHelper.DeserializeObject(json);
                List <Dictionary <string, object> > groups = dic["tags"] as List <Dictionary <string, object> >;
                foreach (var group in groups)
                {
                    WeChatTags info = new WeChatTags();
                    info.count = group["count"].TryToInt(0);
                    info.id    = group["id"].TryToInt(0);
                    info.name  = group["name"].TryToString();
                    grouplist.Add(info);
                }
            }
            catch (Exception ex)
            {
                ClassLoger.Error("WeChatGroupAPI.GetAllGroup", ex);
            }
            return(grouplist);
        }
Пример #7
0
 /// <summary>
 /// 用户名密码登录
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public UserInfo UserLogin(string userName, string password)
 {
     try
     {
         ISession         session     = NHibernateSessionFactory.getSession();
         ITransaction     transaction = session.BeginTransaction();
         string           sql         = string.Format("select * from  UserInfo  where State=0 and  Password='******' and  UserName='******';", getPassword(password), userName);
         IList <UserInfo> wlist       = session.CreateSQLQuery(sql).AddEntity(typeof(UserInfo)).List <UserInfo>();
         if (wlist == null || wlist.Count == 0)
         {
             sql   = string.Format("select * from  UserInfo  where State=0 and   Password='******' and  Telephone='{1}';", getPassword(password), userName);
             wlist = session.CreateSQLQuery(sql).AddEntity(typeof(UserInfo)).List <UserInfo>();
         }
         if (wlist == null || wlist.Count == 0)
         {
             sql   = string.Format("select * from  UserInfo  where State=0 and  Password='******' and  Email='{1}';", getPassword(password), userName);
             wlist = session.CreateSQLQuery(sql).AddEntity(typeof(UserInfo)).List <UserInfo>();
         }
         session.Flush();
         transaction.Commit();
         session.Close();
         if (wlist != null)
         {
             return(wlist.FirstOrDefault());
         }
     }
     catch (Exception ex)
     {
         ClassLoger.Error("UserInfoDal.UserLogin", ex);
     }
     return(null);
 }
Пример #8
0
        /// <summary>
        /// 批量为用户打标签
        /// </summary>
        /// <param name="openIDList"></param>
        /// <param name="tagid"></param>
        /// <returns></returns>
        public static bool batchtagging(List <string> openIDList, int tagid)
        {
            if (openIDList == null || openIDList.Count == 0 || tagid == 0)
            {
                return(false);
            }
            TagUserList tlist = new TagUserList();

            tlist.openid_list = openIDList;
            tlist.tagid       = tagid;
            try
            {
                string access_token = WeChatAccessTokenAPI.GetWeChatAccess_token();
                string url          = string.Format("https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={0}", access_token);
                string posJson      = JsonHelper.SerializeObject(tlist);
                string resultJson   = HttpUtils.Ins.POST(url, posJson);
                Dictionary <string, object> reslut = JsonHelper.DeserializeObject(resultJson);
                if (reslut["errcode"].TryToInt(0) == 0)
                {
                    return(true);
                }
            } catch (Exception ex)
            {
                ClassLoger.Error("WeChatTagsAPI.batchtagging", ex);
            }
            return(false);
        }
Пример #9
0
        /**
         *
         * 检测签名是否正确
         * 正确返回true,错误抛异常
         */
        public bool CheckSign()
        {
            //如果没有设置签名,则跳过检测
            if (!IsSet("sign"))
            {
                ClassLoger.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
                throw new WxPayException("WxPayData签名存在但不合法!");
            }
            //如果设置了签名但是签名为空,则抛异常
            else if (GetValue("sign") == null || GetValue("sign").ToString() == "")
            {
                ClassLoger.Error(this.GetType().ToString(), "WxPayData签名存在但不合法!");
                throw new WxPayException("WxPayData签名存在但不合法!");
            }

            //获取接收到的签名
            string return_sign = GetValue("sign").ToString();

            //在本地计算新的签名
            string cal_sign = MakeSign();

            if (cal_sign == return_sign)
            {
                return(true);
            }

            ClassLoger.Error(this.GetType().ToString(), "WxPayData签名验证错误!");
            throw new WxPayException("WxPayData签名验证错误!");
        }
Пример #10
0
        /**
         *
         * 网页授权获取用户基本信息的全部过程
         * 详情请参看网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
         * 第一步:利用url跳转获取code
         * 第二步:利用code去获取openid和access_token
         *
         */
        //public void GetOpenidAndAccessToken()
        //{
        //    if (!string.IsNullOrEmpty(HttpContext.Request.QueryString["code"]))
        //    {
        //        //获取code码,以获取openid和access_token
        //        string code = HttpContext.Request.QueryString["code"];
        //        ClassLoger.DEBUG(this.GetType().ToString(), "Get code : " + code);
        //        GetOpenidAndAccessTokenFromCode(code);
        //    }
        //    else
        //    {
        //        //构造网页授权获取code的URL
        //        string host = HttpContext.Request.Url.Host;
        //        string path = HttpContext.Request.Path;
        //        string redirect_uri = HttpUtils.Ins.UrlEncode("http://" + host + path);
        //        WxPayData data = new WxPayData();
        //        data.SetValue("appid", SystemSet.Serviceappid);
        //        data.SetValue("redirect_uri", redirect_uri);
        //        data.SetValue("response_type", "code");
        //        data.SetValue("scope", "snsapi_base");
        //        data.SetValue("state", "STATE" + "#wechat_redirect");
        //        string url = "https://open.weixin.qq.com/connect/oauth2/authorize?" + data.ToUrl();
        //        ClassLoger.DEBUG(this.GetType().ToString(), "Will Redirect to URL : " + url);
        //        try
        //        {
        //            //触发微信返回code码
        //            HttpContext.Response.Redirect(url);//Redirect函数会抛出ThreadAbortException异常,不用处理这个异常
        //        }
        //        catch (System.Threading.ThreadAbortException ex)
        //        {
        //        }
        //    }
        //}


        /**
         *
         * 通过code换取网页授权access_token和openid的返回数据,正确时返回的JSON数据包如下:
         * {
         *  "access_token":"ACCESS_TOKEN",
         *  "expires_in":7200,
         *  "refresh_token":"REFRESH_TOKEN",
         *  "openid":"OPENID",
         *  "scope":"SCOPE",
         *  "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
         * }
         * 其中access_token可用于获取共享收货地址
         * openid是微信支付jsapi支付接口统一下单时必须的参数
         * 更详细的说明请参考网页授权获取用户基本信息:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
         * @失败时抛异常WxPayException
         */
        public void GetOpenidAndAccessTokenFromCode(string code)
        {
            try
            {
                //构造获取openid及access_token的url
                WxPayData data = new WxPayData();
                data.SetValue("appid", SystemSet.Serviceappid);
                data.SetValue("secret", SystemSet.Serviceappsecret);
                data.SetValue("code", code);
                data.SetValue("grant_type", "authorization_code");
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

                //请求url以获取数据
                string result = HttpUtils.Ins.GET(url);

                ClassLoger.DEBUG(this.GetType().ToString(), "GetOpenidAndAccessTokenFromCode response : " + result);

                //保存access_token,用于收货地址获取
                JsonData jd = JsonMapper.ToObject(result);
                access_token = (string)jd["access_token"];

                //获取用户openid
                openid = (string)jd["openid"];

                ClassLoger.DEBUG(this.GetType().ToString(), "Get openid : " + openid);
                ClassLoger.DEBUG(this.GetType().ToString(), "Get access_token : " + access_token);
            }
            catch (Exception ex)
            {
                ClassLoger.Error(this.GetType().ToString(), ex.ToString());
                throw new WxPayException(ex.ToString());
            }
        }
        /// <summary>
        /// 微信开放平台拉取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="access_token">网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同</param>
        /// <param name="openid">用户的唯一标识</param>
        /// <returns></returns>
        public static WeChatUserInfo GetWeChatUserInfo(string access_token, string openid)
        {
            WeChatUserInfo uinfo      = new WeChatUserInfo();
            string         url        = string.Format("https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN", access_token, openid);
            string         jsonResult = HttpUtils.Ins.GET(url);

            ClassLoger.Info("WeChatAPIHelper.GetWeChatUserInfo", url, jsonResult);
            if (!jsonResult.IsNull())
            {
                if (jsonResult.Contains("errcode"))
                {
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", url);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatUserInfo", jsonResult);
                }
                else
                {
                    Dictionary <string, object> resultDic = JsonHelper.DeserializeObject(jsonResult);
                    uinfo.city       = resultDic["city"].TryToString();
                    uinfo.country    = resultDic["country"].TryToString();
                    uinfo.headimgurl = resultDic["headimgurl"].TryToString();
                    uinfo.nickname   = resultDic["nickname"].TryToString();
                    uinfo.openid     = resultDic["openid"].TryToString();
                    uinfo.privilege  = resultDic["privilege"].TryToString();
                    uinfo.province   = resultDic["province"].TryToString();
                    uinfo.sex        = resultDic["sex"].TryToInt(0);
                    if (resultDic.ContainsKey("unionid"))
                    {
                        uinfo.unionid = resultDic["unionid"].TryToString();
                    }
                }
            }
            return(uinfo);
        }
Пример #12
0
        /// <summary>
        /// 获取微信公共号的Access_token
        /// </summary>
        /// <returns></returns>
        public static string GetWeChatAccess_token()
        {
            string access_token = string.Empty;
            string key          = getaccess_tokenKey();

            if (RedisBase.ContainsKey(key))
            {
                access_token = RedisBase.Item_Get <string>(key);
            }
            else
            {
                string url        = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", SystemSet.Serviceappid, SystemSet.Serviceappsecret);
                string resultJson = HttpUtils.Ins.GET(url);
                if (!resultJson.IsNull())
                {
                    if (resultJson.Contains("errcode"))
                    {
                        //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson);
                        ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token", url);
                        ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token", resultJson);
                    }
                    else
                    {
                        Dictionary <string, object> resDic = JsonHelper.DeserializeObject(resultJson);
                        access_token = resDic["access_token"].TryToString();
                        int expires_in = resDic["expires_in"].TryToInt(100);
                        RedisBase.Item_Set <string>(key, access_token);
                        RedisBase.ExpireEntryAt(key, DateTime.Now.AddSeconds(expires_in));
                    }
                }
            }
            return(access_token);
        }
Пример #13
0
        /// <summary>
        /// 获取网页用户授权
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Access_tokenResult GetWeChatAccess_token(string code)
        {
            string             url        = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", SystemSet.Appid, SystemSet.Appsecret, code);
            Access_tokenResult result     = new Access_tokenResult();
            string             resultJson = HttpUtils.Ins.GET(url);

            if (!resultJson.IsNull())
            {
                if (resultJson.Contains("errcode"))
                {
                    //WeChatErrorResult errorResult = JsonHelper.DeserializeObject<WeChatErrorResult>(resultJson);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", url);
                    ClassLoger.Fail("WeChatAPIHelper.GetWeChatAccess_token(" + code + ")", resultJson);
                }
                else
                {
                    Dictionary <string, object> resDic = JsonHelper.DeserializeObject(resultJson);
                    result.access_token  = resDic["access_token"].TryToString();
                    result.expires_in    = resDic["expires_in"].TryToInt(100);
                    result.openid        = resDic["openid"].TryToString();
                    result.refresh_token = resDic["refresh_token"].TryToString();
                    result.scope         = resDic["scope"].TryToString();
                }
            }
            return(result);
        }
Пример #14
0
        /**
         * 调用统一下单,获得下单结果
         * @return 统一下单结果
         * @失败时抛异常WxPayException
         */
        public WxPayData GetUnifiedOrderResult()
        {
            //统一下单
            WxPayData data = new WxPayData();

            data.SetValue("body", body);
            data.SetValue("attach", attach);
            data.SetValue("out_trade_no", out_trade_no);
            data.SetValue("total_fee", total_fee);
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));
            data.SetValue("goods_tag", "test");
            data.SetValue("trade_type", trade_type);
            data.SetValue("openid", openid);
            data.SetValue("product_id", product_id);
            WxPayData result = WxPayApi.UnifiedOrder(data);

            if (!result.IsSet("appid") || !result.IsSet("prepay_id") || result.GetValue("prepay_id").ToString() == "")
            {
                ClassLoger.Error(this.GetType().ToString(), "UnifiedOrder response error!");
                throw new WxPayException("UnifiedOrder response error!");
            }

            unifiedOrderResult = result;
            return(result);
        }
Пример #15
0
        public async Task <Tuple <List <UserInfo>, long> > GetList(string name, int pageIndex, int pageSize)
        {
            try
            {
                DataContext     db       = new DataContext();
                List <UserInfo> userlist = new List <UserInfo>();
                long            count    = 0;
                await Task.Run(() => {
                    if (!string.IsNullOrEmpty(name))
                    {
                        var query = db.Users.Where(x => x.State == Model.Enume.StateEnum.Invalid && x.Name.Contains(name));
                        userlist  = query.OrderByDescending(x => x.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        count     = query.LongCount();
                    }
                    else
                    {
                        userlist = db.Users.Where(x => x.State == Model.Enume.StateEnum.Invalid).OrderByDescending(x => x.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                        count    = db.Users.Where(x => x.State == Model.Enume.StateEnum.Invalid).LongCount();
                    }
                });

                return(Tuple.Create(userlist, count));
            }
            catch (Exception ex)
            {
                ClassLoger.Error("UserDal.GetList", ex);
            }
            return(Tuple.Create <List <UserInfo>, long>(new List <UserInfo>(), 0));
        }
Пример #16
0
 /// <summary>
 /// 新场景的事件获取单帧图像
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="image"></param>
 private void VideoSourcePlayer1_NewFrame(object sender, ref Bitmap image)
 {
     try
     {
         if (IsStart)
         {
             IsStart = false;
             // 在线程池中另起一个线程进行人脸检测,这样不会造成界面视频卡顿现象
             ThreadPool.QueueUserWorkItem(new WaitCallback(this.Detect), image.Clone());
         }
         if (location != null)
         {
             try
             {
                 // 绘制方框套住人脸
                 Graphics g = Graphics.FromImage(image);
                 g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top), new System.Drawing.Point(location.left + location.width, location.top));
                 g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top), new System.Drawing.Point(location.left, location.top + location.height));
                 g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left, location.top + location.height), new System.Drawing.Point(location.left + location.width, location.top + location.height));
                 g.DrawLine(new Pen(Color.Black), new System.Drawing.Point(location.left + location.width, location.top), new System.Drawing.Point(location.left + location.width, location.top + location.height));
                 g.Dispose();
             }
             catch (Exception ex)
             {
                 ClassLoger.Error("VideoSourcePlayer1_NewFrame", ex);
             }
         }
     } catch (Exception ex)
     {
         ClassLoger.Error("VideoSourcePlayer1_NewFrame1", ex);
     }
 }
Пример #17
0
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
            ClassLoger.StartLogin();
            clearlogs clearlog = new clearlogs();

            clearlog.Start();
        }
Пример #18
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.HttpContext.Session.Keys.Contains("user"))
     {
         ClassLoger.Fail("UserLoginFilter", "session过期");
         context.Result = new RedirectResult("/Account/Index");
         return;
     }
     base.OnActionExecuting(context);
 }
        public async Task <HttpResponseMessage> Getfile(string id, string token)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            if (id.IsNull() || token.IsNull())
            {
                response.StatusCode = HttpStatusCode.NotFound;
                return(response);
            }
            ApiUserManager usermanage = new ApiUserManager();
            UserInfo       user       = usermanage.GetUser(token);

            if (user == null)
            {
                response.StatusCode = HttpStatusCode.NotFound;
                return(response);
            }
            try
            {
                await Task.Run(() => {
                    string filename = string.Format("{0}.docx", id);
                    //string filePath = WordHelper.GetWordFilePath(filename);
                    //if (File.Exists(filePath))
                    //{
                    //    var stream = new FileStream(filePath, FileMode.Open);
                    //    response.Content = new StreamContent(stream);
                    //    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    //    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    //    {
                    //        FileName = filename
                    //    };
                    //    return;
                    //}
                    //StringBuilder sb = new StringBuilder();
                    //string title = "文件名称";
                    //Tuple<string, string> re = WordHelper.CreateWord(title, sb.ToString(), filename);
                    //if (re.Item1.IsNull())
                    //{
                    //    response.StatusCode = HttpStatusCode.NotFound;
                    //    return;
                    //}
                    //var streams = new FileStream(filePath, FileMode.Open);
                    //response.Content = new StreamContent(streams);
                    //response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                    //response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    //{
                    //    FileName = filename
                    //};
                });
            } catch (Exception ex)
            {
                ClassLoger.Error("FileDownAPIController.GetPsychtest", ex);
            }
            return(response);
        }
Пример #20
0
        public void OnException(ExceptionContext filterContext)
        {
            ClassLoger.Error(string.Format("{0}发生异常", filterContext.HttpContext.Request.Url.TryToString()), filterContext.Exception);

            JsonResult <string> result = new JsonResult <string>();

            result.code = -1;
            result.msg  = string.Format("{0}发生异常{1}", filterContext.HttpContext.Request.Url.TryToString(), filterContext.Exception.Message);

            filterContext.HttpContext.Response.Write(JsonHelper.SerializeObject(result));
        }
Пример #21
0
 public async Task UpdateAsync(WorkPlan workPlan)
 {
     try
     {
         DataContext dataContext = new DataContext();
         dataContext.WorkPlans.Update(workPlan);
         await dataContext.SaveChangesAsync();
     } catch (Exception ex)
     {
         ClassLoger.Error("WorkPlanDal.UpdateAsync", ex);
     }
 }
Пример #22
0
 public async Task DelModel(ModuleInfo module)
 {
     try
     {
         DataContext dataContext = new DataContext();
         dataContext.ModuleInfos.Remove(module);
         await dataContext.SaveChangesAsync();
     } catch (Exception ex)
     {
         ClassLoger.Error("ModuleInfoDal.DelModel", ex);
     }
 }
Пример #23
0
 private UserAccount GetUserAccountByUserID(int userid)
 {
     try
     {
         DataContext dataContext = new DataContext();
         return(dataContext.UserAccounts.Where(x => x.UserID == userid).FirstOrDefault());
     } catch (Exception ex)
     {
         ClassLoger.Error("UserDal.GetUserAccountByUserID", ex);
     }
     return(null);
 }
Пример #24
0
 public async Task DelAsync(EnterCustomer enterCustomer)
 {
     try
     {
         DataContext dataContext = new DataContext();
         dataContext.Remove(enterCustomer);
         await dataContext.SaveChangesAsync();
     }
     catch (Exception ex)
     {
         ClassLoger.Error("EnterCustomerDal.DelAsync", ex);
     }
 }
Пример #25
0
        /**
         *
         * 申请退款
         * @param WxPayData inputObj 提交给申请退款API的参数
         * @param int timeOut 超时时间
         * @throws WxPayException
         * @return 成功时返回接口调用结果,其他抛异常
         */
        public static WxPayData Refund(WxPayData inputObj, int timeOut = 6)
        {
            string url = "https://api.mch.weixin.qq.com/secapi/pay/refund";

            //检测必填参数
            if (!inputObj.IsSet("out_trade_no") && !inputObj.IsSet("transaction_id"))
            {
                throw new WxPayException("退款申请接口中,out_trade_no、transaction_id至少填一个!");
            }
            else if (!inputObj.IsSet("out_refund_no"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数out_refund_no!");
            }
            else if (!inputObj.IsSet("total_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数total_fee!");
            }
            else if (!inputObj.IsSet("refund_fee"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数refund_fee!");
            }
            else if (!inputObj.IsSet("op_user_id"))
            {
                throw new WxPayException("退款申请接口中,缺少必填参数op_user_id!");
            }

            inputObj.SetValue("appid", SystemSet.Serviceappid);                         //公众账号ID
            inputObj.SetValue("mch_id", SystemSet.Mch_id);                              //商户号
            inputObj.SetValue("nonce_str", Guid.NewGuid().ToString().Replace("-", "")); //随机字符串
            inputObj.SetValue("sign", inputObj.MakeSign());                             //签名

            string xml   = inputObj.ToXml();
            var    start = DateTime.Now;

            ClassLoger.DEBUG("WxPayApi", "Refund request : " + xml);
            string response = HttpService.Post(xml, url, true, timeOut);//调用HTTP通信接口提交数据到API

            ClassLoger.DEBUG("WxPayApi", "Refund response : " + response);

            var end      = DateTime.Now;
            int timeCost = (int)((end - start).TotalMilliseconds);//获得接口耗时

            //将xml格式的结果转换为对象以返回
            WxPayData result = new WxPayData();

            result.FromXml(response);

            ReportCostTime(url, timeCost, result);//测速上报

            return(result);
        }
Пример #26
0
        public async Task <List <EnterTotalReportForDay> > GetReportAsync(DateTime startTime, DateTime endTime, int?userid = null)
        {
            List <EnterTotalReportForDay> reportList = new List <EnterTotalReportForDay>();

            try
            {
                await Task.Run(() => {
                    DataContext dataContext = new DataContext();
                    if (userid.HasValue)
                    {
                        var report = from u in dataContext.EnterCustPhaseLogs
                                     where u.CreateTime > startTime && u.CreateTime < endTime && u.UserID == userid
                                     group u by new { CreateTime = u.CreateTime.ToString("yyyy-MM-dd"), UserID = u.UserID } into g
                        select new { g.Key.UserID, g.Key.CreateTime, Total = g.Count() };
                        if (report != null)
                        {
                            foreach (var r in report)
                            {
                                EnterTotalReportForDay enterTotal = new EnterTotalReportForDay();
                                enterTotal.Days   = r.CreateTime;
                                enterTotal.Total  = r.Total;
                                enterTotal.UserID = r.UserID;
                                reportList.Add(enterTotal);
                            }
                        }
                    }
                    else
                    {
                        var report = from u in dataContext.EnterCustPhaseLogs
                                     where u.CreateTime > startTime && u.CreateTime < endTime
                                     group u by new { CreateTime = u.CreateTime.ToString("yyyy-MM-dd"), UserID = u.UserID } into g
                        select new { g.Key.UserID, g.Key.CreateTime, Total = g.Count() };
                        if (report != null)
                        {
                            foreach (var r in report)
                            {
                                EnterTotalReportForDay enterTotal = new EnterTotalReportForDay();
                                enterTotal.Days   = r.CreateTime;
                                enterTotal.Total  = r.Total;
                                enterTotal.UserID = r.UserID;
                                reportList.Add(enterTotal);
                            }
                        }
                    }
                });
            } catch (Exception ex)
            {
                ClassLoger.Error("EnterCustPhaseLogDal.EnterCustPhaseLogDal", ex);
            }
            return(reportList);
        }
Пример #27
0
        public async Task <SalesProject> GetAsync(int id)
        {
            try
            {
                DataContext dataContext = new DataContext();
                var         info        = await dataContext.SalesProjects.FindAsync(id);

                return(info);
            } catch (Exception ex)
            {
                ClassLoger.Error("SalesProjectDal.GetAsync", ex);
            }
            return(null);
        }
Пример #28
0
        public override void OnException(HttpActionExecutedContext context)
        {
            ClassLoger.Error(string.Format("{0}发生异常", context.Request.RequestUri.TryToString()), context.Exception);

            JsonResult <string> result = new JsonResult <string>();

            result.code = -1;
            result.msg  = string.Format("{0}发生异常{1}", context.Request.RequestUri.TryToString(), context.Exception.Message);

            //篡改Response
            context.Response = new HttpResponseMessage(HttpStatusCode.OK);

            context.Response.Content = new StringContent(JsonHelper.SerializeObject(result));
        }
Пример #29
0
        public async Task <UserRole> Get(int ID)
        {
            try
            {
                DataContext db       = new DataContext();
                var         userrole = await db.UserRoles.FindAsync(ID);

                return(userrole);
            } catch (Exception ex)
            {
                ClassLoger.Error("UserRoleDal.Get", ex);
            }
            return(null);
        }
Пример #30
0
 public List <ModuleInfo> GetList()
 {
     try
     {
         List <ModuleInfo> list = null;
         DataContext       db   = new DataContext();
         list = db.ModuleInfos.ToList();
         return(list);
     } catch (Exception ex)
     {
         ClassLoger.Error("ModuleInfoDal.GetList", ex);
     }
     return(null);
 }