Exemplo n.º 1
0
        public ActionResult <Response <List <Vote> > > GetVotesToComplete([FromHeader] int playerID)
        {
            try
            {
                Player player = new Player(playerID);
                //Call the Data Access Layer to get the photos require voting to be completed
                Response <List <Vote> > response = new PhotoDAL().GetVotesToComplete(player);

                //If the response was successful compress the response before sending the data over the network
                if (response.IsSuccessful())
                {
                    foreach (var vote in response.Data)
                    {
                        vote.Compress();
                    }
                }

                return(response);
            }
            //Catch any error associated with invalid model data
            catch (InvalidModelException e)
            {
                return(new Response <List <Vote> >(e.Msg, e.Code));
            }
            //Catch any unhandled / unexpected server errrors
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 2
0
        public ActionResult <Response> Upload(PhotoUploadRequest request)
        {
            try
            {
                //Build the photo object
                Photo uploadedPhoto = new Photo(request.latitude, request.longitude, request.imgUrl, request.takenByID, request.photoOfID);

                //Get the player object from the database
                Response <Player> getPlayerResponse = new PlayerDAL().GetPlayerByID(uploadedPhoto.TakenByPlayerID);
                if (!getPlayerResponse.IsSuccessful())
                {
                    return(new Response(getPlayerResponse.ErrorMessage, getPlayerResponse.ErrorCode));
                }

                Response <Photo> response;

                //Call the BR Upload business logic if the player is a BR player
                if (getPlayerResponse.Data.IsBRPlayer())
                {
                    response = new PhotoDAL().SavePhoto(uploadedPhoto, true);
                }

                //Otherwise, call the CORE business logic
                else
                {
                    response = new PhotoDAL().SavePhoto(uploadedPhoto, false);
                }

                //If the response is successful we want to send live updates to clients and
                //email or text message notifications to not connected players
                if (response.IsSuccessful())
                {
                    HubInterface hubInterface = new HubInterface(_hubContext);
                    hubInterface.UpdatePhotoUploaded(response.Data);
                    ScheduledTasks.ScheduleCheckPhotoVotingCompleted(response.Data, hubInterface);
                }
                return(new Response(response.ErrorMessage, response.ErrorCode));
            }
            //Catch any error associated with invalid model data
            catch (InvalidModelException e)
            {
                return(new Response(e.Msg, e.Code));
            }
            //Catch any unhandled / unexpected server errrors
            catch
            {
                return(StatusCode(500));
            }
        }
        /// <summary>
        /// The code which will run in a new thread after the FinishVotingTime has passed.
        /// The method checks to see if all players have voted on the image and if not, will
        /// update the image to be successful and make all votes a success. Then send out notifications
        /// to the affected players.
        /// </summary>
        /// <param name="uploadedPhoto">The photo which was uploaded and being checked if voting has been completed.</param>
        /// <param name="timeToWait">The number of milliseconds to wait for the thread to start.</param>
        /// <param name="hubInterface">The Hub interface which will be used to send notifications / updates</param>
        private static void Run_CheckPhotoVotingCompleted(Photo uploadedPhoto, int timeToWait, HubInterface hubContext)
        {
            //Wait for the specified time
            Thread.Sleep(timeToWait);

            //Get the updated photo record from the database
            Photo photo = new PhotoDAL().GetPhotoByID(uploadedPhoto.PhotoID);

            if (photo == null)
            {
                return;
            }

            //Confirm the game the photo is apart of is not completed, if completed leave the method
            if (photo.Game.IsCompleted())
            {
                return;
            }

            //Check to see if the voting has been completed for the photo.
            //If the voting has been completed exit the method
            if (photo.IsVotingComplete)
            {
                return;
            }

            //Otherwise, the game is not completed and the photo has not been successfully voted on by all players

            //Call the Data Access Layer to update the photo record to now be completed.
            PhotoDAL         photoDAL = new PhotoDAL();
            Response <Photo> response = photoDAL.VotingTimeExpired(photo.PhotoID, photo.TakenByPlayer.IsBRPlayer());

            //If the update was successful then send out the notifications to the affected players
            //Will send out in game notifications and text/email notifications
            if (response.IsSuccessful())
            {
                //If the response's data is NULL that means the game is now completed. Send live updates to complete the game
                if (response.Data == null)
                {
                    hubContext.UpdateGameCompleted(photo.Game, false);
                }

                //Otherwise, update the players that voting has been completed
                else
                {
                    hubContext.UpdatePhotoVotingCompleted(response.Data);
                }
            }
        }
Exemplo n.º 4
0
        private void btnAjouter(object sender, RoutedEventArgs e)
        {
            myDataObject.id = PhotoDAL.getMaxIdPhoto() + 1;

            lp.Add(myDataObject);
            PhotoORM.insertPhoto(myDataObject);
            compteur = lp.Count();

            // Comme on a inséré une Photo, on crée un nouvel objet PhotoViewModel
            // Et on réatache tout ce qu'il faut pour que la vue soit propre
            myDataObject = new PhotoViewModel();

            // Comme le contexte des élément de la vue est encore l'ancien PhotoViewModel,
            // On refait les liens entre age, slider, textbox, bouton et le nouveau PhotoViewModel
            ComboBoxProduit.DataContext = myDataObject;
        }
Exemplo n.º 5
0
        public ActionResult <Response> VoteOnPhoto([FromHeader] int playerID, [FromHeader] int voteID, [FromForm] string decision)
        {
            try
            {
                //Get the player object from the database
                Response <Player> getPlayerResponse = new PlayerDAL().GetPlayerByID(playerID);
                if (!getPlayerResponse.IsSuccessful())
                {
                    return(new Response(getPlayerResponse.ErrorMessage, getPlayerResponse.ErrorCode));
                }

                Vote            vote = new Vote(voteID, decision, playerID);
                Response <Vote> response;

                //Vote on the photo
                response = new PhotoDAL().VoteOnPhoto(vote, getPlayerResponse.Data.IsBRPlayer());
                if (response.IsSuccessful())
                {
                    //If the response's data is NULL that means the game is now completed for a BR game. Send live updates to complete the game
                    if (response.Data == null)
                    {
                        HubInterface hubInterface = new HubInterface(_hubContext);
                        hubInterface.UpdateGameCompleted(getPlayerResponse.Data.Game, false);
                    }

                    //If the Photo's voting has now been completed send the notifications / updates
                    else if (response.Data.Photo.IsVotingComplete)
                    {
                        HubInterface hubInterface = new HubInterface(_hubContext);
                        hubInterface.UpdatePhotoVotingCompleted(response.Data.Photo);
                    }
                }
                return(new Response(response.ErrorMessage, response.ErrorCode));
            }
            //Catch any error associated with invalid model data
            catch (InvalidModelException e)
            {
                return(new Response(e.Msg, e.Code));
            }
            //Catch any unhandled / unexpected server errrors
            catch
            {
                return(StatusCode(500));
            }
        }
Exemplo n.º 6
0
        public void ProcessRequest(HttpContext context)
        {
            StreamReader reader     = new StreamReader(context.Request.InputStream, Encoding.UTF8);
            string       requestStr = reader.ReadToEnd();

            long record_id = long.Parse(requestStr);

            PhotoModel[] photos = PhotoDAL.GetAllByRecordId(record_id);

            JObject jObj = new JObject();

            jObj.Add("count", photos.Length);
            JArray jArr = new JArray();

            foreach (var photo in photos)
            {
                jArr.Add(photo.Path);
            }
            jObj.Add("content", jArr);

            byte[] buf = Encoding.UTF8.GetBytes(jObj.ToString());
            context.Response.OutputStream.Write(buf, 0, buf.Length);
        }
Exemplo n.º 7
0
        //JSON数据格式
        //{
        //    Username: string
        //    Description:string
        //    Time:DateTime
        //    LocationStr string(四川_成都_郫县)
        //    Answers:string("010100")
        //    PicNames:string的JArray
        //}
        public void ProcessRequest(HttpContext context)
        {
            StreamReader reader     = new StreamReader(context.Request.InputStream, Encoding.UTF8);
            string       requestStr = reader.ReadToEnd();

            JObject  jObj        = JObject.Parse(requestStr);
            string   username    = jObj["Username"].ToString();
            string   description = jObj["Description"].ToString();
            DateTime time        = DateTime.Parse(jObj["Time"].ToString());
            string   locationStr = jObj["LocationStr"].ToString();
            string   answers     = jObj["Answers"].ToString();
            JArray   picNames    = JArray.Parse(jObj["PicNames"].ToString());

            //添加到自检记录
            RecordModel record = new RecordModel();

            record.Answers     = answers;
            record.Description = description;

            //如果locationStr为null,则返回"000000"(中国),否则解析并保存
            if (string.IsNullOrEmpty(locationStr))
            {
                record.Citycode = "000000";
            }
            else
            {
                record.Citycode = LocationDAL.GetLocalId(locationStr);
            }

            record.Time    = time;
            record.User_id = UserDAL.GetByUsername(username).User_id;
            long record_id = RecordDAL.Insert(record);

            //添加自检图片
            foreach (string picName in picNames)
            {
                PhotoModel photo = new PhotoModel();
                photo.Path      = picName;
                photo.Record_id = record_id;
                PhotoDAL.Insert(photo);
            }

            //返回Record_id给移动端
            JObject jObjSend = new JObject();

            jObjSend.Add("Record_id", record_id);

            byte[] buf = Encoding.UTF8.GetBytes(jObjSend.ToString());
            context.Response.OutputStream.Write(buf, 0, buf.Length);

            Thread thread = new Thread(() =>
            {
                List <CVResultModel> results = new List <CVResultModel>();

                //检查图片是否分析完成(是否Insert到CVResult中)
                const int WAIT_TIME = 240;   //等待时间(如果240秒某张图片都没有传输成功且分析完成,则放弃)
                foreach (string picName in picNames)
                {
                    //轮询
                    for (int i = 0; i < WAIT_TIME; i++)
                    {
                        if (null != CVResultDAL.GetById(picName))
                        {
                            results.Add(CVResultDAL.GetById(picName));
                            break;
                        }
                        Thread.Sleep(1000);
                    }
                }

                //计算分数并保存
                float score = ScoreUtil.GetScore(results);
                RecordDAL.UpdateScore(score, record_id);
            });

            thread.Start();
        }
Exemplo n.º 8
0
 public static void insertPhoto(PhotoDAO p)
 {
     PhotoDAL.insertPhoto(p);
 }
Exemplo n.º 9
0
 public static void updatePhoto(PhotoDAO p)
 {
     PhotoDAL.updatePhoto(p);
 }
Exemplo n.º 10
0
 public static void supprimerPhoto(int id)
 {
     PhotoDAL.supprimerPhoto(id);
 }
Exemplo n.º 11
0
        public static PhotoDAO getPhoto(int idPhoto)
        {
            PhotoDAO p = PhotoDAL.getPhoto(idPhoto);

            return(p);
        }
Exemplo n.º 12
0
        public static ObservableCollection <PhotoDAO> listePhotos()
        {
            ObservableCollection <PhotoDAO> l = PhotoDAL.selectPhotos();

            return(l);
        }
Exemplo n.º 13
0
        public void ProcessRequest(HttpContext context)
        {
            StreamReader reader     = new StreamReader(context.Request.InputStream, Encoding.UTF8);
            string       requestStr = reader.ReadToEnd();

            //返回所有自检结果,其中本地区的置前
            if ("ListAll".Equals(requestStr))
            {
                ////获取IP地理信息
                //string hostIP = context.Request.UserHostAddress;
                //IPRecord ip = HttpHelper.GetIPRecord(hostIP);

                ////通过IP地理信息获取所在区域的编号
                //RecordModel[] recordModels = null;
                //if (string.IsNullOrEmpty(ip.Province))
                //{
                //    //返回所有的自检
                //    recordModels = RecordDAL.GetAll();
                //}
                //else if (string.IsNullOrEmpty(ip.City))
                //{
                //    //返回指定省份的自检
                //    recordModels = RecordDAL.GetAllProvinceFirst(ip.Province);
                //}
                //else if (string.IsNullOrEmpty(ip.District))
                //{
                //    //返回指定城市的自检
                //    recordModels = RecordDAL.GetAllCityFirst(ip.City);
                //}
                //else
                //{
                //    //返回指定区域的自检
                //    recordModels = RecordDAL.GetAllAreaFirst(ip.District);
                //}

                RecordModel[] recordModels = RecordDAL.GetAll();
                JObject       jObj         = new JObject();
                jObj.Add("count", recordModels.Length);
                JArray jArr = new JArray();
                foreach (RecordModel recordModel in recordModels)
                {
                    jArr.Add(JsonConvert.SerializeObject(new ExRecordModel(recordModel)));
                }
                jObj.Add("content", jArr);

                byte[] bytes = Encoding.UTF8.GetBytes(jObj.ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            }
            else if (requestStr.StartsWith("Patient: "))
            {
                //返回指定用户的自检信息
                string        username     = requestStr.Substring("Patient: ".Length);
                RecordModel[] recordModels = RecordDAL.GetByUsername(username);

                JObject jObj = new JObject();
                jObj.Add("count", recordModels.Length);
                JArray jArr = new JArray();
                foreach (RecordModel recordModel in recordModels)
                {
                    jArr.Add(JsonConvert.SerializeObject(recordModel));
                }
                jObj.Add("content", jArr);

                byte[] bytes = Encoding.UTF8.GetBytes(jObj.ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            }
            else if (requestStr.StartsWith("Record_id: "))
            {
                //返回指定编号的自检信息
                long record_id;
                if (long.TryParse(requestStr.Substring("Record_id: ".Length), out record_id))
                {
                    var record = RecordDAL.GetById(record_id);

                    string json = JsonConvert.SerializeObject(record);

                    byte[] bytes = Encoding.UTF8.GetBytes(json);
                    context.Response.OutputStream.Write(bytes, 0, bytes.Length);
                }
            }
            else
            {
                //返回指定id对应的自检图片
                long         id     = long.Parse(requestStr);
                PhotoModel[] photos = PhotoDAL.GetAllByRecordId(id);
                JObject      jObj   = new JObject();
                jObj.Add("count", photos.Length);
                JArray jArr = new JArray();
                foreach (PhotoModel photo in photos)
                {
                    jArr.Add(JsonConvert.SerializeObject(photo));
                }
                jObj.Add("content", jArr);

                byte[] bytes = Encoding.UTF8.GetBytes(jObj.ToString());
                context.Response.OutputStream.Write(bytes, 0, bytes.Length);
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// 图片消息处理
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public string ImageMsgReceive(ImageRequestMsgModel msg)
        {
            string         res  = string.Empty;
            MsgAutoRuleDAL dal  = new MsgAutoRuleDAL();
            MsgAutoRule    rule = dal.GetImageRule(wxConfig.ID);

            if (rule != null)
            {
                switch (rule.MsgType.ToLower())
                {
                case "hp_photo":
                    try
                    {
                        string fileDir = HttpContext.Current.Server.MapPath("/HP_PHOTO/");
                        if (!Directory.Exists(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        ExceptionLog log = new ExceptionLog();
                        log.Message = weixin.WeiXinConfig.AppId + "}{" + weixin.WeiXinConfig.AppSecret + "}{" + msg.MediaId;
                        ExceptionLogDAL.InsertExceptionLog(log);

                        //string fileName = weixin.SaveAsMedia(msg.MediaId, fileDir);
                        string fileName = weixin.SaveAsFile(msg.PicUrl, fileDir);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            Photo p = new Photo()
                            {
                                SiteCode = siteCode,
                                OpenId   = msg.FromUserName,
                                Img      = fileName
                            };
                            PhotoDAL photoDal = new PhotoDAL();
                            photoDal.SaveInfo(p);

                            //回复文本消息
                            string url     = string.Format("{0}/WebService/ImageEdit.aspx?id={1}", GetSiteUrl(), p.ID);
                            string content = string.Format("<a href='{0}'>点击编辑</a>", url);
                            TextResponseMsgModel textMsg = new TextResponseMsgModel()
                            {
                                ToUserName   = msg.FromUserName,
                                FromUserName = msg.ToUserName,
                                CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                                Content      = content
                            };
                            res = textMsg.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogDAL.InsertExceptionLog(ex);
                    }
                    break;

                case "user_photo":
                    try
                    {
                        string fileDir = HttpContext.Current.Server.MapPath("/USER_PHOTO/");
                        if (!Directory.Exists(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }

                        //string fileName = weixin.SaveAsMedia(msg.MediaId, fileDir);
                        string fileName = weixin.SaveAsFile(msg.PicUrl, fileDir);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            UserPhoto photo = new UserPhoto()
                            {
                                Name     = fileName,
                                SiteCode = siteCode,
                                OpenId   = msg.FromUserName,
                                FilePath = fileName
                            };
                            UserPhotoDAL uPhotoDal = new UserPhotoDAL();
                            uPhotoDal.Insert(photo);

                            //回复文本消息
                            TextResponseMsgModel textMsg = new TextResponseMsgModel()
                            {
                                ToUserName   = msg.FromUserName,
                                FromUserName = msg.ToUserName,
                                CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                                Content      = rule.MsgValue == null ? string.Empty : TransformText(rule.MsgValue, msg)
                            };
                            res = textMsg.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogDAL.InsertExceptionLog(ex);
                    }
                    break;

                case "user_photo_url":
                    try
                    {
                        string fileDir = HttpContext.Current.Server.MapPath("/USER_PHOTO/");
                        if (!Directory.Exists(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        string fileName = weixin.SaveAsFile(msg.PicUrl, fileDir);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            UserPhoto photox = new UserPhoto()
                            {
                                Name     = fileName,
                                SiteCode = siteCode,
                                OpenId   = msg.FromUserName,
                                FilePath = fileName
                            };
                            UserPhotoDAL uPhotoDal = new UserPhotoDAL();
                            uPhotoDal.Insert(photox);

                            //回复文本消息
                            string url     = string.Format("{0}/MicroSite/PhotoPrint.aspx?id={1}", GetSiteUrl(), photox.ID);
                            string content = string.Format("<a href='{0}'>开始打印</a>", url);
                            TextResponseMsgModel textUrlMsg = new TextResponseMsgModel()
                            {
                                ToUserName   = msg.FromUserName,
                                FromUserName = msg.ToUserName,
                                CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                                Content      = content
                            };
                            res = textUrlMsg.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogDAL.InsertExceptionLog(ex);
                    }
                    break;

                case "user_printphoto_stepone":
                    try
                    {
                        string fileDir = HttpContext.Current.Server.MapPath("/USER_PHOTO/");
                        if (!Directory.Exists(fileDir))
                        {
                            Directory.CreateDirectory(fileDir);
                        }
                        string fileName = weixin.SaveAsFile(msg.PicUrl, fileDir);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            UserPhoto photox = new UserPhoto()
                            {
                                Name     = fileName,
                                SiteCode = siteCode,
                                OpenId   = msg.FromUserName,
                                FilePath = fileName
                            };
                            UserPhotoDAL uPhotoDal = new UserPhotoDAL();
                            uPhotoDal.Insert(photox);

                            //回复文本消息
                            string url     = string.Format("{0}/MicroSite/PhotoPrintStepOne.aspx?id={1}", GetSiteUrl(), photox.ID);
                            string content = string.Format("<a href='{0}'>开始打印</a>", url);
                            TextResponseMsgModel textUrlMsg = new TextResponseMsgModel()
                            {
                                ToUserName   = msg.FromUserName,
                                FromUserName = msg.ToUserName,
                                CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                                Content      = content
                            };
                            res = textUrlMsg.ToString();
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionLogDAL.InsertExceptionLog(ex);
                    }
                    break;

                default:
                    rule = dal.GetDefaultRule(wxConfig.ID);
                    if (rule != null)
                    {
                        res = ProcessReply(msg, rule.MsgType, rule.MsgValue);
                    }
                    break;
                }
            }
            return(res);
        }
Exemplo n.º 15
0
        /// <summary>
        /// 窗口加载时:通过GET请求的"record_id"参数到数据库取得相应的自检信息并显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            long record_id;

            if (long.TryParse(Request.Params["record_id"], out record_id))
            {
                //调用数据库访问类查询该主键对应的自检记录
                RecordModel  record = RecordDAL.GetById(record_id);
                PhotoModel[] photos = PhotoDAL.GetAllByRecordId(record_id);

                //原图片
                List <string> srcUrls = new List <string>();
                List <string> dstUrls = new List <string>();
                foreach (var photo in photos)
                {
                    srcUrls.Add("~/ImageWebForm.aspx?fileType=src&picName=" + photo.Path);
                    dstUrls.Add("~/ImageWebForm.aspx?fileType=dst&picName=" + photo.Path);
                }

                //将图片绑定到控件上
                dl_srcImgs.DataSource = srcUrls;
                dl_srcImgs.DataBind();

                dl_dstImgs.DataSource = dstUrls;
                dl_dstImgs.DataBind();

                //取得该自检对应图片的所有处理结果
                List <CVResultModel> results = new List <CVResultModel>();
                foreach (var photo in photos)
                {
                    var result = CVResultDAL.GetById(photo.Path);
                    if (result != null)
                    {
                        results.Add(result);
                    }
                }

                //分析处理结果
                float score = ScoreUtil.GetScore(results);

                //结论
                StringBuilder builder = new StringBuilder();
                //builder.AppendFormat("系统分析得分:{0:f2}", score).AppendLine();
                var group = Severity.Group(score);
                switch (group)
                {
                case Severity.SeverityEnum.Normal:
                    builder.AppendLine("牙齿正常,请注意保持");
                    break;

                case Severity.SeverityEnum.Light:
                    builder.AppendLine("有少量龋齿或程度较轻");
                    break;

                case Severity.SeverityEnum.Medium:
                    builder.AppendLine("有一定龋齿或程度中等");
                    break;

                case Severity.SeverityEnum.Severe:
                    builder.AppendLine("有大量龋齿或龋坏严重");
                    break;

                default:
                    break;
                }

                if (group != Severity.SeverityEnum.Normal)
                {
                    builder.AppendLine("可能为色素沉着,牙石或牙垢,保持口腔清洁或前往正规医院洗牙可以让结果更准确");
                }
                lbl_conclusion.Text = builder.ToString().Replace(Environment.NewLine, "<br>");

                //医生意见
                DiagnosisModel[] diagnoses = DiagnosisDAL.GetAllByRecordId(record_id);
                List <string>    comments  = new List <string>();
                foreach (var diagnosis in diagnoses)
                {
                    string item = string.Format("{0} {1}", diagnosis.Time.ToString(), DoctorDAL.GetById(diagnosis.Doc_id).RealName)
                                  + Environment.NewLine + diagnosis.Result;
                    comments.Add(item);
                }
                dl_comments.DataSource = comments;
                dl_comments.DataBind();
            }
            else
            {
                //record_id出错
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// 处理回复消息
        /// "text":回复文本消息处理,MsgValue对应回复的文本
        /// "sub_auto_coupon":回复订阅自动优惠券处理,MsgValue对应回复的图文消息ID
        /// "auto_news_article":根据文章自动生成图文消息进行回复,MsgValue为类别ID
        /// "news":回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
        /// </summary>
        /// <param name="replyMsgType"></param>
        /// <param name="replyMsgValue"></param>
        /// <param name="customParams"></param>
        /// <returns></returns>
        private string ProcessReply(RequestMsgModel msgModel, string replyMsgType, string replyMsgValue)
        {
            string res = string.Empty;

            try
            {
                switch (replyMsgType.ToLower())
                {
                case "text":
                    //回复文本消息处理,MsgValue对应回复的文本
                    TextResponseMsgModel textMsg = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                    };
                    res = textMsg.ToString();
                    break;

                case "voice":
                    //回复语音消息处理,MsgValue对应回复的文本
                    VoiceResponseMsgModel voiceMsg = new VoiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    Media media = MediaDAL.CreateInstance().GetMediaByID(replyMsgValue);
                    if (media != null && !string.IsNullOrEmpty(media.MediaID))
                    {
                        voiceMsg.MediaId = media.MediaID;
                    }
                    res = voiceMsg.ToString();
                    break;

                case "wxpay_test":
                    //用于微信支付测试
                    TextResponseMsgModel textMsgx = new TextResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        Content      = string.Format("<a href='{0}/Payment/wxpay/wxpayDemo.aspx?openid={1}'>微信支付测试</a>", GetSiteUrl(), msgModel.FromUserName)
                    };
                    res = textMsgx.ToString();
                    break;

                case "transfer_customer_service":
                    //将消息转发到多客服
                    TransferCustomerServiceResponseMsgModel transferMsg = new TransferCustomerServiceResponseMsgModel()
                    {
                        ToUserName   = msgModel.FromUserName,
                        FromUserName = msgModel.ToUserName,
                        CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                    };
                    res = transferMsg.ToString();
                    break;

                case "sub_auto_coupon":
                    //回复订阅自动优惠券处理,MsgValue对应回复的优惠券图文消息ID
                    //SubscribeCouponActHandle sch = new SubscribeCouponActHandle();
                    SiteActivityDAL dal      = new SiteActivityDAL();
                    SiteActivity    activity = dal.GetSiteAct(siteCode, "Coupon");
                    if (activity != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activity.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activity.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    CouponNewsDAL nmDAL = new CouponNewsDAL();
                    CouponNews    nm    = nmDAL.GetCouponNews(replyMsgValue);
                    if (nm != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nm.Title,
                            Description = nm.Description,
                            PicUrl      = GetPicUrl(nm.PicUrl),
                            Url         = TransformUrl(nm.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_coupon_category":
                    SiteActivityDAL dalCatList  = new SiteActivityDAL();
                    SiteActivity    activityCat = dalCatList.GetSiteAct(siteCode, "Coupon");
                    if (activityCat != null)
                    {
                        CouponDAL cdal = new CouponDAL();
                        if (!cdal.ExistCoupon(siteCode, activityCat.ID, msgModel.FromUserName))
                        {
                            Coupon coupon = new Coupon()
                            {
                                SiteCode       = siteCode,
                                SiteActivityID = activityCat.ID,
                                OpenID         = msgModel.FromUserName,
                                //CouponCode = msgModel.FromUserName,
                                CouponStatus = 0
                            };
                            cdal.InsertInfo(coupon);
                        }
                    }
                    ArticleDAL catDal = new ArticleDAL();
                    DataSet    cdsCat = catDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cdsCat != null && cdsCat.Tables.Count > 0 && cdsCat.Tables[0] != null && cdsCat.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cdsCat.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_article":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    ArticleDAL aDal = new ArticleDAL();
                    DataSet    ds   = aDal.GetArticleDetail(replyMsgValue);
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 100),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "auto_news_category":
                    //根据类别自动生成图文消息进行回复,MsgValue为类别ID
                    ArticleDAL cDal = new ArticleDAL();
                    DataSet    cds  = cDal.GetCategoryList(siteCode, replyMsgValue);
                    if (cds != null && cds.Tables.Count > 0 && cds.Tables[0] != null && cds.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in cds.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Title"].ToString(),
                                Description = dr["Summary"].ToString(),
                                //Description = RemoveHtmlTag(dr["Content"].ToString(), 30),
                                PicUrl = GetPicUrl(dr["Pic"].ToString()),
                                Url    = GetArticleUrl(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "coupon":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL nmDAL1 = new NewsMsgDAL();
                    NewsMsg    nms    = nmDAL1.GetNewsMsg(replyMsgValue);
                    if (nms != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        articles.Add(new Article()
                        {
                            Title       = nms.Title,
                            Description = nms.Description,
                            PicUrl      = GetPicUrl(nms.PicUrl),
                            Url         = TransformUrl(nms.Url, msgModel)
                        });
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "news":
                    //回复图文表中的消息,MsgValue为图文消息表ID集,用逗号分隔
                    NewsMsgDAL      nmDALs   = new NewsMsgDAL();
                    IList <NewsMsg> newsMsgs = nmDALs.GetNewsMsgs(replyMsgValue);
                    if (newsMsgs != null)
                    {
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (NewsMsg msg in newsMsgs)
                        {
                            articles.Add(new Article()
                            {
                                Title       = msg.Title,
                                Description = msg.Description,
                                PicUrl      = GetPicUrl(msg.PicUrl),
                                Url         = TransformUrl(msg.Url, msgModel)
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "url":
                    //根据文章自动生成图文消息进行回复,MsgValue为文章ID
                    DAL.SYS.AccountDAL dalUrl = new DAL.SYS.AccountDAL();
                    DataSet            dsUrl  = dalUrl.GetAccountExtData(replyMsgValue);
                    if (dsUrl != null && dsUrl.Tables.Count > 0 && dsUrl.Tables[0] != null && dsUrl.Tables[0].Rows.Count > 0)
                    {
                        int i = 0;
                        NewsResponseMsgModel newsModel = new NewsResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString()
                        };
                        List <Article> articles = new List <Article>();
                        foreach (DataRow dr in dsUrl.Tables[0].Rows)
                        {
                            if (++i > 4)
                            {
                                break;
                            }
                            articles.Add(new Article()
                            {
                                Title       = dr["Name"].ToString(),
                                Description = dr["Summary"].ToString(),
                                PicUrl      = GetPicUrl(dr["Photo"].ToString()),
                                Url         = GetSiteInfo(dr["ID"].ToString())
                            });
                        }
                        newsModel.Articles = articles;
                        res = newsModel.ToString();
                    }
                    break;

                case "hp_photo_text":
                    //为当前hp_photo对应的照片附加文字信息
                    PhotoDAL photoDal = new PhotoDAL();
                    if (photoDal.ExistPhoto(siteCode, msgModel.FromUserName, 0))
                    {
                        TextRequestMsgModel temp = msgModel as TextRequestMsgModel;
                        string text = temp.Content.Replace("#ms", "");
                        //附加图片文字
                        photoDal.UpdateAttachText(siteCode, msgModel.FromUserName, text);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                    }
                    else
                    {
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = "对不起,您暂未参加图片打印活动!"
                        };
                        res = textMsg2.ToString();
                    }
                    break;

                case "hp_photo_ticket":
                    //对当前hp_photo对应的照片进行打印认证
                    PrintCodeDAL        printCodeDAL = new PrintCodeDAL();
                    TextRequestMsgModel temp1        = msgModel as TextRequestMsgModel;
                    string printCode = temp1.Content.Replace("#dy", "");
                    string clientID  = printCodeDAL.GetClientIDByPrintCode(printCode, siteCode);
                    ExceptionLogDAL.InsertExceptionLog(new ExceptionLog()
                    {
                        Message = clientID
                    });
                    if (!string.IsNullOrEmpty(clientID))
                    {
                        PhotoDAL photoDal1 = new PhotoDAL();
                        photoDal1.UpdatePrintInfo(printCode, clientID, siteCode, msgModel.FromUserName);
                        TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        {
                            ToUserName   = msgModel.FromUserName,
                            FromUserName = msgModel.ToUserName,
                            CreateTime   = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                            Content      = replyMsgValue == null ? string.Empty : TransformText(replyMsgValue, msgModel)
                        };
                        res = textMsg2.ToString();
                        //TextResponseMsgModel textMsg2 = new TextResponseMsgModel()
                        //{
                        //    ToUserName = msgModel.FromUserName,
                        //    FromUserName = msgModel.ToUserName,
                        //    CreateTime = WeiXinHelper.ConvertDateTimeInt(DateTime.Now).ToString(),
                        //    Content = "照片打印中,请稍侯..."
                        //};
                        //res = textMsg2.ToString();
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                ExceptionLogDAL.InsertExceptionLog(ex);
            }
            return(res);
        }
Exemplo n.º 17
0
        public ActionResult <Response <MapResponse> > GetMap([FromHeader] int playerID)
        {
            try
            {
                Player player = new Player(playerID);

                //Get the player from the database
                Response <Player> playerResponse = new PlayerDAL().GetPlayerByID(playerID);
                if (!playerResponse.IsSuccessful())
                {
                    return(new Response <MapResponse>(playerResponse.ErrorMessage, playerResponse.ErrorCode));
                }

                //Call the data access layer to get the last known locations
                Response <List <Photo> > getLastPhotoLocationsResponse = new PhotoDAL().GetLastKnownLocations(player);
                if (!getLastPhotoLocationsResponse.IsSuccessful())
                {
                    return(new Response <MapResponse>(getLastPhotoLocationsResponse.ErrorMessage, getLastPhotoLocationsResponse.ErrorCode));
                }

                //If the response was successful compress the photo to remove any unneccessary data needed for the map
                foreach (var photo in getLastPhotoLocationsResponse.Data)
                {
                    photo.CompressForMapRequest();
                }

                MapResponse map;

                //if the player is not a BR player return the list of photos
                if (!playerResponse.Data.IsBRPlayer())
                {
                    map = new MapResponse()
                    {
                        Photos    = getLastPhotoLocationsResponse.Data,
                        IsBR      = false,
                        Latitude  = 0,
                        Longitude = 0,
                        Radius    = 0
                    };
                }

                //otherwise, calculate the currenct radius
                else
                {
                    map = new MapResponse()
                    {
                        Photos    = getLastPhotoLocationsResponse.Data,
                        IsBR      = true,
                        Latitude  = playerResponse.Data.Game.Latitude,
                        Longitude = playerResponse.Data.Game.Longitude,
                        Radius    = playerResponse.Data.Game.CalculateRadius()
                    };
                }

                return(new Response <MapResponse>(map));
            }
            //Catch any error associated with invalid model data
            catch (InvalidModelException e)
            {
                return(new Response <MapResponse>(e.Msg, e.Code));
            }
            //Catch any unhandled / unexpected server errrors
            catch
            {
                return(StatusCode(500));
            }
        }