Beispiel #1
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public void Add(VoteLog model)
 {
     using (DBHelper db = DBHelper.Create())
     {
         db.Insert <VoteLog>(model);
     }
 }
Beispiel #2
0
        public async Task <IActionResult> Post([FromForm] VoteLog voteLog)
        {
            await dbContext.AddRangeAsync(voteLog);

            await dbContext.SaveChangesAsync();

            return(Json(new { result = "success", msg = "ok" }));
            //try
            //{
            //    if (voteLog == null)
            //    {
            //        return NoContent();
            //    }
            //    var result = await PorcessResult(voteLog);
            //    //var ws = wsPool.WebSocketList.Find(x => x.QueryString.Any(c => c.Value == "voteResult"));
            //    if (ws != null)
            //        await ws.OryxWebSocket.SendAsync(result);
            //    dbOptMng22.InsertOptAutoRun(voteLog, async _localModel =>
            //    {
            //        await dbContext.AddRangeAsync(_localModel);
            //        await dbContext.SaveChangesAsync();
            //    });
            //    return Json(new { result = "success", msg = "ok" });
            //}
            //catch (Exception exc)
            //{
            //    await Log.WriteLog(exc.Message);
            //    return new BadRequestResult();
            //}
        }
        public async Task <IActionResult> OnGet(int?voteId)
        {
            if (voteId == null)
            {
                return(NotFound());
            }

            VoteInfo = dbContext.VoteInfo.Include("VoteOptions").FirstOrDefault(x => x.Id == voteId.Value);
            VoteLog  = dbContext.VoteLog.Where(x => x.VoteId == voteId.Value && x.VoteOption != "null").GroupBy(x => x.VoteOption).Select(x => new
            {
                _key   = x.Select(c => c.VoteOption).First() ?? "",
                _count = x.Count()
            })?.ToDictionary(x => x._key, y => y._count);
            VoteLogJson = JsonConvert.SerializeObject(VoteLog.Select(x => new { voteOption = x.Key, voteSum = x.Value }).ToList());
            var currentBuffer = await dbContext.VoteBuff.FirstOrDefaultAsync(x => x.VoteId == voteId);

            //var buffResultDic = new Dictionary<string, double>();
            //foreach (var item in buffResultList)
            //{
            //    if (buffResultDic.ContainsKey(item.VoteOption))
            //    {
            //        buffResultDic[item.VoteOption] += 16.666666666;
            //    }
            //    else
            //    {
            //        buffResultDic[item.VoteOption] = 16.666666666;
            //    }
            //}
            //BuffResult = JsonConvert.SerializeObject(buffResultDic);
            BuffResult = currentBuffer?.VoteOption;
            PeopleNum  = dbContext.ExcelUserInfo.Count();
            return(Page());
        }
Beispiel #4
0
 /// <summary>
 /// 更新一条数据
 /// </summary>
 public bool Update(VoteLog model)
 {
     using (DBHelper db = DBHelper.Create())
     {
         db.Update <VoteLog>(model);
         return(true);
     }
 }
Beispiel #5
0
        public async Task <IActionResult> PostTest2([FromForm] VoteLog voteLog)
        {
            await dbContext.AddAsync(voteLog);

            await dbContext.SaveChangesAsync();

            return(Ok());
        }
Beispiel #6
0
 public async Task <IActionResult> PostTest4([FromForm] VoteLog voteLog)
 {
     dbOptMng.InsertOptAutoRun(voteLog, async _localModel =>
     {
         await dbContext.VoteLog.AddRangeAsync(_localModel);
         await dbContext.SaveChangesAsync();
     }, 1500);
     return(Ok());
 }
        // GET: Vote
        public ActionResult Index(int index = 0, int pageSize = 6)
        {
            var data = db.Votes.Where(d => !d.IsDisabled).OrderByDescending(d => d.Index).Skip(index).Take(pageSize).ToList()
                       .GroupJoin(db.VoteLog, Vote => Vote.Id, VoteLog => VoteLog.VoteId, (Vote, VoteLog) => new StudentVote()
            {
                Vote = Vote, isNew = !VoteLog.Any(d => d.StudentId == account.studentId)
            });

            return(View(data));
        }
 public VoteLogApi(VoteLog v)
 {
     if (v != null)
     {
         Id = v.Id;
         SectionId = v.SectionId;
         VoteForId = v.VoteForId;
         UserName = v.UserName;
         Vote = v.Vote;
         Active = v.Active;
     }
 }
