public object Post(Vote request) { try { if (!string.IsNullOrEmpty(request.DoorID) && null != _voteSource) { var req = base.Request; string voterID = req.Cookies.ContainsKey("VoterID") ? req.Cookies["VoterID"].Value : null; var payload = new VotePayload() { IP = req.RemoteIp, Cookies = req.CookiesAsDictionary(), Headers = req.Headers }; Log.Information("Feature", "Post Vote", "A vote for door {0} from IP: {1}, ID: {2}", request.DoorID, payload.IP, voterID); if (string.IsNullOrEmpty(voterID)) { base.Response.Cookies.AddPermanentCookie("VoterID", Guid.NewGuid().ToString(), false); } _voteSource.PostVote(new VoteInfo() { DoorID = request.DoorID, Payload = payload, VoterID = voterID }); } else { Log.Warning("Warning", "Post Vote", "Posting vote for empty DoorID or no vote source. DoorID: {0}", request.DoorID); } return new VoteResponse() { Status = "Success" }; } catch(Exception ex) { Log.Error(ex, "Error", "Post Vote", "Error posting vote for door {0}", request.DoorID); throw; } }
public ActionResult ProcessVote(VotePostModel vote) { if (vote != null && vote.Value != 0 && this.ModelState.IsValid) { if (vote.Value > 1) { vote.Value = 1; } else if (vote.Value < -1) { vote.Value = -1; } this.currentArticleId = vote.ArticleId; var newVote = new Vote { Value = vote.Value, ArticleId = this.currentArticleId, AuthorId = this.User.Identity.GetUserId() }; this.votes.Create(newVote); } else { this.TempData["ErrorMessage"] = "Illegal operation!"; return this.View("Error"); } var currentStringId = this.identifierProvider.EncodeId(this.currentArticleId); var currentArticle = this.articles.GetById(currentStringId); var newRating = currentArticle.Votes.Sum(x => x.Value); return this.Json(new { value = newRating }); }
public override void ViewDidLoad() { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. var votes = new VoteManager ().ReadVotesFromRemote (); var source = new TableSource (votes); voteTable.Source = source; source.VoteSelected += (object sender, VoteSelectedEventArgs e) => { SelectedVote = e.SelectedVote; if (DateTime.Now > e.SelectedVote.EndTime) { InvokeOnMainThread (() => { PerformSegue ("moveToVoteResultViewSegue", this); }); } else { InvokeOnMainThread (() => { PerformSegue ("moveToVoteFlowSegue", this); }); } }; }
/// <summary> /// Add vote /// </summary> /// <param name="dealId">Deal Id</param> /// <param name="userName">Username</param> /// <param name="date">Date</param> /// <param name="vote">Vote</param> public void AddVote(int dealId, string userName, DateTime date, Vote vote) { string connectionString = ConfigurationManager.ConnectionStrings["ReadWriteDatabase"].ConnectionString; try { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = connection.CreateCommand()) { command.CommandText = SaveVoteQuery; command.Parameters.AddWithValue("@dealId", dealId); command.Parameters.AddWithValue("@vote", vote); command.Parameters.AddWithValue("@userName", userName); command.Parameters.AddWithValue("@date", DateTime.Now); command.ExecuteNonQuery(); } } } catch (Exception e) { log.Warn(e, "Could not add vote to deal: {0} user: {1} vote: {2}", dealId, userName, vote); } }
public void Delete(Vote vote) { // Delete any points associated with this vote _membershipUserPointsService.Delete(PointsFor.Vote, vote.Id); // Delete the vote _context.Vote.Remove(vote); }
private void LoadVideoFragment(Vote vote) { var fragment = VoteVideoTypeFragment.NewInstance (vote); var fragmentManager = this.FragmentManager; var ft = fragmentManager.BeginTransaction (); ft.Replace (Resource.Id.votedescview_fragmentcontent, fragment); ft.Commit (); }
public static Fragment NewInstance(Vote vote) { Fragment fragment = new VoteImageTypeFragment (); Bundle args = new Bundle (); args.PutString (VoteImageTypeFragment_KEY, Newtonsoft.Json.JsonConvert.SerializeObject(vote)); fragment.Arguments = args; return fragment; }
public void Create(int trackId, string authorId, int value) { var vote = new Vote { TrackId = trackId, AuthorId = authorId, Value = value }; this.votes.Add(vote); this.votes.Save(); }
// POST: api/VoteAPI public void Post([FromBody]string value) { using (var db = new SnaFoo.natEntities()) { var vote = new Vote(); vote.SnackId = Int32.Parse(value); vote.VotedOn = DateTime.Now; db.Votes.Add(vote); db.SaveChanges(); } }
public void setupConnection(string oldConnectionId) { string currentConnectionId = this.Context.ConnectionId; Vote storedVote = votes.Find(a => a.connectionId == oldConnectionId); if (storedVote == null) { storedVote = new Vote(); } storedVote.connectionId = currentConnectionId; Caller.setValue(storedVote); SendResults(); }
// Use this for initialization void Start () { //Players a = new PlayerClass("a", "room", 5, "PETA"); b = new PlayerClass("b", "room", 5, "AARP"); c = new PlayerClass("c", "room", 5, "NAACP"); d = new PlayerClass("d", "room", 5, "ALG"); e = new PlayerClass("e", "room", 5, "CI"); f = new PlayerClass("f", "room", 5, "EA"); g = new PlayerClass("g", "room", 5, "NAS"); h = new PlayerClass("h", "room", 5, "FRAC"); i = new PlayerClass("i", "room", 5, "NAMBLA"); VictimGenerator generator = new VictimGenerator(); generator = new VictimGenerator(); players = new PlayerClass[]{ a, b, c, d, e, f, g, h, i}; v1 = generator.generateVictim(); v2 = generator.generateVictim(); v3 = generator.generateVictim(); v4 = generator.generateVictim(); v5 = generator.generateVictim(); v6 = generator.generateVictim(); v7 = generator.generateVictim(); v8 = generator.generateVictim(); v9 = generator.generateVictim(); v10 = generator.generateVictim(); v11 = generator.generateVictim(); v12 = generator.generateVictim(); v13 = generator.generateVictim(); v14 = generator.generateVictim(); v15 = generator.generateVictim(); List < Victim > k1 = new List<Victim> { v1, v2, v3 }; List<Victim> k2 = new List<Victim> { v4, v5, v6 }; List<Victim> k3 = new List<Victim> { v7, v8, v9 }; List<Victim> k4 = new List<Victim> { v10, v11, v12 }; List<Victim> k5 = new List<Victim> { v13, v14, v15 }; List<Victim> s1 = new List<Victim> { v13, v14, v15 }; List<Victim> s2 = new List<Victim> { v10, v11, v12 }; List<Victim> s3 = new List<Victim> { v7, v8, v9 }; List<Victim> s4 = new List<Victim> { v4, v5, v6 }; List<Victim> s5 = new List<Victim> { v4, v5, v6 }; //Votes Vote vote1 = new Vote(k1, s1, 1, players); Vote vote2 = new Vote(k2, s2, 2, players); Vote vote3 = new Vote(k3, s3, 3, players); Vote vote4 = new Vote(k4, s4, 4, players); Vote vote5 = new Vote(k5, s5, 5, players); Vote[] votes = new Vote[] { vote1, vote2, vote3, vote4, vote5 }; Statistics test = new Statistics(votes); }
/// <summary> /// Add a new vote /// </summary> /// <param name="vote"></param> /// <returns></returns> public Vote Add(Vote vote) { var e = new VoteEventArgs {Vote = vote}; EventManager.Instance.FireBeforeVoteMade(this, e); if (!e.Cancel) { _context.Vote.Add(vote); EventManager.Instance.FireAfterVoteMade(this, new VoteEventArgs {Vote = vote}); } return vote; }
public void Subject_Method() { Assert.Throws<ArgumentNullException>(() => IVoteExtensions.Subject<IVote>(null, "subject")); Assert.Throws<ArgumentNullException>(() => Enumerable.Empty<IVote>().Subject(null)); Assert.Throws<ArgumentException>(() => Enumerable.Empty<IVote>().Subject(string.Empty)); Assert.False(Enumerable.Empty<IVote>().Subject("subject").Any()); var first = new Vote { Subject = "FIRST" }; var second = new Vote { Subject = "Second" }; var votes = new[] { null, first, second }; Assert.True(ReferenceEquals(first, votes.Subject("first").Single())); Assert.True(ReferenceEquals(second, votes.Subject("second").Single())); }
public int VoteDown(int id, string userId) { var user = this.users.GetById(userId); var proposal = this.proposals.GetById(id); var upOrDown = 0; if (proposal != null) { var voted = proposal.Votes.FirstOrDefault(v => v.UserId == userId); if (voted == null) { var vote = new Vote() { OptionId = 2, User = user, ProposalId = id }; upOrDown = 1; user.Votes.Add(vote); this.users.SaveChanges(); this.votes.SaveChanges(); } else { if (voted.OptionId == 2) { voted.OptionId = 3; upOrDown = 0; } else if (voted.OptionId == 1 || voted.OptionId == 3) { voted.OptionId = 2; upOrDown = 1; } this.votes.SaveChanges(); } } this.proposals.Update(proposal); this.proposals.SaveChanges(); return upOrDown; }
protected void VoteAgainst_Click(object sender, EventArgs e) { string connectionString = ConfigurationManager.AppSettings.Get("connString"); Vote voteObj = new Vote(); //creating and initializing Vote object voteObj.AdviceId = Convert.ToInt32(Session["AdviceId"].ToString()); voteObj.Username = Session["Username"].ToString(); voteObj.Isliked = false; //passing to business layer BusinessLayer businessLayerObj = new BusinessLayer(); businessLayerObj.InsertVote(voteObj, connectionString); PlaceHolder1.Visible = false; PlaceHolder2.Visible = true; }
public void setVote(Vote v) { string currentConnectionId = this.Context.ConnectionId; Vote storedVote = votes.Find(a => a.connectionId == currentConnectionId); if (storedVote == null) { storedVote = new Vote(); storedVote .connectionId = currentConnectionId; votes.Add(storedVote ); }; storedVote.speed = v.speed; storedVote.preparation = v.preparation; storedVote.techValue = v.techValue; storedVote.demos = v.demos; storedVote.comments = v.comments; SendResults(); }
private void button1_Click(object sender, EventArgs e) { var client = new FoodleServiceClient(); var result = client.GetVoteOptions(); var vote = new Vote { Prio1 = result.Restaurants[0], Prio2 = result.Restaurants[1], Prio3 = result.Restaurants[2] }; var submitted = client.SubmitVote(vote); var res = client.GetResults(); Console.WriteLine(); }
public JsonResult Vote(int photoId) { var loggedUserId = this.User.Identity.GetUserId(); var loggedUser = this.Data.Users.Find(loggedUserId); var photo = this.Data.Pictures.Find(photoId); if (photo.AuthorId == loggedUserId) { return this.Json(new { result = "fail", message = "You cannot vote for your own photo" }, JsonRequestBehavior.AllowGet); } if (photo.Votes.Any(v => v.VoterId == loggedUserId)) { return this.Json(new { result = "fail", message = "Already voted for that photo" }, JsonRequestBehavior.AllowGet); } var vote = new Vote { VotedOn = DateTime.Now, Voter = loggedUser, Picture = photo }; photo.Votes.Add(vote); var contest = this.Data.Contests.Find(photo.ContestId); var leaderId = contest.Pictures .OrderByDescending(p => p.Votes.Count) .Take(1) .Select(p => p.AuthorId) .FirstOrDefault(); contest.CurrentLeader = this.Data.Users.Find(leaderId); this.Data.SaveChanges(); return this.Json(new { result = "success" }, JsonRequestBehavior.AllowGet); }
public object Get(Vote request) { try { string voterID = base.Request.CookiesAsDictionary().ContainsKey("VoterID") ? base.Request.CookiesAsDictionary()["VoterID"] : null; Log.Information("Feature", "Get Vote", "A get for door {0} from IP: {1}, ID: {2}", request.DoorID, base.Request.RemoteIp, voterID); if (string.IsNullOrEmpty(voterID)) { base.Response.Cookies.AddPermanentCookie("VoterID", Guid.NewGuid().ToString(), false); } return new VoteResponse() { Status = string.Format( "Welcome to the Door Competition voting service. You can post your vote to this endpoint. DoorID: {0}", request.DoorID) }; } catch(Exception ex) { Log.Error(ex, "Error", "Get Vote", "Error when getting vote for door {0}", request.DoorID); throw; } }
/// <summary> /// Upvotes a photo and writes an app activity for the vote action. /// </summary> /// <param name="context">The request and response object with the user in session. /// </param> /// <returns>On success, returns the Photo object for the image voted on. On failure, /// returns null.</returns> public Photo DoVote(HttpContext context, int photoId) { User user = GetUser(context); // User will be NULL if there isn't someone signed in. if (user == null) { return null; } if (!CanVote(user.id, photoId)){ return null; } // Create the vote and increment the vote count for this photo. PhotohuntContext db = new PhotohuntContext(); Vote v = new Vote(); v.photoId = photoId; v.ownerUserId = user.id; db.Votes.Add(v); db.SaveChanges(); var photoQuery = from b in db.Photos where b.id == photoId select b; Photo voteTarget = null; foreach (Photo currPhoto in photoQuery) { voteTarget = currPhoto; } voteTarget.numVotes += 1; db.SaveChanges(); WriteGooglePlusVoteAppActivity(user, voteTarget); return voteTarget; }
/// <summary> /// register a new vote on an snippet /// </summary> /// <param name="newVote"></param> /// <returns></returns> public async Task<int> RegisterVote(Vote newVote) { var snippet = await _snippetRepository.GetById(newVote.ItemId); if (snippet == null) return 0; //No Snippet return zero var existingVotes = await _voteRepository.GetByItemId(newVote.ItemId); if (existingVotes.Count(v => v.UserId == newVote.UserId) > 0) return snippet.Score; //Already voted return current score //create the vote var created = await _voteRepository.CreateVote(newVote); if (created.Id != Guid.Empty) { //update the score on the snippet model var voteCount = _voteRepository.GetByItemId(snippet.Id).Result.Sum(v => v.Value); if (voteCount != snippet.Score) { snippet.Score = voteCount; } snippet = await _snippetRepository.Update(snippet); } return snippet.Score; }
private void SendResults() { Vote total = new Vote(); if (votes.Count > 0) { foreach (Vote v in votes) { total.speed += v.speed; total.preparation += v.preparation; total.techValue += v.techValue; total.demos += v.demos; if (!String.IsNullOrWhiteSpace(v.comments)) { if (!String.IsNullOrWhiteSpace(total.comments)) { total.comments += "<br/>"; } total.comments += v.comments.Replace("\n", "<br/>"); } } total.numberOfVotes = votes.Count(); } Clients.updateVotes(total); }
public Vote GetItem(int id, string userId) { Vote item = voteRepository.GetByID(id, userId); return(item); }
public async Task<Vote> CreateVote(Vote newVote) { newVote.Id = Guid.NewGuid(); _dataContext.Add(newVote); return newVote; }
public async Task <Vote> ReplaceVote(int categoryId, int postId, int answerId, int voteId, [FromBody] Vote vote) { vote.CategoryId = categoryId; vote.PostId = postId; vote.AnswerId = answerId; vote.VoteId = voteId; var updated = await _postVotesRepository.UpdateAsyn(vote); return(updated); }
public void UpdateUIWith(Vote vote) { lbDescription.Text = vote.Description; imageDescription.Image = UIImage.FromFile ("Images/sample.jpg"); }
public void AddVote(Vote vote) { _context.Votes.Add(vote); SaveChanges(); var test = _context.Votes.ToList(); }
public void RemoveVote(Vote vote) { ctx.Votes.Remove(vote); ctx.SaveChanges(); }
public void Load(string uri, int vposShift, int startPos, int endPos) { XmlReader xr = XmlReader.Create(uri); List <Comment> result = new List <Comment>(); List <Perm> perms = new List <Perm>(); List <Vote> votes = new List <Vote>(); if (xr == null) { return; } int count = 0; Comment cmt = null; Vote vote = null; Perm perm = null; while (xr.Read()) { if (xr.ReadToFollowing("chat")) { int vpos = int.Parse(xr.GetAttribute("vpos")) - startPos + vposShift; if (vpos < -10 || vpos > endPos + 10) { continue; } int premium = int.Parse(xr.GetAttribute("premium") ?? "0"); string mail = xr.GetAttribute("mail") ?? ""; string[] mails = mail.ToLower().Split(' '); cmt = new Comment() { Count = count, //Number = int.Parse(xr.GetAttribute("no")), Vpos = vpos, //Mail = xr.GetAttribute("mail") ?? "", Mails = mails, Text = xr.ReadString() }; bool add = true; if (cmt.Text.StartsWith("/hb")) { continue; } if (cmt.Text.Contains("\n"))// Environment.NewLine { cmt.IsAA = true; } if (premium >= 3) { cmt.Text = Comment.StripHtmlTags(cmt.Text); add = false; if (cmt.Text.StartsWith("/clear") || cmt.Text.StartsWith("/cls")) { if (perm != null) { double endTime = cmt.Vpos / 100.0; if (perm.StartTime + 180.0 >= endTime) { perm.EndTime = endTime; } perm = null; } } else if (cmt.Text.StartsWith("/vote ")) { //start showresult stop cmt.IsVote = true; cmt.Text = cmt.Text.Substring(6); if (cmt.Text.StartsWith("start ")) { if (vote != null) { votes.Add(vote); } vote = new Vote(); vote.VoteComment = cmt; vote.StartTime = cmt.Vpos / 100.0; vote.ResultTime = (cmt.Vpos / 100.0) + 10.0; //temp vote.EndTime = (cmt.Vpos / 100.0) + 10.0; //temp } else if (cmt.Text.StartsWith("showresult ")) { if (vote != null) { vote.ResultComment = cmt; vote.ResultTime = (cmt.Vpos / 100.0); vote.EndTime = (cmt.Vpos / 100.0) + 10.0; //temp } } else if (cmt.Text.StartsWith("stop")) { if (vote != null) { vote.EndTime = cmt.Vpos / 100.0; votes.Add(vote); vote = null; } } } else { if (cmt.Text.StartsWith("/perm ")) { cmt.Text = cmt.Text.Substring(6); } cmt.IsPerm = true; perm = new Perm(); perm.Comment = cmt; perm.StartTime = cmt.Vpos / 100.0 - 3; //ちょっと早めに出す perm.EndTime = perm.StartTime + 12.0; //temp perms.Add(perm); } } if (add) { result.Add(cmt); } count++; } } if (vote != null) { votes.Add(vote); } result.Sort((a, b) => { return(a.Vpos >= b.Vpos ? 1 : -1); }); //逆順 votes.Sort((a, b) => { return(a.StartTime >= b.StartTime ? -1 : 1); }); perms.Sort((a, b) => { return(a.StartTime >= b.StartTime ? -1 : 1); }); Comments = result.ToArray(); Perms = perms.ToArray(); Votes = votes.ToArray(); }
public static string AnalysisUrl(string url) { try { if (!Utils.IsURL(url)) { return(null); } string tmpCode = ""; if (IsShortLink(url, ref tmpCode)) { return(tmpCode); } string shortlink = UrlShort.ShortUrl(url)[0]; Url u = GetUrlByShortLink(shortlink); if (u != null) { UpdateUrlForRefCount(u.ID); } else { u = new Url(); u.MediaID = -1; u.OriginalUrl = url; u.ShortLink = shortlink; u.Type = TypeConfigs.GetUrlNormal; u.ID = Urls.CreateUrl(u); } if (u.MediaID < 0) { long mediaID = 0; int type = TypeConfigs.GetUrlNormal; if (Videos.IsVideoUrl(url)) { VideoInfo vInfo = Videos.GetVideo(url); if (vInfo != null) { long vid = Videos.CreateVideo(vInfo); if (vid > 0) { mediaID = vid; type = TypeConfigs.GetUrlVideo; } } } if (Musics.IsMusicUrl(url)) { Music music = new Music(); music.Title = Path.GetFileNameWithoutExtension(url); music.MusicUrl = url; long mid = Musics.CreateMusic(music); if (mid > 0) { mediaID = mid; type = TypeConfigs.GetUrlMusic; } } if (Votes.IsVoteUrl(url)) { long vid = Votes.GetVoteIdFromUrl(url); Vote vote = Votes.GetVoteByID(vid); if (vote != null) { mediaID = vote.ID; type = TypeConfigs.GetUrlVote; } } if (mediaID != 0) { UpdateUrlForMedia(u.ID, mediaID, type); return(shortlink); } else { return(shortlink); } } else { return(shortlink); } } catch (Exception ex) { Logs.WriteErrorLog(ex); return(null); } }
public async Task EndVote([Remainder] string voteId = "0") { //The input is just a number if (ulong.TryParse(voteId, NumberStyles.None, CultureInfo.InvariantCulture, out ulong id)) { //Cancel last vote the user started if (id == 0) { UserAccount user = UserAccountsManager.GetAccount((SocketGuildUser)Context.User); if (user.UserLastVoteId != 0) { await VotingService.EndVote( ServerListsManager.GetServer(Context.Guild).GetVote(user.UserLastVoteId), Context.Guild); } else { await Context.Channel.SendMessageAsync( "You don't appear to have any votes running, if you do, put in the ID of the vote message with this command as well!"); } return; } Vote vote = ServerListsManager.GetServer(Context.Guild).GetVote(id); if (vote == null) { await Context.Channel.SendMessageAsync("There are no votes with that ID!"); return; } if (((SocketGuildUser)Context.User).GuildPermissions.ManageMessages) { await VotingService.EndVote(vote, Context.Guild); await Context.Channel.SendMessageAsync("That vote was ended."); return; } if (vote.VoteStarterUserId != Context.User.Id) { await VotingService.EndVote(vote, Context.Guild); await Context.Channel.SendMessageAsync("Your vote was ended."); return; } } //End all votes if (voteId.RemoveWhitespace() == "*") { if (!((SocketGuildUser)Context.User).GuildPermissions.ManageMessages) { await Context.Channel.SendMessageAsync("You don't have permissions to end all votes!"); return; } Vote[] votes = ServerListsManager.GetServer(Context.Guild).Votes.ToArray(); foreach (Vote vote in votes) { await VotingService.EndVote(vote, Context.Guild); } await Context.Channel.SendMessageAsync("All votes were ended."); return; } await Context.Channel.SendMessageAsync( "Unknown argument! Either needs to be none or a message ID to end a vote, or `*` to end all."); }
protected override void Seed(WCIWTDbContext context) { var admin = new User { // Password: qwerty123 Id = Guid.Parse("aa00dc64-5c07-40fe-a916-175165b9b90f"), Username = "******", Email = "*****@*****.**", PasswordHash = "FuQPWbHATtEPh0CO1i6tUqI65/k=", PasswordSalt = "WMYJiF/FT8bEchjALl3bCg==", Gender = Gender.Male, IsAdmin = true, Birthdate = new DateTime(1995, 8, 20) }; // Password: qwerty123 var user1 = new User { Id = Guid.Parse("22d1461d-41db-4a5a-8996-dd0fcf7f5f04"), Username = "******", Email = "*****@*****.**", PasswordHash = "FuQPWbHATtEPh0CO1i6tUqI65/k=", PasswordSalt = "WMYJiF/FT8bEchjALl3bCg==", Gender = Gender.Male, IsAdmin = false, Birthdate = new DateTime(1990, 8, 20) }; var user2 = new User { Id = Guid.Parse("abcf8c45-cdcb-4e12-9aeb-b6adef036964"), Username = "******", Email = "*****@*****.**", PasswordHash = "FuQPWbHATtEPh0CO1i6tUqI65/k=", PasswordSalt = "WMYJiF/FT8bEchjALl3bCg==", Gender = Gender.Female, IsAdmin = false, Birthdate = new DateTime(1950, 8, 20) }; var user3 = new User { Id = Guid.Parse("b8f4bf3c-0367-4ae9-a408-4bd98541f100"), Username = "******", Email = "*****@*****.**", PasswordHash = "FuQPWbHATtEPh0CO1i6tUqI65/k=", PasswordSalt = "WMYJiF/FT8bEchjALl3bCg==", Gender = Gender.Female, IsAdmin = false, Birthdate = new DateTime(2004, 8, 20) }; var post1 = new Post { Id = Guid.Parse("afbfd424-d186-4747-bd9b-8d894c410936"), Time = new DateTime(2018, 10, 20, 20, 20, 35), Text = "This is a test public post. Vote for the outfit you like the most #ootd", Visibility = PostVisibility.Public, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user3.Id, }; var post2 = new Post { Id = Guid.Parse("e710774f-586c-48ca-9487-9c2d5db8070b"), Time = new DateTime(2018, 8, 20, 20, 20, 35), Text = "This is another test public post. Vote for the outfit you like the most #ootd", Visibility = PostVisibility.Public, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user1.Id, }; var post3 = new Post { Id = Guid.Parse("5fcad9cc-ba64-4161-969f-1c941c9e2da5"), Time = new DateTime(2018, 5, 20, 20, 20, 35), Text = $"This is a test private post. Only friends of {user1.Username} should see this.Vote for the outfit you like the most #classy", Visibility = PostVisibility.FriendsOnly, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user1.Id, }; var post4 = new Post { Id = Guid.Parse("09dd3724-6df5-4f16-aeb3-2149d06c071d"), Time = new DateTime(2018, 1, 20, 20, 20, 35), Text = "This is a test of gender restricted post. Only women should see this.Vote for the outfit you like the most #ootd", Visibility = PostVisibility.Public, GenderRestriction = Gender.Female, HasAgeRestriction = false, UserId = user2.Id, }; var post5 = new Post { Id = Guid.Parse("142330f6-3648-46e3-8ece-64ae166dd914"), Time = new DateTime(2018, 3, 20, 20, 20, 35), Text = "This is a test of age restricted post. Only users with age between 20 and 40 should see this.Vote for the outfit you like the most #fresh", Visibility = PostVisibility.Public, GenderRestriction = Gender.NoInformation, HasAgeRestriction = true, AgeRestrictionFrom = 20, AgeRestrictionTo = 40, UserId = user2.Id, }; var post6 = new Post { Id = Guid.Parse("142330f6-3648-46e3-8ece-64ae166dd915"), Time = new DateTime(2018, 3, 20, 20, 20, 35), Text = "This is a test post from Lenka #ootd", Visibility = PostVisibility.Public, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user2.Id, }; var post7 = new Post { Id = Guid.Parse("142330f6-3648-46e3-8ece-64ae166dd916"), Time = new DateTime(2018, 3, 20, 20, 20, 35), Text = "This is a test post from Marie #ootd", Visibility = PostVisibility.Public, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user3.Id, }; var post8 = new Post { Id = Guid.Parse("142330f6-3648-46e3-8ece-64ae166dd917"), Time = new DateTime(2018, 3, 20, 20, 20, 35), Text = "This is a private post from Marie #classy", Visibility = PostVisibility.FriendsOnly, GenderRestriction = Gender.NoInformation, HasAgeRestriction = false, UserId = user3.Id, }; var postReply1 = new PostReply { Id = Guid.Parse("9d3a47ff-0fa2-415f-9da5-da14ffeab957"), UserId = user1.Id, PostId = post1.Id, Time = new DateTime(2018, 10, 20, 22, 20, 35), Text = "Hey, this is me commenting my own post" }; var postReply2 = new PostReply { Id = Guid.Parse("9d3a47ff-0fa2-415f-9da5-da14ffeab958"), UserId = user2.Id, PostId = post1.Id, Time = new DateTime(2018, 10, 20, 22, 25, 35), Text = "Yo, nice outfit!" }; var user1Touser3Friendship = new Friendship { Id = Guid.Parse("9d3a47ff-0fa2-415f-9da5-da14ffeab959"), ApplicantId = user1.Id, RecipientId = user3.Id, IsConfirmed = true }; var message1 = new Message { Id = Guid.Parse("b5bf2ab1-b51c-43bc-a018-55f35a88fac9"), UserSenderId = user1.Id, UserReceiverId = user3.Id, Seen = true, Time = new DateTime(2018, 10, 10, 20, 30, 30), Text = "Hey, cool website right? Did you know you can also send private messages?" }; var message2 = new Message { Id = Guid.Parse("b5bf2ab1-b51c-43bc-a018-55f35a88fac1"), UserSenderId = user3.Id, UserReceiverId = user1.Id, Seen = true, Time = new DateTime(2018, 10, 10, 20, 30, 50), Text = "Sure, it's really great. How did you find out about it?" }; var message3 = new Message { Id = Guid.Parse("b5bf2ab1-b51c-43bc-a018-55f35a88fac2"), UserSenderId = user1.Id, UserReceiverId = user3.Id, Seen = true, Time = new DateTime(2018, 10, 10, 20, 31, 30), Text = "I read about it in the new issue of Forbes. How about you?" }; var message4 = new Message { Id = Guid.Parse("b5bf2ab1-b51c-43bc-a018-55f35a88fac3"), UserSenderId = user3.Id, UserReceiverId = user1.Id, Seen = false, Time = new DateTime(2018, 10, 10, 20, 35, 30), Text = "Well, my friend told me about it." }; string imageFolder = "~\\Content\\Images\\TestingImages\\"; var imageGirl1 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "lucia1.jpg")); var imageGirl2 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "lucia2.jpg")); var imageGirl3 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "lucia3.jpg")); var imageGirl4 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "lucia4.jpg")); var imageGirl5 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "lucia5.jpg")); var imageHelicopter1 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "apache1.jpg")); var imageHelicopter2 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "apache2.jpg")); var image1Post2 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0201.jpg")); var image2Post2 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0202.jpg")); var image1Post3 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0301.jpg")); var image2Post3 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0302.jpg")); var image3Post3 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0303.jpg")); var image1Post4 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0401.jpg")); var image2Post4 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0402.jpg")); var image3Post4 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0403.jpg")); var image1Post5 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0501.jpg")); var image2Post5 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0502.jpg")); var image3Post5 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0503.jpg")); var image1Post6 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0601.jpg")); var image2Post6 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0602.jpg")); var image3Post6 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0603.jpg")); var image1Post7 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0701.jpg")); var image2Post7 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0702.jpg")); var image3Post7 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0703.jpg")); var image1Post8 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0801.jpg")); var image2Post8 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0802.jpg")); var image3Post8 = File.ReadAllBytes(HttpContext.Current.Server.MapPath(imageFolder + "img0803.jpg")); var vote1Image1 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e20"), Type = VoteType.Like, UserId = user1.Id, }; var vote2Image1 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e21"), Type = VoteType.Dislike, UserId = user2.Id, }; var vote1Image4 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e22"), Type = VoteType.Like, UserId = user3.Id, }; var vote2Image4 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e23"), Type = VoteType.Like, UserId = user2.Id, }; var vote3Image4 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e24"), Type = VoteType.Like, UserId = user1.Id, }; var vote1Image5 = new Vote { Id = Guid.Parse("5f107264-fee7-4a35-ab7f-f5e302c42e26"), Type = VoteType.Like, UserId = user1.Id, }; var image1Post1 = new Image { Id = Guid.Parse("bbe4fcc1-03f5-433a-b677-0022a7a3b3d1"), DislikesCount = 1, LikesCount = 1, BinaryImage = imageGirl1, PostId = post1.Id, }; var image2Post1 = new Image { Id = Guid.Parse("bbe4fcc1-03f5-433a-b677-0022a7a3b3d2"), DislikesCount = 0, LikesCount = 0, BinaryImage = imageGirl2, PostId = post1.Id, }; var image3Post1 = new Image { Id = Guid.Parse("bbe4fcc1-03f5-433a-b677-0022a7a3b3d3"), DislikesCount = 0, LikesCount = 0, BinaryImage = imageGirl3, PostId = post1.Id, }; var image4Post1 = new Image { Id = Guid.Parse("bbe4fcc1-03f5-433a-b677-0022a7a3b3d4"), DislikesCount = 0, LikesCount = 3, BinaryImage = imageGirl4, PostId = post1.Id, }; var image5Post1 = new Image { Id = Guid.Parse("bbe4fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 1, BinaryImage = imageGirl5, PostId = post1.Id, }; var image1Post2Obj = new Image { Id = Guid.Parse("abe4fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post2, PostId = post2.Id, }; var image2Post2Obj = new Image { Id = Guid.Parse("abe5fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post2, PostId = post2.Id, }; var image1Post3Obj = new Image { Id = Guid.Parse("abe6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post3, PostId = post3.Id, }; var image2Post3Obj = new Image { Id = Guid.Parse("abe7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post3, PostId = post3.Id, }; var image3Post3Obj = new Image { Id = Guid.Parse("abe8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post3, PostId = post3.Id, }; var image1Post4Obj = new Image { Id = Guid.Parse("ace6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post4, PostId = post4.Id, }; var image2Post4Obj = new Image { Id = Guid.Parse("ace7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post4, PostId = post4.Id, }; var image3Post4Obj = new Image { Id = Guid.Parse("ace8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post4, PostId = post4.Id, }; var image1Post5Obj = new Image { Id = Guid.Parse("ade6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post5, PostId = post5.Id, }; var image2Post5Obj = new Image { Id = Guid.Parse("ade7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post5, PostId = post5.Id, }; var image3Post5Obj = new Image { Id = Guid.Parse("ade8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post5, PostId = post5.Id, }; var image1Post6Obj = new Image { Id = Guid.Parse("aee6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post6, PostId = post6.Id, }; var image2Post6Obj = new Image { Id = Guid.Parse("aee7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post6, PostId = post6.Id, }; var image3Post6Obj = new Image { Id = Guid.Parse("aee8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post6, PostId = post6.Id, }; var image1Post7Obj = new Image { Id = Guid.Parse("cde6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post7, PostId = post7.Id, }; var image2Post7Obj = new Image { Id = Guid.Parse("cde7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post7, PostId = post7.Id, }; var image3Post7Obj = new Image { Id = Guid.Parse("cde8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post7, PostId = post7.Id, }; var image1Post8Obj = new Image { Id = Guid.Parse("cce6fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image1Post8, PostId = post8.Id, }; var image2Post8Obj = new Image { Id = Guid.Parse("cce7fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image2Post8, PostId = post8.Id, }; var image3Post8Obj = new Image { Id = Guid.Parse("cce8fcc1-03f5-433a-b677-0022a7a3b3d5"), DislikesCount = 0, LikesCount = 0, BinaryImage = image3Post8, PostId = post8.Id, }; vote1Image1.ImageId = image1Post1.Id; vote2Image1.ImageId = image1Post1.Id; vote1Image4.ImageId = image4Post1.Id; vote2Image4.ImageId = image4Post1.Id; vote3Image4.ImageId = image4Post1.Id; vote1Image5.ImageId = image5Post1.Id; var hashtagOotdPost1 = new Hashtag { Id = Guid.Parse("3150e617-f069-4fc9-98bf-78e87b4084ad"), Tag = "#ootd", PostId = post1.Id, }; var hashtagOotdPost2 = new Hashtag { Id = Guid.Parse("0411449a-4f06-463b-bcbb-9f15843a4ecd"), Tag = "#ootd", PostId = post2.Id, }; var hashtagClassydPost3 = new Hashtag { Id = Guid.Parse("fb34c6a6-390e-41e2-aae5-79ed941df01a"), Tag = "#classy", PostId = post3.Id, }; var hashtagOotdPost4 = new Hashtag { Id = Guid.Parse("c8b27680-20a0-474c-ae96-ff10815bf6f0"), Tag = "#ootd", PostId = post4.Id, }; var hashtagFreshdPost5 = new Hashtag { Id = Guid.Parse("695e5879-3b3c-4cf3-bb9e-5af7ce40d069"), Tag = "#fresh", PostId = post5.Id, }; var hashtagOotdPost6 = new Hashtag { Id = Guid.Parse("67c634c7-e8dc-44f6-a304-2db8c83f46eb"), Tag = "#ootd", PostId = post6.Id, }; var hashtagOotdPost7 = new Hashtag { Id = Guid.Parse("15595c32-07ba-4fc7-8be5-f9d1a754b34c"), Tag = "#ootd", PostId = post7.Id, }; var hashtagClassydPost8 = new Hashtag { Id = Guid.Parse("276fe6f5-28ec-4f5b-8e80-b606ee002e6b"), Tag = "#classy", PostId = post8.Id, }; context.Votes.AddOrUpdate(vote => vote.Id, vote1Image1, vote2Image1, vote1Image4, vote1Image5, vote2Image4, vote3Image4); context.Images.AddOrUpdate(image => image.Id, image1Post1, image2Post1, image3Post1, image4Post1, image5Post1, image1Post2Obj, image2Post2Obj, image1Post3Obj, image2Post3Obj, image3Post3Obj, image1Post4Obj, image2Post4Obj, image3Post4Obj, image1Post5Obj, image2Post5Obj, image3Post5Obj, image1Post6Obj, image2Post6Obj, image3Post6Obj, image1Post7Obj, image2Post7Obj, image3Post7Obj, image1Post8Obj, image2Post8Obj, image3Post8Obj); context.Users.AddOrUpdate(user => user.Id, admin, user1, user2, user3); context.Posts.AddOrUpdate(post => post.Id, post1, post2, post3, post4, post5, post6, post7, post8); context.Friendships.AddOrUpdate(friendship => friendship.Id, user1Touser3Friendship); context.PostReplys.AddOrUpdate(postReply => postReply.Id, postReply1, postReply2); context.Messages.AddOrUpdate(message => message.Id, message1, message2, message3, message4); context.Hashtags.AddOrUpdate(hashtag => hashtag.Id, hashtagOotdPost1, hashtagOotdPost2, hashtagOotdPost4, hashtagOotdPost6, hashtagOotdPost7, hashtagFreshdPost5, hashtagClassydPost3, hashtagClassydPost8); context.SaveChanges(); }
public VoteOnCommentEvent(int commentId, Vote newVote, Vote?oldVote = null) { CommentId = commentId; NewVote = newVote; OldVote = oldVote; }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } string username = HttpContext.Session.GetString("username"); AppCondition app = await _context.AppCondition.FirstOrDefaultAsync(app => app.AppConditionId.Equals(1)); //Now we have to check wether to vote or unvote //We will vote if a user hasn't vote for that team yet //IList<Vote> allUserVotes = await _context.Vote.Where(v => v.UserName.Equals(username) && v.EventID.Equals(app.EventID)).ToListAsync(); //foreach (var vote in allUserVotes) //{ // //Now we run through the entire loop if // //The team with teamid = id is found in the list // //Then we unvote it // if (vote.TeamID.Equals(id)) // { // //WE have found the vote // _context.Vote.Remove(vote); // await _context.SaveChangesAsync(); // } //} Vote vote = await _context.Vote.FirstOrDefaultAsync(v => v.UserName.Equals(username) && v.TeamID.Equals(id) && v.EventID.Equals(app.EventID)); Team team = await _context.Team.FirstOrDefaultAsync(t => t.TeamId.Equals(id)); User user = await _context.User.FirstOrDefaultAsync(u => u.UserName.Equals(username)); if (vote == null) { //That means user wish to vote for this team Vote newVote = new Vote() { EventID = app.EventID, TeamID = team.TeamId, TeamName = team.TeamName, UserID = user.UserId, UserName = user.UserName }; _context.Vote.Add(newVote); await _context.SaveChangesAsync(); } else { //Then we will have to unvote this team as user has already votes fo4r this team _context.Vote.Remove(vote); await _context.SaveChangesAsync(); } IList <Judge> allJudges = await _context.Judge.Where(j => j.EventID.Equals(app.EventID)).ToListAsync(); //Before we send the user back we need to the voting //We need to perform certain checks for that foreach (var judge in allJudges) { if (judge.UserID.Equals(user.UserId)) { return(RedirectToPage("JudgeVoting")); } } //Other wise the user is just a normal user //So we just send him/her back to confirm voting return(RedirectToPage("Voting")); }
public async Task <Vote> UpdatePost([FromBody] Vote vote) { var updated = await _postVotesRepository.UpdateAsyn(vote); return(updated); }
// POST: api/Vote public Vote Post([FromBody] Vote value) { return(DataAccessHelper <Vote> .AddEntity(value)); }
public Vote GetVote(string resolutionId, string userId) { Vote vote = _context.Votes.Where(z => z.ResolutionId == resolutionId && z.UserId == userId).FirstOrDefault(); return(vote); }
// PUT: api/Vote/5 public void Put(int id, [FromBody] Vote value) { DataAccessHelper <Vote> .UpdateEntity(id, value); }
public static int Main(string[] args) { Logger.Success(new SQLiteConnectionStringBuilder() { DataSource = "EventDatabase.db" }.ConnectionString); //Load server config Config.LoadConfig(); //Start Discord bot #if (TEAMSABER) var serverName = "Team Saber"; #elif (DISCORDCOMMUNITY) var serverName = "Beat Saber Discord Server"; #elif (TRUEACCURACY) var serverName = "True Accuracy Championship"; #elif (ASIAVR) var serverName = "Asia VR Community"; #elif QUALIFIER var serverName = "Beat Saber World Cup"; #elif BTH var serverName = "Beat the Hub Season 1"; #elif BEATKHANA var serverName = "BeatKhana!"; #elif HIDDENNOTES var serverName = "Beat Saber Testing Server"; #elif BETA var serverName = "Beat Saber Testing Server"; #endif #if (TEAMSABER) string scoreChannel = "event-feed"; #elif (DISCORDCOMMUNITY) ulong scoreChannel = 457952124307898368; //"event-scores"; #elif (TRUEACCURACY) ulong scoreChannel = 663160463017639971; //"qualifier-feed"; #elif (ASIAVR) ulong scoreChannel = 572908789699969054; //"scores feed"; #elif QUALIFIER ulong scoreChannel = 724118394693222451; //"qualifier-scores"; #elif BTH ulong scoreChannel = 713655231107301446; //"qualifier-scores"; #elif BEATKHANA ulong scoreChannel = 488445468141944842; //"event-scores"; #elif HIDDENNOTES ulong scoreChannel = 488445468141944842; #elif BETA ulong scoreChannel = 488445468141944842; //"event-scores"; #endif #if (TEAMSABER) string infoChannel = "event-feed"; #elif (DISCORDCOMMUNITY) ulong infoChannel = 457952124307898368; //"event-scores"; #elif (TRUEACCURACY) ulong infoChannel = 663160463017639971; //"qualifier-feed"; #elif (ASIAVR) ulong infoChannel = 572908789699969054; //"scores feed"; #elif QUALIFIER ulong infoChannel = 709154896183820349; //"country-registration"; #elif BTH ulong infoChannel = 713655231107301446; //"qualifier-scores"; #elif BEATKHANA ulong infoChannel = 488445468141944842; //"event-scores" #elif HIDDENNOTES ulong infoChannel = 488445468141944842; #elif BETA ulong infoChannel = 488445468141944842; //"event-scores"; #endif Thread thread1 = new Thread(async() => { CommunityBot.Start(serverName, scoreChannel, infoChannel); Vote.RegisterVotesWithBot(); await Task.Delay(-1); }); thread1.Start(); //Set up HTTP server Thread thread2 = new Thread(new ThreadStart(StartHttpServer)); thread2.Start(); //Kill on enter press Console.ReadLine(); return(0); }
private async Task <int> DecrementCachedVotesSum(Vote vote) => await _cache.DecrementAndGetConcurrentAsync( GetCachingKey(new VoteCachingContext(vote.TargetId, vote.Target.Target)), () => _voteRepository.GetVotesSumAsync(vote.TargetId), 60);
public void AddVote(int postid, Vote vote) { GetById(postid).AddVote(vote); }
// // GET: /Default5/RowData/5 public ActionResult RowData(int id) { Vote vote = db.Votes.Single(v => v.id == id); return(PartialView("GridData", new Vote[] { vote })); }
public async Task <IActionResult> OnPostAsync(int id) { if (!ModelState.IsValid) { return(Page()); } Voting = await Context.Votings .Include(v => v.Episode) .Include(v => v.NormalOptions) .ThenInclude(o => o.Votes) .FirstOrDefaultAsync(m => m.VotingID == id); NormalOptions = Voting.NormalOptions.ToArray(); if (Voting.Policy == Voting.PolicyType.Equality) { Vote.Value = Voting.Threshold; } if (Vote.Value < Voting.Threshold) { ErrorMessage = "票價不足於投票設定的最小值"; return(Page()); } string UserID = UserManager.GetUserId(User); Vote ExistingVote = null; foreach (var option in NormalOptions) { ExistingVote = option .Votes .Where(v => v.OwnerID == UserID) .FirstOrDefault(); if (ExistingVote != null) { break; } } NormalOption = await Context .NormalOptions .Where(n => n.NormalOptionID == NormalOption.NormalOptionID) .FirstOrDefaultAsync(); if (ExistingVote == null) { Vote NewVote = new Vote(); //Protect from overposting attacks if (await TryUpdateModelAsync <Vote>( NewVote, "Vote", // Prefix for form value. v => v.Value)) { NewVote.OwnerID = UserID; NewVote.NormalOptionID = NormalOption.NormalOptionID; Context.Votes.Add(NewVote); } } else { Voted = true; ErrorMessage = "已經投過票了"; return(Page()); } if (Vote.Value > 0) { if (VirtualVote) { await VirtualVoteOptionAsync(Context, NormalOption, Vote.Value); } else { await VoteOptionAsync(Context, NormalOption, Vote.Value); } if (ErrorMessage == "餘額不足") { return(Page()); } return(RedirectToPage("/Episodes/Details", "OnGet", new { id = Voting.EpisodeID }, "Voting")); } else { await Context.SaveChangesAsync(); return(RedirectToPage("/Episodes/Details", "OnGet", new { id = Voting.EpisodeID }, "Voting")); } }
public static void ProcessMessage(string message, string userName) { userName = userName.ToLowerInvariant(); message = message.ToLowerInvariant(); // Console.WriteLine("From: {0} - Message:{1} ", channelName, msg); if (userName == "streamlabs") { message = message.Substring(2); Console.WriteLine("Message:{0}", message); } if (!message.StartsWith("!")) { return; } string[] split = message.Substring(1).Split(' '); if (userName == Room || userName == AdminUsrName) { // admin stuff } switch (split[0]) { case "item": if (split.Length > 1) { if (itemDict.TryGetValue(split[1], out int v)) { GiveItem(v); } } else { int i = RandomNumber(0, 10); if (i == 9) { ++i; } GiveItem(i); } break; case "omochao": SpawnOmochao(); break; case "voice": if (split.Length > 1) { if (int.TryParse(split[1], out int id) && id >= 0 && id < 2727) { PlayVoice(Math.Min(Math.Max(0, id), 2726)); } } else { PlayVoice(RandomNumber(0, 2727)); } break; case "stop": Stop(); break; case "gottagofast": GottaGoFast(); break; case "tsafogattog": TsafOgAttog(); break; case "superjump": SuperJump(); break; case "pmujrepus": PmujRepus(); break; case "timestop": TimeStop(); break; case "die": if (DateTime.Now - lastDieCommand > dieCommandTimeout && Die(userName)) { lastDieCommand = DateTime.Now; } break; case "win": if (DateTime.Now - lastWinCommand > winCommandTimeout && Win(userName)) { lastWinCommand = DateTime.Now; } break; case "grow": Grow(); break; case "shrink": Shrink(); break; case "bonus": if (split.Length > 1) { if (bonusDict.TryGetValue(split[1], out int val)) { Bonus(val); } else if (int.TryParse(split[1], out val)) { Bonus(val); } } else { Bonus(bonusDict.Values.ElementAt(RandomNumber(0, bonusDict.Count))); } break; case "music": if (split.Length > 1) { if (int.TryParse(split[1], out int mus) && mus >= 0 && mus < 157) { PlayMusic(mus); } } else { PlayMusic(RandomNumber(0, 157)); } break; case "highgravity": HighGravity(); break; case "lowgravity": LowGravity(); break; case "healboss": HealBoss(); break; case "confuse": Confuse(); break; case "earthquake": Earthquake(); break; case "chaokey": ToggleChaoKey(); break; case "water": ToggleWater(); break; case "level": if (split.Length > 1 && levelmap.TryGetValue(split[1], out LevelIDs lvl)) { votes[userName] = new Vote(StoryEntryType.Level, (short)(lvl & ~LevelIDs.Dark), lvl.HasFlag(LevelIDs.Dark)); TallyVotes(); } break; case "event": if (split.Length > 1 && short.TryParse(split[1], out short ev) && events.Contains(ev)) { if (!allowCredits && ev == 210) { break; } votes[userName] = new Vote(StoryEntryType.Event, ev); TallyVotes(); } break; case "credits": if (allowCredits) { votes[userName] = new Vote(StoryEntryType.Credits); TallyVotes(); } break; case "endstory": votes[userName] = new Vote(StoryEntryType.End); TallyVotes(); break; } if (AllowBuildHTMLPagesForOverlay) { DoBuildHTML(); } }
public void TestResultComputation() { Assert.IsNull(GetTestSurveyFromDb()); Survey s = CreateTestSurvey(); Survey s2 = CreateTestSurvey(); s2.Question += "2"; using (var db = new TestSurveyContext()) { db.Surveys.Add(s); db.Surveys.Add(s2); db.SaveChanges(); Vote v1 = new Vote(new User() { Code = "User1", Created = DateTime.Now }, s, s.Answers.ElementAt(0)); db.Votes.Add(v1); Vote v2 = new Vote(new User() { Code = "User2", Created = DateTime.Now }, s, s.Answers.ElementAt(2)); db.Votes.Add(v2); Vote v3 = new Vote(new User() { Code = "User3", Created = DateTime.Now }, s, s.Answers.ElementAt(0)); db.Votes.Add(v3); Vote v4 = new Vote(new User() { Code = "User3", Created = DateTime.Now }, s2, s2.Answers.ElementAt(0)); db.Votes.Add(v4); db.SaveChanges(); } using (var db = new TestSurveyContext()) { Result[] res = db.getResultsFor(s); Assert.IsNotNull(res); Assert.IsTrue(res.Length == 2); Assert.IsTrue(res[0].Answer.AnswerText == "Answer 1"); Assert.IsTrue(res[0].Count == 2); Assert.IsTrue(res[1].Answer.AnswerText == "Answer 3"); Assert.IsTrue(res[1].Count == 1); Vote[] votes = db.Votes.Where(v => v.Survey.Id == s.Id || v.Survey.Id == s2.Id).ToArray <Vote>(); foreach (Vote v in votes) { db.Votes.Remove(v); } db.SaveChanges(); } using (var db = new TestSurveyContext()) { db.Surveys.Attach(s); db.Surveys.Remove(s); db.Surveys.Attach(s2); db.Surveys.Remove(s2); db.SaveChanges(); } }
public static VoteCreated From(Vote obj) => new VoteCreated { Count = obj.Count, OptionName = obj.OptionName, SubjectId = obj.SubjectId };
public ActionResult AddPostKarma(int postId) { int userId = entities.Users.First(u => u.Username == HttpContext.User.Identity.Name).Id; if (!entities.Votes.Any(v => v.PostId == postId && v.UserId == userId)) { Post post = entities.Posts.First(p => p.Id == postId); post.Karma++; Vote vote = new Vote() { UserId = userId, PostId = postId, IsUpvote = true }; entities.Votes.Add(vote); entities.SaveChanges(); if (!entities.NotificationGroups.Any(n => n.EventType == (int)EventType.Karma && n.EventId == postId)) { entities.NotificationGroups.Add(new NotificationGroup() { EventType = (int)EventType.Karma, EventId = vote.Id, TargetId = entities.Posts.Find(postId).AuthorId, Seen = false }); } else { entities.NotificationGroups.First(n => n.EventType == (int)EventType.Karma && n.EventId == postId).Seen = false; } entities.SaveChanges(); entities.NotificationGroupMembers.Add(new NotificationGroupMember() { SourceId = entities.Users.First(u => u.Username == User.Identity.Name).Id, NotificationGroupId = entities.NotificationGroups.First(n => n.EventType == (int)EventType.Karma && n.EventId == vote.Id).Id, Date = DateTime.Now, }); entities.SaveChanges(); IEnumerable <NotificationGroup> groups = entities.NotificationGroups.Where(n => n.TargetId == post.User.Id && !n.Seen); if (groups.Count() > maxSeenNotificationsInDatabase) { IEnumerable <NotificationGroup> groupsToRemove = groups.Take(groups.Count() - maxSeenNotificationsInDatabase); foreach (NotificationGroup notGroup in groupsToRemove) { entities.NotificationGroupMembers.RemoveRange(notGroup.NotificationGroupMembers); } entities.SaveChanges(); entities.NotificationGroups.RemoveRange(groupsToRemove); } entities.SaveChanges(); } else if (entities.Votes.First(v => v.PostId == postId && v.UserId == userId).IsUpvote == false) { entities.Posts.First(p => p.Id == postId).Karma++; entities.Votes.Remove(entities.Votes.First(v => v.UserId == userId && v.PostId == postId)); entities.SaveChanges(); } else { entities.Posts.First(p => p.Id == postId).Karma--; entities.Votes.Remove(entities.Votes.First(v => v.UserId == userId && v.PostId == postId)); entities.SaveChanges(); } return(Content(entities.Posts.First(p => p.Id == postId).Karma.ToString(), "text")); }
public static async Task ClientOnMessageReactionAdded(DiscordClient client, MessageReactionAddEventArgs e) { var discordUser = await client.GetUserAsync(e.User.Id); if (discordUser.IsBot) { return; } //Проверка если сообщение с принятием правил сообщества if (e.Message.Id == Bot.BotSettings.CodexMessageId && e.Emoji.GetDiscordName() == ":white_check_mark:") { //При надобности добавить кулдаун /*if (EmojiCooldowns.ContainsKey(e.User)) // проверка на кулдаун * if ((EmojiCooldowns[e.User] - DateTime.Now).Seconds > 0) return; * * // если проверка успешно пройдена, добавим пользователя * // в словарь кулдаунов * EmojiCooldowns[e.User] = DateTime.Now.AddSeconds(Bot.BotSettings.FastCooldown);*/ //Проверка на purge var hasPurge = false; ReportSQL validPurge = null; foreach (var purge in ReportSQL.GetForUser(discordUser.Id, ReportType.CodexPurge)) { if (purge.ReportEnd > DateTime.Now) { validPurge = purge; hasPurge = true; break; } } if (hasPurge) { var moderator = await e.Channel.Guild.GetMemberAsync(validPurge.Moderator); try { await(await e.Guild.GetMemberAsync(discordUser.Id)).SendMessageAsync( "**Возможность принять правила заблокирована**\n" + $"**Снятие через:** {Utility.FormatTimespan(DateTime.Now - validPurge.ReportEnd)}\n" + $"**Модератор:** {moderator.Username}#{moderator.Discriminator}\n" + $"**Причина:** {validPurge.Reason}\n"); } catch (UnauthorizedException) { //user can block the bot } return; } //Выдаем роль правил var member = await e.Guild.GetMemberAsync(discordUser.Id); //Проверка времени входа на сервер. if (member.JoinedAt > DateTime.Now.AddMinutes(-10)) { try { await member.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Для принятия правил вы должны находиться на сервере минимум " + $"**{Utility.FormatTimespan(TimeSpan.FromMinutes(10))}**."); await e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"), member); } catch (UnauthorizedException) { } return; } if (!member.Roles.Contains(e.Channel.Guild.GetRole(Bot.BotSettings.CodexRole))) { //Выдаем роль правил await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.CodexRole)); //Убираем роль блокировки правил await member.RevokeRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.PurgeCodexRole)); client.Logger.LogInformation(BotLoggerEvents.Event, $"Пользователь {discordUser.Username}#{discordUser.Discriminator} ({discordUser.Id}) подтвердил прочтение правил через реакцию."); } return; } //Проверка если сообщение с принятием правил рейда if (e.Message.Id == Bot.BotSettings.FleetCodexMessageId && e.Emoji.GetDiscordName() == ":white_check_mark:") { //Проверка на purge var hasPurge = false; ReportSQL validPurge = null; foreach (var purge in ReportSQL.GetForUser(discordUser.Id, ReportType.FleetPurge)) { if (purge.ReportEnd > DateTime.Now) { validPurge = purge; hasPurge = true; break; } } if (hasPurge) { var moderator = await e.Channel.Guild.GetMemberAsync(validPurge.Moderator); try { await(await e.Guild.GetMemberAsync(discordUser.Id)).SendMessageAsync( "**Возможность принять правила заблокирована**\n" + $"**Снятие через:** {Utility.FormatTimespan(DateTime.Now - validPurge.ReportEnd)}\n" + $"**Модератор:** {moderator.Username}#{moderator.Discriminator}\n" + $"**Причина:** {validPurge.Reason}\n"); } catch (UnauthorizedException) { //user can block the bot } return; } //Удаляем блокировку если истекла var member = await e.Guild.GetMemberAsync(discordUser.Id); //Проверка времени входа на сервер. if (member.JoinedAt > DateTime.Now.AddDays(-Bot.BotSettings.FleetDateOffset)) { await member.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Для получения доступа к рейдам вы должны находиться на сервере " + $"**{Utility.FormatTimespan(TimeSpan.FromDays(Bot.BotSettings.FleetDateOffset))}**."); await e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"), member); return; } var voiceTime = VoiceListener.GetUpdatedVoiceTime(e.User.Id); //Проверка на время проведенное в голосовых каналах if (voiceTime < TimeSpan.FromHours(Bot.BotSettings.FleetVoiceTimeOffset)) { await member.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Для получения доступа к рейдам вы должны провести " + $"**{Utility.FormatTimespan(TimeSpan.FromHours(Bot.BotSettings.FleetVoiceTimeOffset))}** в голосовых каналах. " + $"Ваше время: **{Utility.FormatTimespan(voiceTime)}**"); await e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"), member); return; } //Проверка на регистрацию и привязку Xbox var webUser = WebUser.GetByDiscordId(member.Id); if (webUser == null) { await member.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Для получения доступа к рейдам вам нужно авторизоваться с помощью Discord на сайте {Bot.BotSettings.WebURL}login."); await e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"), member); return; } if (webUser.LastXbox == "") { await member.SendMessageAsync($"{Bot.BotSettings.ErrorEmoji} Для получения доступа к рейдам вы должны привязать Xbox к своему аккаунту, затем перейдите по ссылке " + $"{Bot.BotSettings.WebURL}xbox - это обновит базу данных."); await e.Message.DeleteReactionAsync(DiscordEmoji.FromName(client, ":white_check_mark:"), member); return; } // Проверка ЧС if (BlacklistEntry.IsBlacklisted(member.Id) || BlacklistEntry.IsBlacklistedXbox(webUser.LastXbox)) { await member.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Вы находитесь в чёрном списке рейдов и вам навсегда ограничен доступ к ним."); return; } //Выдаем роль правил рейда if (!member.Roles.Any(x => x.Id == Bot.BotSettings.FleetCodexRole)) { await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.FleetCodexRole)); await e.Guild.GetChannel(Bot.BotSettings.FleetLogChannel) .SendMessageAsync($"{DiscordEmoji.FromName(client, ":new:")} Пользователь **{e.User.Username}#{e.User.Discriminator}** ({e.User.Id}) получил роль рейда."); client.Logger.LogInformation(BotLoggerEvents.Event, $"Пользователь {discordUser.Username}#{discordUser.Discriminator} ({discordUser.Id}) подтвердил прочтение правил рейда."); } return; } //Проверка на сообщение эмиссарства if (e.Message.Id == Bot.BotSettings.EmissaryMessageId) { await e.Message.DeleteReactionAsync(e.Emoji, discordUser); if (EmojiCooldowns.ContainsKey(discordUser)) // проверка на кулдаун { if ((EmojiCooldowns[discordUser] - DateTime.Now).Seconds > 0) { return; } } // если проверка успешно пройдена, добавим пользователя // в словарь кулдаунов EmojiCooldowns[discordUser] = DateTime.Now.AddSeconds(Bot.BotSettings.FastCooldown); //Проверка у пользователя уже существующих ролей эмисарства и их удаление var member = await e.Guild.GetMemberAsync(discordUser.Id); member.Roles.Where(x => x.Id == Bot.BotSettings.EmissaryGoldhoadersRole || x.Id == Bot.BotSettings.EmissaryTradingCompanyRole || x.Id == Bot.BotSettings.EmissaryOrderOfSoulsRole || x.Id == Bot.BotSettings.EmissaryAthenaRole || x.Id == Bot.BotSettings.EmissaryReaperBonesRole || x.Id == Bot.BotSettings.HuntersRole || x.Id == Bot.BotSettings.ArenaRole).ToList() .ForEach(async x => await member.RevokeRoleAsync(x)); //Выдаем роль в зависимости от реакции switch (e.Emoji.GetDiscordName()) { case ":moneybag:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.EmissaryGoldhoadersRole)); break; case ":pig:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.EmissaryTradingCompanyRole)); break; case ":skeleton:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.EmissaryOrderOfSoulsRole)); break; case ":gem:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.EmissaryAthenaRole)); break; case ":skull_and_crossbones:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.EmissaryReaperBonesRole)); break; case ":fish:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.HuntersRole)); break; case ":crossed_swords:": await member.GrantRoleAsync(e.Channel.Guild.GetRole(Bot.BotSettings.ArenaRole)); break; default: break; } //Отправка в лог client.Logger.LogInformation(BotLoggerEvents.Event, $"{discordUser.Username}#{discordUser.Discriminator} получил новую роль эмиссарства."); return; } //Проверка на голосование if (e.Message.Channel.Id == Bot.BotSettings.VotesChannel) { var vote = Vote.GetByMessageId(e.Message.Id); await e.Message.DeleteReactionAsync(e.Emoji, discordUser); // Проверка на окончание голосования if (DateTime.Now > vote.End) { return; } // Проверка на предыдущий голос if (vote.Voters.ContainsKey(discordUser.Id)) { return; } if (e.Emoji.GetDiscordName() == ":white_check_mark:") { vote.Voters.Add(discordUser.Id, true); ++vote.Yes; } else { vote.Voters.Add(discordUser.Id, false); ++vote.No; } var total = vote.Voters.Count; var author = await e.Guild.GetMemberAsync(vote.Author); var embed = Utility.GenerateVoteEmbed( author, DiscordColor.Yellow, vote.Topic, vote.End, vote.Voters.Count, vote.Yes, vote.No, vote.Id); Vote.Save(Bot.BotSettings.VotesXML); await e.Message.ModifyAsync(embed : embed); await(await e.Guild.GetMemberAsync(discordUser.Id)).SendMessageAsync($"{Bot.BotSettings.OkEmoji} Спасибо, ваш голос учтён!"); } // Private ship confirmation message if (e.Channel.Id == Bot.BotSettings.PrivateRequestsChannel) { var ship = PrivateShip.GetByRequest(e.Message.Id); if (ship != null && ship.Channel == 0) { if (e.Emoji == DiscordEmoji.FromName(client, ":white_check_mark:")) { var channel = await e.Guild.CreateChannelAsync($"☠{ship.Name}☠", ChannelType.Voice, e.Guild.GetChannel(Bot.BotSettings.PrivateCategory), bitrate : Bot.BotSettings.Bitrate); await channel.AddOverwriteAsync(e.Guild.GetRole(Bot.BotSettings.CodexRole), Permissions.AccessChannels); await channel.AddOverwriteAsync(e.Guild.EveryoneRole, Permissions.None, Permissions.UseVoice); ship.Channel = channel.Id; ship.CreatedAt = DateTime.Now; ship.LastUsed = DateTime.Now; var captain = (from member in ship.GetMembers() where member.Role == PrivateShipMemberRole.Captain select member).First(); var captainMember = await e.Guild.GetMemberAsync(captain.MemberId); await channel.AddOverwriteAsync(captainMember, Permissions.UseVoice); captain.Status = true; await e.Channel.SendMessageAsync( $"{Bot.BotSettings.OkEmoji} Администратор {e.User.Mention} подтвердил запрос на создание " + $"корабля **{ship.Name}**."); try { await captainMember.SendMessageAsync( $"{Bot.BotSettings.OkEmoji} Администратор **{e.User.Username}#{e.User.Discriminator}** " + $"подтвердил твой запрос на создание корабля **{ship.Name}**."); } catch (UnauthorizedException) { } } else if (e.Emoji == DiscordEmoji.FromName(client, ":no_entry:")) { var captain = (from member in ship.GetMembers() where member.Role == PrivateShipMemberRole.Captain select member).First(); var captainMember = await e.Guild.GetMemberAsync(captain.MemberId); PrivateShip.Delete(ship.Name); await e.Channel.SendMessageAsync( $"{Bot.BotSettings.OkEmoji} Администратор {e.User.Mention} отклонил запрос на создание " + $"корабля **{ship.Name}**."); try { await captainMember.SendMessageAsync( $"{Bot.BotSettings.ErrorEmoji} Администратор **{e.User.Username}#{e.User.Discriminator}** " + $"отклонил твой запрос на создание корабля **{ship.Name}**."); } catch (UnauthorizedException) { } } await e.Message.DeleteAllReactionsAsync(); } } }
public StatsCompiler(Vote[] votes) { //sanatize votes for(int i = 0;i<votes.Length;i++) { Vote v=null; if (votes[i] != null) v = votes[i]; if (v == null || v.getPlayers() == null || v.getKilledVictims() == null || v.getSavedVictims() == null) //we got a bad vote { votes[i] = new Vote(new List<Victim>(), new List<Victim>(), -1, new PlayerClass[0]); } } //should be ok with abstains now.... Debug.Log ("number of votes received by the StatsCompiler is "+votes.Where (x => x != null).Count()); //Gender female = new Characteristic("female", "gender"); male = new Characteristic("male", "gender"); gender = new Characteristic[] { female, male }; //Animal cat = new Characteristic("cat", "animal"); dog = new Characteristic("dog", "animal"); chupacabra = new Characteristic("chupacabra", "animal"); deer = new Characteristic("deer", "animal"); spacecat = new Characteristic("space cat", "animal"); animal = new Characteristic[] { cat, dog, chupacabra, deer, spacecat }; //Race latinohispanic = new Characteristic ("latino/hispanic", "race"); chinese = new Characteristic ("chinese", "race"); filipino = new Characteristic("filipino", "race"); indian = new Characteristic("indian", "race"); vietnamese = new Characteristic("vietnamese", "race"); korean = new Characteristic("korean", "race"); japanese = new Characteristic("japanese" , "race"); arab = new Characteristic("arab", "race"); black = new Characteristic("black", "race"); white = new Characteristic("white", "race"); nativeamerican = new Characteristic("native american", "race"); race = new Characteristic[] { latinohispanic, chinese, filipino, indian, vietnamese, korean, japanese, arab, black, white, nativeamerican }; //Occupation author = new Characteristic("author", "occupation"); actor = new Characteristic("actor", "occupation"); arsonist = new Characteristic("arsonist", "occupation"); barista = new Characteristic("barista", "occupation"); commoncriminal = new Characteristic("common criminal", "occupation"); crazycathoarder = new Characteristic("crazy cat-hoarder", "occupation"); cattamer = new Characteristic("cat tamer", "occupation"); doctor = new Characteristic("doctor", "occupation"); dj = new Characteristic("DJ", "occupation"); debtcollector = new Characteristic("debt collector", "occupation"); faithhealer = new Characteristic("faith healer", "occupation"); fosterparent = new Characteristic("foster parent", "occupation"); gardener = new Characteristic("gardener", "occupation"); murder = new Characteristic("murderer", "occupation"); miner = new Characteristic("miner", "occupation"); musician = new Characteristic("musician", "occupation"); refugee = new Characteristic("refugee", "occupation"); roofer = new Characteristic("roofer", "occupation"); plumber = new Characteristic("plumber", "occupation"); pediatrician = new Characteristic("pediatrician", "occupation"); politician = new Characteristic("politician", "occupation"); pedophile = new Characteristic("pedophile", "occupation"); professor = new Characteristic("professor", "occupation"); policeofficer = new Characteristic("police officer", "occupation"); playboybunny = new Characteristic("playboy bunny", "occupation"); pimp = new Characteristic("pimp", "occupation"); prostitute = new Characteristic("prostitute", "occupation"); scientist = new Characteristic("scientist", "occupation"); stuntman = new Characteristic("stuntman", "occupation"); salesperson = new Characteristic("salesperson", "occupation"); stalker = new Characteristic("stalker", "occupation"); teacher = new Characteristic("teacher", "occupation"); trolleydriver = new Characteristic("trolley driver", "occupation"); tailor = new Characteristic("tailor", "occupation"); taxevader = new Characteristic("taxevader", "occupation"); preciousbaby = new Characteristic("precious baby", "occupation"); child = new Characteristic("child", "occupation"); angstyteenager = new Characteristic("angsty teenager", "occupation"); occupation = new Characteristic[] {author, actor, arsonist, barista, commoncriminal, crazycathoarder, cattamer, doctor, dj, debtcollector, faithhealer, fosterparent, gardener, murder, miner, musician, refugee, roofer, plumber, pediatrician, politician, pedophile, professor, policeofficer,playboybunny, pimp, prostitute, scientist, stuntman, stalker, teacher, trolleydriver, tailor, taxevader, preciousbaby, child, angstyteenager }; //Age zero = new Characteristic("0-9", "age"); ten = new Characteristic("10-19", "age"); twenty = new Characteristic("20-29", "age"); thirty = new Characteristic("30-39", "age"); fourty = new Characteristic("40-49", "age"); fifty = new Characteristic("50-59", "age"); sixty = new Characteristic("60-69", "age"); seventy = new Characteristic("70-79", "age"); eighty = new Characteristic("80-89", "age"); ninety = new Characteristic("90-100", "age"); age = new Characteristic[] { zero, ten, twenty, thirty, fourty, fifty, sixty, seventy, eighty, ninety }; //Affiliation PETA = new Characteristic("PETA", "affiliation"); AARP = new Characteristic("AARP", "affiliation"); NAACP = new Characteristic("NAACP", "affiliation"); ALG = new Characteristic("ALG", "affiliation"); CI = new Characteristic("CI", "affiliation"); EA = new Characteristic("EA", "affiliation"); NAS = new Characteristic("NAS", "affiliation"); FRAC = new Characteristic("FRAC", "affiliation"); NAMBLA = new Characteristic("NAMBLA", "affiliation"); affiliation = new Characteristic[] { PETA, AARP, NAACP, ALG, CI, EA, NAS, FRAC, NAMBLA }; update = new List<Characteristic>(); for (int i = 0; i < votes.Length; i++) { if (votes[i]!=null&&votes[i].getKilledVictims() != null && votes[i].getSavedVictims() != null) { killedVictims = votes[i].getKilledVictims().ToArray(); savedVictims = votes[i].getSavedVictims().ToArray(); //Since killedVictims and savedVictims are the same size //will go through them simultanously to save time for (int j = 0; j < killedVictims.Length; j++) { //Gender for (int k = 0; k < gender.Length; k++) { if (killedVictims[j].getGender() == gender[k].getType()) { gender[k].setKilled(); } if (savedVictims[k].getGender() == gender[k].getType()) { gender[k].setSaved(); } } //Age if (savedVictims[j].getIntAge() < 10) { zero.setSaved(); } else if (savedVictims[j].getIntAge() < 20) { ten.setSaved(); } else if (savedVictims[j].getIntAge() < 30) { twenty.setSaved(); } else if (savedVictims[j].getIntAge() < 40) { thirty.setSaved(); } else if (savedVictims[j].getIntAge() < 50) { fourty.setSaved(); } else if (savedVictims[j].getIntAge() < 60) { fifty.setSaved(); } else if (savedVictims[j].getIntAge() < 70) { sixty.setSaved(); } else if (savedVictims[j].getIntAge() < 80) { seventy.setSaved(); } else if (savedVictims[j].getIntAge() < 90) { eighty.setSaved(); } else { ninety.setSaved(); } if (killedVictims[j].getIntAge() < 10) { zero.setKilled(); } else if (killedVictims[j].getIntAge() < 20) { ten.setKilled(); } else if (killedVictims[j].getIntAge() < 30) { twenty.setKilled(); } else if (killedVictims[j].getIntAge() < 40) { thirty.setKilled(); } else if (killedVictims[j].getIntAge() < 50) { fourty.setKilled(); } else if (killedVictims[j].getIntAge() < 60) { fifty.setKilled(); } else if (killedVictims[j].getIntAge() < 70) { sixty.setKilled(); } else if (killedVictims[j].getIntAge() < 80) { seventy.setKilled(); } else if (killedVictims[j].getIntAge() < 90) { eighty.setKilled(); } else { ninety.setKilled(); } //Killed Animal if (!killedVictims[j].isPerson()) { for (int k = 0; k < animal.Length; k++) { if (killedVictims[j].getSpecies() == animal[k].getType()) { animal[k].setKilled(); } } } else { //Killed Race for (int k = 0; k < race.Length; k++) { if (killedVictims[j].getRace() == race[k].getType()) { race[k].setKilled(); } } //Killed Occupation for (int k = 0; k < occupation.Length; k++) { if (killedVictims[j].getOccupation() == occupation[k].getType()) { occupation[k].setKilled(); } } } //Saved Animal if (!savedVictims[j].isPerson()) { for (int k = 0; k < animal.Length; k++) { if (savedVictims[j].getSpecies() == animal[k].getType()) { animal[k].setSaved(); } } } else { //Saved Race for (int k = 0; k < race.Length; k++) { if (savedVictims[j].getRace() == race[k].getType()) { race[k].setSaved(); } } //Saved Occupation for (int k = 0; k < occupation.Length; k++) { if (savedVictims[j].getOccupation() == occupation[k].getType()) { occupation[k].setSaved(); } } } } } } for (int i =0; i<votes[0].getPlayers().Length; i++) { Debug.Log ("outer loop: "+i+" "+votes[0].ToString()+" "+votes[0].getPlayers().ToString()+" "+votes[0].getPlayers().Length); for (int j =0; j < affiliation.Length; j++) { Debug.Log ("inner loop: "+j+" "+affiliation[j].getType()+" "+votes[0].getPlayers()[i].ToString()+" "+votes[0].getPlayers()[i].getAffiliation()); if(votes[0].getPlayers()[i].getAffiliation() == affiliation[j].getType()) { for (int k =0; k < votes[0].getPlayers()[i].getVotesForAffiliation().Length; k++) { if (votes[0].getPlayers()[i].getVotesForAffiliation()[k] == 0) { affiliation[j].setSaved(); } else { affiliation[j].setKilled(); } } } } } for(int i =0; i < age.Length; i++) { if (age[i].getChanged()) { update.Add(age[i]); } } for (int i = 0; i < animal.Length; i++) { if (animal[i].getChanged()) { update.Add(animal[i]); } } for (int i = 0; i < gender.Length; i++) { if (gender[i].getChanged()) { update.Add(gender[i]); } } for (int i = 0; i < occupation.Length; i++) { if (occupation[i].getChanged()) { update.Add(occupation[i]); } } for (int i = 0; i < affiliation.Length; i++) { if (affiliation[i].getChanged()) { update.Add(affiliation[i]); } } for (int i = 0; i < race.Length; i++) { if (race[i].getChanged()) { update.Add(race[i]); } } }
public void SaveVote(Vote vote, bool force = false) { throw new NotImplementedException(); }
/// <summary> /// When user want to submit a link /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { //Check login again just in case user log out when in the page VL.Current.checkLogin(); //List of all selected categories CategoryCollection ListCatSelected = UcCategorySelectionList1.SelectedCategory; //Strip the # part of the url txtInputURL.Text = VL.ORM.Link.NormalizeURL(txtInputURL.Text); string LinkURL = txtInputURL.Text; string LinkTitle = txtInputTitle.Text; string LinkDesc = TxtInputDescription.Text; #region Check input error //Count how many error occured int ErrorCount = 0; //And list of all the warning message StringBuilder ErrorList; ErrorCount = VL.ORM.Link.ValidateInput(ListCatSelected, LinkURL, LinkTitle, out ErrorList, true); #endregion //If there's no error post it if (ErrorCount == 0) { int language = 0; if (radViet.Checked) { language = 1; } else if(radEng.Checked) { language = 2; } //Post new link up VL.ORM.Link newLink = VL.ORM.Link.PostLink(ListCatSelected, LinkURL, LinkTitle, LinkDesc, language); if (VL.Current.User.SecurityLevel > 4) { Vote thisVote = new Vote(Vote.Columns.LinkID, newLink.LinkID); thisVote.Point = ubConvert.ToInt(TxtVotePoint.Text, 1); thisVote.Save(); } string ThumbnailGuid = ""; if (newLink.IsImage) { SaveLink2Thumbnails(newLink); } else { ThumbnailGuid = PullThumbnails(newLink.Url); } // If found possible thumbnails, redirect to thumnails selection pages if (ThumbnailGuid.Length > 0) { Response.Redirect(VL.Config.GetConfigPath("GetThumbnailsPage") + "?ssid=" + ThumbnailGuid + "&linkid=" +newLink.LinkID.ToString()); } else { //If don't have any thumbnails, redirect to the link page then Response.Redirect(newLink.RewriteLink); } } else { //There is errors. Show them in the warning and do nothing divFailedWarning.InnerHtml = "<ul>"+ErrorList+"</ul>"; divFailedWarning.Style.Add("display", "block"); } }
public void DeleteVote(Vote vote) { throw new NotImplementedException(); }
public void receiveVoteFromPlayer(int choiceAsInt,PhotonMessageInfo info){//choice used to be PlayerClass.VoteChoice, but ~no sending enums through RPC~ if (isHost) { //Debug.Log(" received int "+choiceAsInt); PlayerClass.VoteChoice choice = intToVoteChoice(choiceAsInt); players[Array.IndexOf(playerNames, info.sender.name)].addToVotes(choice);//decision = choice; //Debug.Log("that vote had better match with its recorded " + players[Array.IndexOf(playerNames, info.sender.name)].getVotes()[currentRound]); //Debug.Log(players[Array.IndexOf(playerNames, info.sender.name)].getVotes().Select(x=>x.ToString()).Aggregate((c,n)=>c+","+ n)); votesReceived++; //Debug.Log("we the host have received " + info.sender.name + "'s vote of " + choice); if (votesReceived == numberOfPlayers) { //Debug.Log("the votes are " + players.Where(x => x != null).Select(x => x.getName() + ":" + x.getVotes()[currentRound]).Aggregate((c, n) => c + ", " + n)); votesReceived = 0; int numAVotes = players.Where(x => x != null).Where(x => x.getVotes()[currentRound] != PlayerClass.VoteChoice.A).Count(); int numBVotes = players.Where(x => x != null).Where(x => x.getVotes()[currentRound] != PlayerClass.VoteChoice.B).Count(); PlayerClass.VoteChoice majorityChoice = players.Where(x => x != null).GroupBy(p => p.getVotes()[currentRound]).OrderByDescending(pd => pd.Count())/*.Where(g => g.First().getVotes()[currentRound] != PlayerClass.VoteChoice.ABSTAIN)*/.First().Select(x => x.getVotes()[currentRound]).First(); //PlayerClass.VoteChoice majorityChoice = players.Where(x => x != null).GroupBy(p => p.getVotes()[currentRound]).OrderByDescending(pd => pd.Count()).Where(g => g.First().getVotes()[currentRound] != PlayerClass.VoteChoice.ABSTAIN).First().Select(x => x.getVotes()[currentRound]).First(); Debug.Log(majorityChoice.ToString() + " was the majority choice"); if (numAVotes == numBVotes || majorityChoice == PlayerClass.VoteChoice.ABSTAIN)//if we have a tie { if(victimGroupA.Count < 5)//if we can draw more cards, we will do so and reset everyone's timer. Since votesReceived was reset to 0, we will have to receive all new votes before trying again to end the round { photonView.RPC("draw2MoreCards", PhotonTargets.All); } else //we got through all 5 rounds without a majority non-abstain vote { foreach (PlayerClass player in players.Where(x => x != null))//punish each coward, send out new scores, and start the next round { player.addToScore(player.getVotes()[currentRound] == PlayerClass.VoteChoice.ABSTAIN ? -3 : 0); Debug.Log(player.getName() + "'s vote for round " + currentRound + " is " + player.getVotes()[currentRound]+ " which is, as an int, "+ voteChoiceToInt(player.getVotes()[currentRound])); photonView.RPC("receivePlayerScore", PhotonTargets.All, player.getName(), voteChoiceToInt(player.getVotes()[currentRound]), player.getScore()); player.nextRound();//update PlayerClass object to use right index with the next call of addToVotes() } if (currentRound < numberOfRounds - 1) //was not checking end condition here.....just needed to paste this logic block here.... photonView.RPC("startRound", PhotonTargets.All); else { //now let's add in each players affiliation points.... Debug.Log("hit upper end condition logic!"); foreach (PlayerClass player in players.Where(x => x != null)) { int totalAffil = 0; foreach (int j in player.getVotesForAffiliation()) { totalAffil += j; } player.addToScore(totalAffil); Debug.Log("adding " + totalAffil + " points for " + player.getName() + "'s affiliation actions"); photonView.RPC("receivePlayerScore", PhotonTargets.All, player.getName(), voteChoiceToInt(player.getVotes()[currentRound]), player.getScore()); } //end adding each players affiliation points... Debug.Log("ending game! GG EVERYBODY"); photonView.RPC("endGame", PhotonTargets.Others); Statistics temp = new Statistics(overallVotes);//takes years to do this\ StartCoroutine(waitABit(5.0F)); } } } else//we do not have a tie { List<Victim> doomedSouls = majorityChoice == PlayerClass.VoteChoice.A ? victimGroupA : victimGroupB; //PlayerClass.VoteChoice majorityChoice = numAVotes > numBVotes ? PlayerClass.VoteChoice.A : PlayerClass.VoteChoice.B; Debug.Log(majorityChoice.ToString()+" was the majority choice"); foreach (PlayerClass player in players.Where(x => x != null)) { //player.addToAffiliationVotes(doomedSouls.Select(v=>isAffiliationVictim(player.getAffiliation(), v)?2:0).Sum()); player.addToAffiliationVotes(doomedSouls.Any(v=>isAffiliationVictim(player.getAffiliation(), v))?2:0); Debug.Log("player's affiliation points for the round are " + player.getVotesForAffiliation()[currentRound]); player.addToScore(player.getVotes()[currentRound] == PlayerClass.VoteChoice.ABSTAIN ? -3 : player.getVotes()[currentRound] == majorityChoice ? 1 : -1); // player.addToScore(player.getVotesForAffiliation()[currentRound]); //either we can add per round....or at end... //Debug.Log(player.getName() + "'s vote for round " + currentRound + " is " + player.getVotes()[currentRound]+ " which is, as an int, "+ voteChoiceToInt(player.getVotes()[currentRound])); photonView.RPC("receiveAffil", PhotonTargets.All, player.getName(), player.getVotesForAffiliation()[currentRound]); photonView.RPC("receivePlayerScore", PhotonTargets.All, player.getName(), voteChoiceToInt(player.getVotes()[currentRound]), player.getScore()); player.nextRound();//update PlayerClass object to use right index with the next call of addToVotes() } overallVotes[currentRound] = new Vote((numAVotes>numBVotes?victimGroupA:victimGroupB), (numAVotes < numBVotes ? victimGroupA : victimGroupB), -1, players.Where(x=>x!=null).ToArray()); Debug.Log (overallVotes.Where (x => x != null).Count()); if (currentRound < numberOfRounds - 1) photonView.RPC("startRound", PhotonTargets.All); else { //now let's add in each players affiliation points.... foreach (PlayerClass player in players.Where(x => x != null)) { int totalAffil = 0; foreach(int j in player.getVotesForAffiliation()) { totalAffil += j; } player.addToScore(totalAffil); Debug.Log("adding " + totalAffil + " points for "+player.getName()+ "'s affiliation actions"); photonView.RPC("receivePlayerScore", PhotonTargets.All, player.getName(), voteChoiceToInt(player.getVotes()[currentRound]), player.getScore()); } //end adding each players affiliation points... Debug.Log("ending game! GG EVERYBODY"); photonView.RPC("endGame", PhotonTargets.Others); Statistics temp = new Statistics(overallVotes);//takes years to do this\ StartCoroutine(waitABit(5.0F)); } } } } }
/// <summary> /// Create a new PingRequestResponseListener that will listen for responses to Ping requests /// </summary> /// <param name="networkListener">The current networklistener</param> /// <param name="vote">The vote being worked on</param> public PingRequestResponseListener(NetworkListener networkListener, Vote vote) : this(networkListener, vote, 0) { //This constructor gives public access to this class without exposing the recursion counter }
public void Unsuccessful_Method() { Assert.Throws<ArgumentNullException>(() => IVoteExtensions.Unsuccessful<IVote>(null)); Assert.False(Enumerable.Empty<IVote>().Unsuccessful().Any()); var first = new Vote { Successful = true }; var second = new Vote { Successful = false }; var votes = new[] { null, first, second }; Assert.True(ReferenceEquals(second, votes.Unsuccessful().Single())); }
public void AddVote(Vote vote) { _context.Votes.Add(vote); }
public VoteBundle(Vote[] votes) { Votes = votes; }
public void FillTestData() { #region Categories Category categorie1 = new Category { Name = "philosophy" }; Category categorie2 = new Category { Name = "reduction" }; Category category3 = new Category { Name = "tree" }; InsertCategory(categorie1); InsertCategory(categorie2); InsertCategory(category3); #endregion #region Posts Post post1 = new Post { Title = "JCIDS", Description = "Maecenas pulvinar lobortis est. Phasellus sit amet erat. Nulla tempus. Vivamus in felis eu sapien cursus vestibulum. Proin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem. Duis aliquam convallis nunc.", DateCreated = new DateTime(2028, 01, 29, 09, 23, 28), BumpTime = new DateTime(2028, 01, 29, 09, 23, 28), CategoryId = 1, UserId = 1, IsDisabled = false }; Post post2 = new Post { Title = "ICD-9", Description = "Phasellus id sapien in sapien iaculis congue. Vivamus metus arcu, adipiscing molestie, hendrerit at, vulputate vitae, nisl. Aenean lectus.", DateCreated = new DateTime(2031, 10, 08, 17, 46, 54), BumpTime = new DateTime(2031, 10, 08, 17, 46, 54), CategoryId = 2, UserId = 2, IsDisabled = false }; Post post3 = new Post { Title = "Olfaction", Description = " Duis at velit eu est congue elementum. In hac habitasse platea dictumst.Morbi vestibulum, velit id pretium iaculis, diam erat fermentum justo, nec condimentum neque sapien placerat ante.Nulla justo. Aliquam quis turpis eget elit sodales scelerisque.Mauris sit amet eros. Suspendisse accumsan tortor quis turpis.", DateCreated = new DateTime(2022, 01, 07, 00, 14, 15), BumpTime = new DateTime(2022, 01, 07, 00, 14, 15), CategoryId = 2, UserId = 2, IsDisabled = false }; InsertPost(post1); InsertPost(post2); InsertPost(post3); #endregion #region PhysicalPosts PhysicalPost physicalPost1 = new PhysicalPost { Title = "Print On Demand ", Description = "Curabitur gravida nisi at nibh. In hac habitasse platea dictumst. Aliquam augue quam, sollicitudin vitae, consectetuer eget, rutrum at, lorem. Integer tincidunt ante vel ipsum.Praesent blandit lacinia erat. Vestibulum sed magna at nunc commodo placerat. Praesent blandit.", BumpTime = new DateTime(2025, 09, 26, 11, 56, 51), DateCreated = new DateTime(2025, 09, 26, 11, 56, 51), CategoryId = 1, UserId = 1, IsLocked = false, AltDescription = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin risus. Praesent lectus. Vestibulum quam sapien, varius ut, blandit non, interdum in, ante.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis. Duis consequat dui nec nisi volutpat eleifend.", Zipcode = "555", Address = "atvej 15" }; PhysicalPost physicalPost2 = new PhysicalPost { Title = "Crisis Communications", Description = "Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vivamus vestibulum sagittis sapien. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam vel augue.Vestibulum rutrum rutrum neque. Aenean auctor gravida sem. Praesent id massa id nisl venenatis lacinia.Aenean sit amet justo. Morbi ut odio.Cras mi pede, malesuada in, imperdiet et, commodo vulputate, justo.", BumpTime = new DateTime(2031, 07, 24, 12, 03, 12), DateCreated = new DateTime(2031, 07, 24, 12, 03, 12), CategoryId = 2, UserId = 2, IsLocked = false, AltDescription = "Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis. Duis consequat dui nec nisi volutpat eleifend. Donec ut dolor.Morbi vel lectus in quam fringilla rhoncus.Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis.", Zipcode = "704", Address = "atvej 15" }; PhysicalPost physicalPost3 = new PhysicalPost { Title = "Policy Writing", Description = "Quisque porta volutpat erat. Quisque erat eros, viverra eget, congue eget, semper rutrum, nulla. Nunc purus. Phasellus in felis.Donec semper sapien a libero.Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla.Sed accumsan felis.", BumpTime = new DateTime(2018, 02, 23, 17, 58, 50), DateCreated = new DateTime(2018, 02, 23, 17, 58, 50), CategoryId = 2, UserId = 2, IsLocked = false, AltDescription = "Vivamus in felis eu sapien cursus vestibulum. Proin eu mi. Nulla ac enim.", Zipcode = "705", Address = "lectusvej 456" }; InsertPost(physicalPost1); InsertPost(physicalPost2); InsertPost(physicalPost3); #endregion #region Reports Report report1 = new Report { Title = "massa tempor convallis nulla neque", Description = "Donec odio justo, sollicitudin ut, suscipit a, feugiat et, eros. Vestibulum ac est lacinia nisi venenatis tristique.", ReportType = "user", IsResolved = true, DateCreated = new DateTime(2019, 07, 24, 21, 48, 58), UserId = 1, CommentId = 0, PostId = 0 }; Report report2 = new Report { Title = "eget rutrum", Description = "Aenean fermentum.", ReportType = "post", IsResolved = true, DateCreated = new DateTime(2036, 12, 10, 15, 23, 35), UserId = 0, CommentId = 0, PostId = 1 }; Report report3 = new Report { Title = "ullamcorper augue a suscipit nulla", Description = "Duis mattis egestas metus. Aenean fermentum. Donec ut mauris eget massa tempor convallis. Nulla neque libero, convallis eget, eleifend luctus, ultricies eu, nibh. Quisque id justo sit amet sapien dignissim vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla dapibus dolor vel est. Donec odio justo, sollicitudin ut, suscipit a, feugiat et, eros. Vestibulum ac est lacinia nisi venenatis tristique. Fusce congue, diam id ornare imperdiet, sapien urna pretium nisl, ut volutpat sapien arcu sed augue. Aliquam erat volutpat.", ReportType = "comment", IsResolved = true, DateCreated = new DateTime(2030, 02, 07, 17, 12, 05), UserId = 0, CommentId = 1, PostId = 0 }; InsertReport(report1); InsertReport(report2); InsertReport(report3); #endregion #region Users User user1 = new User { Name = "Berte Chason", Email = "*****@*****.**", Username = "******", Password = "******", IsAdmin = false, DateCreated = new DateTime(2028, 06, 30, 15, 07, 52) }; User user2 = new User { Name = "Theo Rappaport", Email = "*****@*****.**", Username = "******", Password = "******", IsAdmin = false, DateCreated = new DateTime(2019, 03, 05, 05, 04, 03) }; User user3 = new User { Name = "Abbye Dovydenas", Email = "*****@*****.**", Username = "******", Password = "******", IsAdmin = false, DateCreated = new DateTime(2032, 11, 28, 10, 11, 12) }; InsertUser(user1); InsertUser(user2); InsertUser(user3); #endregion #region Comments Comment comment1 = new Comment { DateCreated = new DateTime(2036, 11, 09, 11, 21, 23), Text = "Donec quis orci eget orci vehicula condimentum. Curabitur in libero ut massa volutpat convallis.", UserId = 1, User = user1, Votes = new List <Vote>(), PostId = 1, CommentType = "Comment" }; Comment comment2 = new Comment { DateCreated = new DateTime(2027, 11, 20, 16, 49, 43), Text = "Vestibulum sed magna at nunc commodo placerat. Praesent blandit. Nam nulla. Integer pede justo, lacinia eget, tincidunt eget, tempus vel, pede. Morbi porttitor lorem id ligula.Suspendisse ornare consequat lectus. In est risus, auctor sed, tristique in, tempus sit amet, sem. Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa.Donec dapibus. Duis at velit eu est congue elementum.", UserId = 2, User = user2, Votes = new List <Vote>(), PostId = 2, CommentType = "Comment" }; Comment comment3 = new Comment { DateCreated = new DateTime(2024, 06, 26, 14, 25, 13), Text = "Mauris lacinia sapien quis libero.Nullam sit amet turpis elementum ligula vehicula consequat.Morbi a ipsum.Integer a nibh.In quis justo.Maecenas rhoncus aliquam lacus.Morbi quis tortor id nulla ultrices aliquet.Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo.Pellentesque viverra pede ac diam.Cras pellentesque volutpat dui.Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc.", UserId = 2, User = user3, Votes = new List <Vote>(), PostId = 2, CommentType = "Comment" }; InsertComment(comment1); InsertComment(comment2); InsertComment(comment3); #endregion #region SolvrComments SolvrComment solvrComment1 = new SolvrComment { DateCreated = new DateTime(2022, 05, 12, 21, 06, 16), Text = "Proin eu mi. Nulla ac enim.In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem.Duis aliquam convallis nunc. Proin at turpis a pede posuere nonummy.Integer non velit.Donec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque.", UserId = 1, PostId = 4, CommentType = "Solvr", TimeAccepted = new DateTime(2019, 06, 15, 15, 02, 42), IsAccepted = false, }; SolvrComment solvrComment2 = new SolvrComment { DateCreated = new DateTime(2033, 11, 28, 02, 54, 41), Text = "Phasellus in felis. Donec semper sapien a libero. Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla.Sed accumsan felis.Ut at dolor quis odio consequat varius.Integer ac leo.Pellentesque ultrices mattis odio. Donec vitae nisi.Nam ultrices, libero non mattis pulvinar, nulla pede ullamcorper augue, a suscipit nulla elit ac nulla.Sed vel enim sit amet nunc viverra dapibus. Nulla suscipit ligula in lacus.Curabitur at ipsum ac tellus semper interdum.", UserId = 2, PostId = 5, CommentType = "Solvr", TimeAccepted = new DateTime(2028, 09, 12, 01, 12, 42), IsAccepted = true }; SolvrComment solvrComment3 = new SolvrComment { DateCreated = new DateTime(2025, 02, 06, 17, 46, 02), Text = "Maecenas leo odio, condimentum id, luctus nec, molestie sed, justo.Pellentesque viverra pede ac diam.Cras pellentesque volutpat dui. Maecenas tristique, est et tempus semper, est quam pharetra magna, ac consequat metus sapien ut nunc.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Mauris viverra diam vitae quam.Suspendisse potenti. Nullam porttitor lacus at turpis.Donec posuere metus vitae ipsum.Aliquam non mauris.Morbi non lectus.Aliquam sit amet diam in magna bibendum imperdiet.", UserId = 2, PostId = 5, CommentType = "Solvr", TimeAccepted = new DateTime(2029, 04, 16, 22, 28, 53), IsAccepted = false }; InsertComment(solvrComment1); InsertComment(solvrComment2); InsertComment(solvrComment3); #endregion #region Vote Vote vote1 = new Vote { IsUpvoted = false, UserId = 1, CommentId = 1 }; Vote vote2 = new Vote { IsUpvoted = false, UserId = 2, CommentId = 2 }; Vote vote3 = new Vote { IsUpvoted = true, UserId = 2, CommentId = 2 }; InsertVote(vote1); InsertVote(vote2); InsertVote(vote3); #endregion }
public string PostVote(ReqVote objReq) { string rst = "0"; try { if (!string.IsNullOrWhiteSpace(objReq.postId)) { using (var db = new UnseentalentdbDataContext()) { Vote votedByUser = db.Votes.FirstOrDefault(x => x.UserId == Convert.ToInt64(objReq.userId) && x.VideoId == Convert.ToInt64(objReq.postId)); if (votedByUser == null) { var objNew = new Vote(); objNew.VideoId = Convert.ToInt64(objReq.postId); objNew.UserId = Convert.ToInt64(objReq.userId); objNew.IsVote = objReq.isLike == "True"; objNew.CreatedDate = DateTime.UtcNow; db.Votes.InsertOnSubmit(objNew); } else { votedByUser.IsVote = objReq.isLike == "True"; votedByUser.CreatedDate = DateTime.UtcNow; } db.SubmitChanges(); rst = "1"; } } } catch { } return rst; }
private Vote InsertVote(Vote vote) { return(MockDBContainer.Instance.AddVote(vote)); }