public static BindingStatue unBindingStudent(string openid)
 {
     using (WeixinDBContext db = new WeixinDBContext())
     {
         var account = db.weixinAccount.Find(openid);
         if (account.studentId == 0)
         {
             return(BindingStatue.UnBinding);
         }
         account.studentId = 0;
         db.SaveChanges();
         return(BindingStatue.Success);
     }
 }
        public static BoolAny <String> SetTrail(string openid)
        {
            WeixinDBContext db = new WeixinDBContext();
            weixinAccount   wa = db.weixinAccount.FirstOrDefault(d => d.openid == openid);

            if (!wa.isTrail)
            {
                wa.trailDate = DateTime.Now;
                wa.isTrail   = false;
                db.SaveChanges();
                return(BoolAny <String> .succeed());
            }
            else
            {
                return(BoolAny <string> .fail("已经绑定过"));
            }
        }
        public static BindingStatue BindingStudent(int loginname, string password)
        {
            string openid = accountIdentity.openid;

            using (BaseContext db = new BaseContext())
            {
                password = password.MD5();
                var member = db.Student.FirstOrDefault(d => d.Id == loginname && d.Password == password && d.IsDisabled != true && d.StudentGroup.IsDisabled != true);
                if (member == null || member.Id == 0)
                {
                    return(BindingStatue.Error);
                }
                else
                {
                    double day = member.getExpireDay(db);
                    if (day > 0)
                    {
                        using (WeixinDBContext weixinDB = new WeixinDBContext())
                        {
                            if (weixinDB.weixinAccount.Count(d => d.studentId == member.Id && d.openid != openid) > 0)
                            {//已经被绑定
                                return(BindingStatue.otherBinded);
                            }

                            var wa = weixinDB.weixinAccount.Find(accountIdentity.openid);

                            if (wa.studentId == 0)
                            {
                                wa.studentId = member.Id;
                                weixinDB.SaveChanges();
                                return(BindingStatue.Success);
                            }
                            else
                            {
                                return(BindingStatue.Binded);
                            }
                        }
                    }
                    else
                    {
                        return(BindingStatue.Expired);
                    }
                }
            }
        }
        private bool ProcessTxtMsg(string xml)
        {
            MsgObject msg = new MsgObject(xml);

            if (msg.MsgType != "text")
            {
                return(false);
            }

            string content = msg.Content;

            if (content.Length > 0)
            {
                using (var dbContext = new WeixinDBContext())
                {
                    bool filter    = false;
                    var  blackList = dbContext.BlackList.Select(p => p.Value).ToList();
                    foreach (var value in blackList)
                    {
                        if (content.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            filter = true;
                            break;
                        }
                    }
                    if (filter == false)
                    {
                        Danmu danmu = new Danmu();
                        danmu.UserName   = string.Empty;
                        danmu.OpenId     = msg.FromUserName;
                        danmu.CreateTime = msg.CreateTime;
                        danmu.Content    = content;
                        dbContext.Danmus.Add(danmu);
                        dbContext.SaveChanges();
                    }
                }
            }

            return(true);
        }
        /// <summary>
        /// 根据不用类型的用户 更新DB weixinAccount的Session,如果存在openid但没有在数据库用则加入
        /// </summary>
        /// <param name="wai"></param>
        /// <returns></returns>
        public static AccountTypeEnum UpdateSessionAccount(string openid)
        {
            if (string.IsNullOrWhiteSpace(openid))
            {
                return(AccountTypeEnum.Null);
            }
            else
            {
                WeixinAccountIdentity wai = new WeixinAccountIdentity()
                {
                    openid = openid
                };

                WeixinDBContext db = new WeixinDBContext();

                weixinAccount wa = db.weixinAccount.Find(openid);
                if (wa == null)//如果存在openid但没有在数据库用则加入
                {
                    JULONG.CAFTS.Model.Weixin.WeixinDBHelper.AddAccount(openid);
                    wa = db.weixinAccount.Find(openid);
                }

                if (wa.isTrail) //试用
                {
                    if ((wa.trailDate.Value - DateTime.Now).TotalMinutes > WeixinConfig.TrailAccountTimeSpan)
                    {
                        SetSessionAccountType(AccountTypeEnum.ExpireTrial);
                        wai.type = AccountTypeEnum.ExpireTrial;
                    }
                    else
                    {
                        wai.type = AccountTypeEnum.Trial;
                    }
                }
                else if (wa.studentId != 0)
                { //学员
                    using (BaseContext webDB = new BaseContext())
                    {
                        Student student = webDB.Student.Find(wa.studentId);

                        double day = student.getExpireDay(webDB);

                        if (day > 0)
                        {
                            wai.type = AccountTypeEnum.Student;
                        }
                        else
                        {
                            wai.type = AccountTypeEnum.ExpireStudent;
                        }
                        wai.studentId    = student.Id;
                        wai.studentName  = student.Name;
                        wai.studentPhone = student.Phone;
                    }
                }
                else
                {//attend,
                    if (wa.attend)
                    {
                        wai.type = AccountTypeEnum.Attend;
                    }
                    else
                    {
                        wai.type = AccountTypeEnum.NoAttend;
                    }
                }

                wa.lastDate = DateTime.Now;
                db.SaveChanges();
                wai.lasVerDate = wa.lastDate;
                WeixinAccountHelper.accountIdentity = wai;
                return(wai.type);
            }
        }
        private async Task <bool> ProcessMsg(string xml, bool returnImage)
        {
            MsgObject msg = new MsgObject(xml);

            if (msg.MsgType != "image")
            {
                string resString = "请点+号输入一张人物风景照片试试";
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                                             msg.FromUserName, msg.ToUserName, resString));
                Response.End();
                return(false);
            }

            bool isDebug = false;

            if (isDebug)
            {
                string debugString = msg.PicUrl;
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                                             msg.FromUserName, msg.ToUserName, msg.PicUrl));
                Response.End();
                return(false);
            }



            //string imagePathorUrl = msg.PicUrl;
            //string imagePathorUrl = msg.PicUrl.Replace("https://", "").Replace("http://", "");
            //var ret = vision.AnalyzeImage(msg.PicUrl);
            RichResult ret = null;
            //ret = vision.AnalyzeImage(msg.PicUrl);

            VisionHelper vision = new VisionHelper(GetVisionAPIkey(), fontPath, DateTime.Now, fontPath);


            var task = QuickReturn(vision, msg);

            //md5 = GetMd5(msg.PicUrl);
            md5 = GetMd5(msg.PicUrl + msg.CreateTime.ToString());
            //check data from db
            using (var dbContext = new WeixinDBContext())
            {
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.OpenId == msg.FromUserName && p.PicUrl == msg.PicUrl && p.CreateTime == msg.CreateTime);
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.PicUrl == msg.PicUrl);
                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.PicUrl == msg.PicUrl && p.CreateTime == msg.CreateTime);

                //ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Md5 == md5 && p.CreateTime == msg.CreateTime);
                ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Md5 == md5);
                if (image != null)
                {
                    Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
                                                 msg.FromUserName, msg.ToUserName, image.ParsedDescription, image.TimeLog, md5));
                    Response.End();
                    return(true);
                }
                dbContext.Dispose();
            }



            ret = await task;

            //when not results in DB and got error
            if (!ret.errorLogs.Equals(""))
            {
                //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>",
                //        msg.FromUserName, msg.ToUserName, "机器人很忙,请稍后再试"));
                Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
                                             msg.FromUserName, msg.ToUserName, ret.analyzeImageResult, ret.timeLogs, ret.errorLogs));
                Response.End();
            }
            //// Debug mode
            //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content><DebugInfo><![CDATA[{3}]]></DebugInfo><ErrorInfo><![CDATA[{4}]]></ErrorInfo></xml>",
            //    msg.FromUserName, msg.ToUserName, ret.analyzeImageResult, ret.timeLogs, ret.errorLogs));

            // Production mode
            //Response.Write(string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>12345678</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{2}]]></Content></xml>", msg.FromUserName, msg.ToUserName, ret.analyzeImageResult));

            //Response.End();


            //save db first without parsedContent
            int id = -1;

            using (var dbContext = new WeixinDBContext())
            {
                ImageStorage image = new ImageStorage();
                image.OpenId     = msg.FromUserName;
                image.CreateTime = msg.CreateTime;
                image.PicUrl     = msg.PicUrl;
                image.Md5        = GetMd5(msg.PicUrl + msg.CreateTime.ToString() + ret.errorLogs);
                //image.PicContent = ret.rawImage;
                image.ParsedUrl         = ret.uploadedUrl;
                image.ParsedDescription = ret.analyzeImageResult + ret.errorLogs;
                image.TimeLog           = ret.timeLogs;
                dbContext.ImageStorages.Add(image);
                dbContext.SaveChanges();
                id = image.Id;
                dbContext.Dispose();
            }

            //write to DB
            //var webClient = new WebClient();
            //var processedImageBytes = webClient.DownloadData(ret.uploadedUrl);

            //using (var dbContext = new WeixinDBContext())
            //{
            //    ImageStorage image = dbContext.ImageStorages.FirstOrDefault(p => p.Id == id);
            //    if (image != null)
            //    {
            //        image.ParsedContent = processedImageBytes;
            //        dbContext.SaveChanges();
            //    }
            //}

            return(true);
        }