Beispiel #9
0
        public async Task <IActionResult> OnPostVoteAsync(int ServiceId)
        {
            var currentUser = await _userManager.GetUserAsync(User);

            Service service = await _context.Service.FirstOrDefaultAsync(q => (q.ServiceId == ServiceId));

            Beneficiary cbc = await _context.Beneficiary.FirstOrDefaultAsync(q => (q.BeneficiaryId == currentUser.UserName));

            VoteLog vl_new = new VoteLog()
            {
                VoteLogId = Guid.NewGuid().ToString(), CorrService = service, Beneficiary = cbc
            };

            _context.VoteLog.Add(vl_new);
            service.Votes++;
            await _context.SaveChangesAsync();

            return(RedirectToPage(new { id = ServiceId }));
        }
Beispiel #10
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            Service = await _context.Service.FirstOrDefaultAsync(m => (m.ServiceId == id));

            if (Service == null)
            {
                return(NotFound());
            }
            var currentUser = await _userManager.GetUserAsync(User);

            CreatedBy = await _context.Beneficiary.FirstOrDefaultAsync(q => (q.BeneficiaryId == Service.CreatedBy.UserName));

            VoteLog vl = await _context.VoteLog.FirstOrDefaultAsync(q => (q.CorrService.ServiceId == Service.ServiceId && currentUser.UserName == CreatedBy.BeneficiaryId));

            hasVoted = (vl == null) ? false : true;
            Comments = await _context.Comment.Where(c => c.CommentedOn.ServiceId == Service.ServiceId).ToListAsync();

            return(Page());
        }
Beispiel #11
0
        public JsonResult SendRating(string r, string s, string id, string url)
        {
            int   autoId    = 0;
            Int16 thisVote  = 0;
            Int16 sectionId = 0;

            Int16.TryParse(s, out sectionId);
            Int16.TryParse(r, out thisVote);
            int.TryParse(id, out autoId);

            if (Session["idu"] == null)
            {
                return(Json("Not authenticated!"));
            }

            if (autoId.Equals(0))
            {
                return(Json("Sorry, record to vote doesn't exists"));
            }
            string usern = userService.GetById((int)Session["idu"]).prenom;

            switch (s)
            {
            case "5":
                var isIt = db.VoteModels.Where(v => v.SectionId == sectionId &&
                                               v.UserName.Equals(usern, StringComparison.CurrentCultureIgnoreCase) && v.VoteForId == autoId).FirstOrDefault();
                if (isIt != null)
                {
                    HttpCookie cookie = new HttpCookie(url, "true");
                    Response.Cookies.Add(cookie);
                    return(Json("<br />You have already rated this post, thanks !"));
                }

                var sch = db.KinderGartens.Where(sc => sc.KinderGartenId == autoId).FirstOrDefault();
                if (sch != null)
                {
                    object obj = sch.Votes;

                    string   updatedVotes = string.Empty;
                    string[] votes        = null;
                    if (obj != null && obj.ToString().Length > 0)
                    {
                        string currentVotes = obj.ToString();     // votes pattern will be 0,0,0,0,0
                        votes = currentVotes.Split(',');
                        // if proper vote data is there in the database
                        if (votes.Length.Equals(5))
                        {
                            // get the current number of vote count of the selected vote, always say -1 than the current vote in the array
                            int currentNumberOfVote = int.Parse(votes[thisVote - 1]);
                            // increase 1 for this vote
                            currentNumberOfVote++;
                            // set the updated value into the selected votes
                            votes[thisVote - 1] = currentNumberOfVote.ToString();
                        }
                        else
                        {
                            votes = new string[] { "0", "0", "0", "0", "0" };
                            votes[thisVote - 1] = "1";
                        }
                    }
                    else
                    {
                        votes = new string[] { "0", "0", "0", "0", "0" };
                        votes[thisVote - 1] = "1";
                    }

                    // concatenate all arrays now
                    foreach (string ss in votes)
                    {
                        updatedVotes += ss + ",";
                    }
                    updatedVotes = updatedVotes.Substring(0, updatedVotes.Length - 1);

                    db.Entry(sch).State = EntityState.Modified;
                    sch.Votes           = updatedVotes;
                    db.SaveChanges();


                    VoteLog vm = new VoteLog()
                    {
                        Active    = true,
                        SectionId = Int16.Parse(s),
                        UserName  = userService.GetById((int)Session["idu"]).prenom,
                        Vote      = thisVote,
                        VoteForId = autoId
                    };

                    db.VoteModels.Add(vm);

                    db.SaveChanges();

                    // keep the school voting flag to stop voting by this member
                    HttpCookie cookie = new HttpCookie(url, "true");
                    Response.Cookies.Add(cookie);
                }
                break;

            default:
                break;
            }
            return(Json("<br />You rated " + r + " star(s), thanks !"));
        }
Beispiel #12
0
        public void PostTest()
        {
            var errSum     = 0;
            var httpClient = new HttpClient();
            var rdm        = new Random();
            var voteLog    = new VoteLog()
            {
                UserId     = "1",
                UserKey    = "2" + (rdm.Next(10000)),
                VoteId     = 6,
                VoteOption = "啊 "
            };
            var voteLogList = new VoteLog[4];

            voteLogList[0] = new VoteLog
            {
                UserId     = "1",
                UserKey    = "2" + (rdm.Next(10000)),
                VoteId     = 1,
                VoteOption = "这个呢?"
            };
            voteLogList[1] = new VoteLog
            {
                UserId     = "1",
                UserKey    = "2" + (rdm.Next(10000)),
                VoteId     = 1,
                VoteOption = "这是谁"
            };
            voteLogList[2] = new VoteLog
            {
                UserId     = "1",
                UserKey    = "2" + (rdm.Next(10000)),
                VoteId     = 1,
                VoteOption = "这又是谁"
            };
            voteLogList[3] = new VoteLog
            {
                UserId     = "1",
                UserKey    = "2" + (rdm.Next(10000)),
                VoteId     = 1,
                VoteOption = "那个呢?"
            };
            var optRdm = new Random();

            var jsonSetting = new JsonSerializerSettings();

            jsonSetting.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            //var json = JsonConvert.SerializeObject(voteLog, jsonSetting);
            //var content = new StringContent(json, Encoding.UTF8, "application/json");
            var taskList = new List <Task>();

            for (int i = 0; i < 2000; i++)
            {
                var taskResult = Task.Run(async() =>
                {
                    try
                    {
                        var targetOpt = voteLogList[optRdm.Next(0, 4)];
                        var pvm       = new PostViewModel();
                        pvm.VoteLog   = new VoteLog
                        {
                            CreateTime = DateTime.Now,
                            UserId     = "123",
                            VoteId     = 15,
                            VoteOption = "Photo 08"
                        };
                        var json = JsonConvert.SerializeObject(pvm, jsonSetting);
                        //var content = new StringContent(json, Encoding.UTF8, "application/json");
                        var content = new StringContent(json, Encoding.UTF8, "application/json");
                        //var result = await httpClient.PostAsync("http://voteapp.oryxl.com/vote/Post", content);
                        var wc     = new WebClient();
                        var result = await httpClient.PostAsync("http://localhost:5000/vote/Post?key=Linengneng", content);
                        Debug.WriteLine("次数: " + ++step + " : " + result.StatusCode);
                        if (result.StatusCode != System.Net.HttpStatusCode.OK)
                        {
                            errSum++;
                            //await Log.WriteLog("Unit Test Status Code : " + result.StatusCode + "\n");
                        }
                    }
                    catch (System.Exception exc)
                    {
                        //await Log.WriteLog("Unit Test Err : " + exc.Message + "\n");
                    }
                });
                taskList.Add(taskResult);
            }

            while (!taskList.All(x => x.Status == TaskStatus.RanToCompletion))
            {
            }
            Assert.IsTrue(errSum == 0);
        }
Beispiel #13
0
        public JsonResult SendRating(string r, string s, string id, string url)
        {
            int   serviceId = 0;
            Int16 thisVote  = 0;
            Int16 sectionId = 0;

            Int16.TryParse(s, out sectionId);
            Int16.TryParse(r, out thisVote);
            int.TryParse(id, out serviceId);

            if (!User.Identity.IsAuthenticated)
            {
                return(Json("<small>Not authenticated!</small>"));
            }

            if (serviceId.Equals(0))
            {
                return(Json("<small>Sorry, record to vote doesn't exists</small>"));
            }

            switch (s)
            {
            case "1":     // property rating
                // check if he has already voted
                var isIt = db.VoteLogs.Where(v => v.SectionId == sectionId &&
                                             v.Username.Equals(User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) && v.VoteForId == serviceId).FirstOrDefault();
                if (isIt != null)
                {
                    // keep the property voting flag to stop voting by this member
                    HttpCookie cookie = new HttpCookie(url, "true");
                    Response.Cookies.Add(cookie);
                    return(Json("<small>You have already rated this post, thanks !</small>"));
                }

                var property = db.Properties.Where(sc => sc.PropertyID == serviceId).FirstOrDefault();

                var property_  = db.Properties.Find(serviceId);
                int totalVotes = property_.TotalVotes;

                if (property != null)
                {
                    object obj = property.Votes;

                    string   updatedVotes = string.Empty;
                    string[] votes        = null;
                    if (obj != null && obj.ToString().Length > 0)
                    {
                        string currentVotes = obj.ToString();     // votes pattern will be 0,0,0,0,0
                        votes = currentVotes.Split(',');
                        // if proper vote data is there in the database
                        if (votes.Length.Equals(5))
                        {
                            // get the current number of vote count of the selected vote, always say -1 than the current vote in the array
                            int currentNumberOfVote = int.Parse(votes[thisVote - 1]);
                            // increase 1 for this vote
                            currentNumberOfVote++;
                            // set the updated value into the selected votes
                            votes[thisVote - 1]  = currentNumberOfVote.ToString();
                            property_.TotalVotes = totalVotes++;
                        }
                        else
                        {
                            votes = new string[] { "0", "0", "0", "0", "0" };
                            votes[thisVote - 1]  = "1";
                            totalVotes           = 1;
                            property_.TotalVotes = totalVotes;
                        }
                    }
                    else
                    {
                        votes = new string[] { "0", "0", "0", "0", "0" };
                        votes[thisVote - 1]  = "1";
                        totalVotes           = 1;
                        property_.TotalVotes = totalVotes;
                    }

                    // concatenate all arrays now
                    foreach (string ss in votes)
                    {
                        updatedVotes += ss + ",";
                    }
                    updatedVotes = updatedVotes.Substring(0, updatedVotes.Length - 1);

                    property.TotalVotes      = totalVotes;
                    db.Entry(property).State = EntityState.Modified;
                    property.Votes           = updatedVotes;
                    db.SaveChanges();

                    VoteLog vl = new VoteLog()
                    {
                        Active    = true,
                        SectionId = Int16.Parse(s),
                        Username  = User.Identity.Name,
                        Vote      = thisVote,
                        VoteForId = serviceId
                    };

                    db.VoteLogs.Add(vl);

                    db.SaveChanges();

                    // keep the product voting flag to stop voting by this member
                    HttpCookie cookie = new HttpCookie(url, "true");
                    Response.Cookies.Add(cookie);
                }
                break;

            default:
                break;
            }
            return(Json("<small>You rated " + r + " star(s), thanks !</small>"));
        }
Beispiel #14
0
        public async Task <string> PorcessResult(PostViewModel _postViewModel)
        {
            VoteLog _voteLog = _postViewModel.VoteLog;

            lock (lockDicObj)
            {
                if (!voteResultLoaded.ContainsKey(_voteLog.VoteId))
                {
                    voteResultLoaded.TryAdd(_voteLog.VoteId, false);
                }
                //load history data
                if (!voteResultLoaded[_voteLog.VoteId])
                {
                    //calculate history sum
                    var _voteLogHistorey = dbContext.VoteLog.Where(x => x.VoteId == _voteLog.VoteId).GroupBy(x => x.VoteOption).Select(x => new
                    {
                        _key   = x.Select(c => c.VoteOption).First(),
                        _count = x.Count()
                    }).ToDictionary(x => x._key, y => y._count);

                    //mapping to globalVoteResult
                    var logList = new BlockingCollection <GlobalVoteResultDicItem>();
                    foreach (var item in _voteLogHistorey)
                    {
                        logList.Add(new GlobalVoteResultDicItem
                        {
                            voteOption = item.Key,
                            voteSum    = item.Value
                        });
                    }
                    // load history data
                    globalVoteResultDic.TryAdd(_voteLog.VoteId, logList);

                    voteResultLoaded[_voteLog.VoteId] = true;
                }
            }
            //check is loaded history data
            if (!globalVoteResultDic.VoteLogList.Contains(_voteLog))
            {
                globalVoteResultDic.VoteLogList.Add(_voteLog);
            }
            //else
            //{
            //    return "exist";
            //}
            return(await Task.Run(() =>
            {
                if (!globalVoteResultDic.ContainsKey(_voteLog.VoteId))
                {
                    globalVoteResultDic.TryAdd(_voteLog.VoteId, new BlockingCollection <GlobalVoteResultDicItem>
                    {
                        new GlobalVoteResultDicItem {
                            voteOption = _voteLog.VoteOption,
                            voteSum = 1
                        }
                    });
                }
                else
                {
                    var itemList = globalVoteResultDic[_voteLog.VoteId];
                    if (!itemList.Any(x => x.voteOption == _voteLog.VoteOption))
                    {
                        itemList.Add(new GlobalVoteResultDicItem
                        {
                            voteOption = _voteLog.VoteOption,
                            voteSum = 1
                        });
                    }
                    else
                    {
                        var item = itemList.FirstOrDefault(x => x.voteOption == _voteLog.VoteOption);
                        if (item != null)
                        {
                            item.voteSum += 1;
                        }
                    }
                }
                var voteResultWrapper = new
                {
                    globalVoteResultDic,
                    nickName = _postViewModel.NickName,
                    avatar = _postViewModel
                };
                return JsonConvert.SerializeObject(voteResultWrapper);
            }));
        }