editing games works via the edit quote form

This commit is contained in:
tmont 2011-02-23 09:19:32 +00:00
parent d159a91208
commit 6b41bd609e
17 changed files with 247 additions and 69 deletions

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Iesi.Collections.Generic;
using JetBrains.Annotations;
@ -14,14 +15,16 @@ namespace VideoGameQuotes.Api {
Created = DateTime.UtcNow;
}
[CanBeNull]
public virtual string Website { get; set; }
public virtual User Creator { get; set; }
public virtual DateTime Created { get; set; }
public virtual IEnumerable<GamingSystem> Systems { get { return systems; } }
[Required]
public virtual string Name { get; set; }
public virtual IEnumerable<Publisher> Publishers { get { return publishers; } }
[CanBeNull]
public virtual byte[] Screenshot { get; set; }
[CanBeNull, StringLength(1024)]
public virtual byte[] Icon { get; set; }
public virtual Region Region { get; set; }
#region adding and removing stuff
@ -51,7 +54,7 @@ namespace VideoGameQuotes.Api {
Created = Created,
Systems = Systems.Select(system => system.ToDto()),
Name = Name,
Region = Region,
Regions = Region.ToString().Split(',').Select(region => region.Trim()),
Publishers = Publishers.Select(publisher => publisher.ToDto())
};
}
@ -86,6 +89,6 @@ namespace VideoGameQuotes.Api {
public IEnumerable<SystemDto> Systems { get; set; }
public string Name { get; set; }
public IEnumerable<PublisherDto> Publishers { get; set; }
public Region Region { get; set; }
public IEnumerable<string> Regions { get; set; }
}
}

View File

@ -8,7 +8,7 @@
<property name="Name" column="game_name" not-null="true" length="255"/>
<property name="Website" column="website" not-null="false" length="255"/>
<property name="Created" column="created" not-null="true" />
<property name="Screenshot" column="screenshot" not-null="false" length="10240" />
<property name="Icon" column="icon" not-null="false" length="1024" />
<property name="Region" column="game_region" not-null="true" />
<many-to-one name="Creator" column="creator" not-null="true" foreign-key="fk_game_user"/>

View File

@ -9,10 +9,14 @@
<property name="Text" column="quote_text" not-null="true" type="string" length="1024"/>
<property name="Created" column="created" not-null="true" type="DateTime" />
<property name="Modified" column="modified" not-null="false" type="DateTime" />
<many-to-one name="Creator" column="creator" not-null="true" foreign-key="fk_quote_user"/>
<many-to-one name="Game" column="game_id" not-null="true" foreign-key="fk_quote_game" />
<many-to-one name="Game" column="game_id" not-null="true" foreign-key="fk_quote_game" fetch="join" />
<!-- denormalization for performance purposes -->
<property name="Score" column="score" not-null="false" index="idx_score_upvotes" />
<property name="UpVotes" column="upvotes" not-null="false" index="idx_score_upvotes" />
<property name="DownVotes" column="downvotes" not-null="false" />
<set access="nosetter.camelcase" name="Categories" table="quote_category_map">
<key column="quote_id" />
<many-to-many class="VideoGameQuotes.Api.Category" column="category_id" />

View File

@ -65,6 +65,12 @@ namespace VideoGameQuotes.Api {
}
votes.Remove(currentVote);
if (currentVote.Direction == VoteDirection.Up) {
UpVotes--;
} else {
DownVotes--;
}
currentVote.Direction = direction;
currentVote.Created = DateTime.UtcNow;
votes.Add(currentVote);
@ -72,6 +78,14 @@ namespace VideoGameQuotes.Api {
votes.Add(new Vote { Direction = direction, Quote = this, Voter = user });
}
if (direction == VoteDirection.Up) {
UpVotes++;
} else {
DownVotes++;
}
Score = UpVotes - DownVotes;
return this;
}
@ -84,9 +98,9 @@ namespace VideoGameQuotes.Api {
return vote.Direction;
}
public virtual int UpVotes { get { return Votes.Count(vote => vote.Direction == VoteDirection.Up); } }
public virtual int DownVotes { get { return Votes.Count(vote => vote.Direction == VoteDirection.Down); } }
public virtual int Score { get { return Votes.Sum(vote => (int)vote); } }
public virtual int UpVotes { get; private set; }
public virtual int DownVotes { get; private set; }
public virtual int Score { get; private set; }
public virtual QuoteDto ToDto() {
return new QuoteDto {

View File

@ -1,7 +1,13 @@
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Portoa.Persistence;
using Portoa.Util;
using Portoa.Web;
using Portoa.Web.Controllers;
using Portoa.Web.Results;
using VideoGameQuotes.Api;
using VideoGameQuotes.Web.Models;
using VideoGameQuotes.Web.Security;
@ -17,8 +23,32 @@ namespace VideoGameQuotes.Web.Controllers {
this.userProvider = userProvider;
}
[HttpPost, VerifyUser(Group = UserGroup.Admin)]
public JsonResult Edit(EditGameModel model) {
if (model.GameId < 1) {
ModelState.AddModelError("GameId", "Invalid game ID");
}
if (!ModelState.IsValid) {
return Json(this.CreateJsonErrorResponse("Some errors occurred"));
}
var game = gameService.FindById(model.GameId);
game.Name = model.GameName;
game.Region = model.GameRegions;
game.Website = model.GameWebsite;
game.ClearPublishers();
game.ClearSystems();
(model.PublisherIds ?? Enumerable.Empty<int>()).Walk(id => game.AddPublisher(new Publisher { Id = id }));
(model.SystemIds ?? Enumerable.Empty<int>()).Walk(id => game.AddSystem(new GamingSystem { Id = id }));
game = gameService.Save(game);
return Json(this.CreateJsonResponse(data: game.ToDto()));
}
[HttpPost, VerifyUser]
public ActionResult Create(CreateGameModel model) {
public JsonResult Create(EditGameModel model) {
if (!ModelState.IsValid) {
return Json(this.CreateJsonErrorResponse("Some errors occurred."));
}

View File

@ -60,15 +60,12 @@ namespace VideoGameQuotes.Web.Controllers {
}
try {
var vote = quoteService.GetVoteOrCreateNew(quoteService.GetQuote(model.QuoteId), currentUserProvider.CurrentUser);
vote.Direction = model.Direction;
var quote = quoteService.SaveQuote(quoteService.GetQuote(model.QuoteId).VoteFor(currentUserProvider.CurrentUser, model.Direction));
vote = quoteService.SaveVote(vote);
var data = new Dictionary<string, string> {
{ "netVotes", vote.Quote.Score.ToString() },
{ "upVotes", vote.Quote.UpVotes.ToString() },
{ "downVotes", vote.Quote.DownVotes.ToString() }
var data = new {
score = quote.Score,
upVotes = quote.UpVotes,
downVotes = quote.DownVotes
};
return Json(this.CreateJsonResponse(null, data));
@ -135,6 +132,10 @@ namespace VideoGameQuotes.Web.Controllers {
[HttpGet, VerifyUser(Group = UserGroup.Admin)]
public ActionResult Edit(int id) {
if (id < 1) {
return View("QuoteNotFound");
}
try {
var model = new EditQuoteModel(quoteService.GetQuote(id));
ResetEditQuoteModel(model);
@ -198,6 +199,7 @@ namespace VideoGameQuotes.Web.Controllers {
}
private void ResetEditQuoteModel(EditQuoteModel model) {
model.CurrentUser = currentUserProvider.CurrentUser;
model.AllGames = quoteService.GetAllGames().OrderBy(game => game.Name);
model.AllSystems = quoteService.GetAllSystems().OrderBy(system => system.ReleaseDate);
model.AllPublishers = quoteService.GetAllPublishers().OrderBy(publisher => publisher.Name);

View File

@ -71,7 +71,7 @@ namespace VideoGameQuotes.Web {
//bullshit route so that RenderAction works
routes.MapRoute("mainmenu", "home/mainmenu", new { controller = "Home", action = "MainMenu" });
routes.MapRoute("crud-default", "{controller}/{action}", null, new { controller = "system|publisher|game", action = "create" });
routes.MapRoute("crud-default", "{controller}/{action}", null, new { controller = "system|publisher|game", action = "create|edit" });
routes.MapRoute("users-paged", "admin/users/{start}-{end}", new { controller = "Admin", action = "Users" }, new { start = @"\d+", end = @"\d+" });
routes.MapRoute("admin", "admin/{action}", new { controller = "Admin", action = "Index" }, new { action = "users|create|flags|password" });

View File

@ -1,10 +1,11 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using VideoGameQuotes.Api;
namespace VideoGameQuotes.Web.Models {
public class CreateGameModel {
public CreateGameModel() {
public class EditGameModel {
public EditGameModel() {
GameRegions = Region.Unknown;
}
@ -15,5 +16,7 @@ namespace VideoGameQuotes.Web.Models {
public List<int> PublisherIds { get; set; }
[Required(ErrorMessage = "At least one system must be specified, uglyface")]
public List<int> SystemIds { get; set; }
public HttpPostedFileBase GameIcon { get; set; }
public int GameId { get; set; }
}
}

View File

@ -24,6 +24,8 @@ namespace VideoGameQuotes.Web.Models {
ActionName = "Edit";
}
public User CurrentUser { get; set; }
public string ActionName { get; set; }
public string ControllerName { get; set; }

View File

@ -9,6 +9,7 @@ namespace VideoGameQuotes.Web.Services {
[CanBeNull]
Game FindByNameAndSystems(string name, IEnumerable<int> systemIds);
Game Save(Game game);
Game FindById(int id);
}
public class GameService : IGameService {
@ -29,5 +30,10 @@ namespace VideoGameQuotes.Web.Services {
public Game Save(Game game) {
return repository.Save(game);
}
[UnitOfWork]
public Game FindById(int id) {
return repository.FindById(id);
}
}
}

View File

@ -35,6 +35,7 @@ namespace VideoGameQuotes.Web.Services {
private readonly IRepository<Publisher> publisherRepository;
private readonly IRepository<Category> categoryRepository;
private readonly IRepository<Vote> voteRepository;
private static readonly Random random = new Random();
public QuoteService(
IRepository<Quote> quoteRepository,
@ -117,25 +118,29 @@ namespace VideoGameQuotes.Web.Services {
[UnitOfWork]
public Quote GetRandomQuote() {
var quotes = quoteRepository.Records.ToArray();
if (quotes.Length == 0) {
var length = quoteRepository.Records.Count();
if (length == 0) {
return null;
}
return quotes[new Random().Next(quotes.Length)];
return quoteRepository
.Records
.Skip(random.Next(length))
.Take(1)
.Single();
}
[UnitOfWork]
public IEnumerable<Quote> GetBestQuotes(int start, int end, out int totalCount) {
//TODO this does a select * on all quotes, which is kind of bad
var records = quoteRepository.Records.ToArray();
totalCount = records.Length;
return records
var records = quoteRepository.Records
.OrderByDescending(quote => quote.Score)
.ThenByDescending(quote => quote.UpVotes)
.Skip(start - 1)
.Take(end - start + 1);
totalCount = quoteRepository.Records.Count();
return records;
}
[UnitOfWork]

View File

@ -90,7 +90,7 @@
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\PublisherController.cs" />
<Compile Include="Controllers\SystemController.cs" />
<Compile Include="Models\CreateGameModel.cs" />
<Compile Include="Models\EditGameModel.cs" />
<Compile Include="Models\CreatePublisherModel.cs" />
<Compile Include="Services\GameService.cs" />
<Compile Include="Services\PublisherService.cs" />

View File

@ -1,5 +1,6 @@
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<VideoGameQuotes.Web.Models.EditQuoteModel>" %>
<%@ Import Namespace="Portoa.Web.Util" %>
<%@ Import Namespace="VideoGameQuotes.Api" %>
<div id="edit-quote-form">
<% using (Html.BeginForm(Model.ActionName, Model.ControllerName)) { %>
@ -10,12 +11,17 @@
<br />
<%= Html.DropDownListFor(model => model.GameId, Model.GetGameList()) %>
<a href="#" id="create-game-link" class="create-new-link">Create new game</a>
<a href="#" id="create-game-link" class="create-new-link" title="create new game"></a>
<% if (Model.CurrentUser != null && Model.CurrentUser.Group >= UserGroup.Admin) { %>
<a href="#" id="edit-game-link" class="edit-link" title="edit currently selected game"></a>
<% } %>
</p>
<div id="create-game-form">
<div id="create-game-form" class="subform">
<input type="hidden" value="0" class="edit-mode" />
<fieldset>
<legend>Create new game</legend>
<p class="error-message"></p>
<p>
@ -43,7 +49,8 @@
<a href="#" id="create-system-link" class="create-new-link">Create new system&hellip;</a>
</div>
<div id="create-system-form">
<div id="create-system-form" class="subform">
<input type="hidden" value="0" class="edit-mode" />
<fieldset>
<legend>Create new system</legend>
@ -79,7 +86,8 @@
<a href="#" id="create-publisher-link" class="create-new-link">Create new publisher</a>
</div>
<div id="create-publisher-form">
<div id="create-publisher-form" class="subform">
<input type="hidden" value="0" class="edit-mode" />
<fieldset>
<legend>Create new publisher</legend>

View File

@ -152,10 +152,18 @@ ul.menu {
width: 500px;
height: 120px;
}
.create-new-link, .edit-link, .loading-link {
padding-left: 16px;
}
.create-new-link {
padding-left: 20px;
background: transparent url(/media/images/add.png) left center no-repeat;
}
.edit-link {
background: transparent url(/media/images/pencil.png) left center no-repeat;
}
.loading-link {
background: transparent url(/media/images/loading.gif) left center no-repeat;
}
#browse-default-menu li {
margin-bottom: 2px;

View File

@ -42,18 +42,53 @@
.hide();
};
$.vgquotes = {
refresh: function() { },
ajaxErrorHandler: function(xhr) {
alert("An error occurred (" + xhr.statusCode + ")");
},
preload: function(images) {
//MM_preloadImages(lulz)
$.each(images, function() {
$('<img/>')[0].src = this;
$.vgquotes = function() {
var callApi = function(url, type, data, callback) {
$.ajax(url, {
type: type,
data: data,
success: callback,
error: callback
});
}
};
};
var cache = {
games: { }
};
return {
refresh: function() { },
ajaxErrorHandler: function(xhr) {
console.dir(xhr);
alert("An error occurred (" + xhr.statusCode + ")");
},
preload: function(images) {
//MM_preloadImages(lulz)
$.each(images, function() {
$('<img/>')[0].src = this;
});
},
loadingGif: "/media/images/loading.gif",
editIcon: "/media/images/pencil.png",
getGame: function(id, callback) {
id = id.toString();
// if (typeof(cache.games[id]) !== "undefined") {
// callback.call(null, cache.games[id]);
// return;
// }
callApi("/api/game/" + id, "GET", null, function(data) {
if (typeof(data) === "undefined" || typeof(data.Error) === "undefined" || data.Error !== null) {
callback.call(null, null);
return;
}
cache.games[id] = data.Data.games[0];
callback.call(null, cache.games[id]);
});
}
};
}();
(function(){
var refreshCookie = "vgquotes.refreshFragment";
@ -106,10 +141,6 @@
var setupVoting = function() {
var voting = false;
var loadingGif = "/media/images/loading.gif";
$.vgquotes.preload([loadingGif]);
$(".vote-for, .vote-against").live("click", function() {
if (voting) {
alert("Please wait for the current vote to process before voting again");
@ -128,7 +159,7 @@
type: "POST",
data: { QuoteId: quoteId, Direction: direction },
beforeSend: function() {
$score.empty().append($("<img/>").attr({ src: loadingGif, title: "submitting your vote" + String.fromCharCode(0x2026) }));
$score.empty().append($("<img/>").attr({ src: $.vgquotes.loadingGif, title: "submitting your vote" + String.fromCharCode(0x2026) }));
},
success: function(data, status, $xhr) {
if (data.Error !== null) {
@ -136,7 +167,7 @@
return;
}
score = data.Data.netVotes;
score = data.Data.score;
$score.attr("title", "+" + data.Data.upVotes + ", -" + data.Data.downVotes);
//remove the voting arrow, and add the other one if needed
@ -284,7 +315,13 @@
var setupQuoteForm = function() {
var toggleFormAndLink = function(type) {
return function() {
$("#create-" + type + "-form").toggle();
$("#create-" + type + "-form")
.find("input[type='text']").val("").end()
.find("input[type='checkbox']").removeAttr("checked").end()
.find("> .edit-mode").val(0).end()
.find("> legend").text("Create new " + type).end()
.toggle();
$("#" + type + "-select").toggle();
return false;
}
@ -361,7 +398,14 @@
$("input:checked[name='PublisherIds']").each(function(index, input) { if (typeof(data.PublisherIds) === "undefined") { data.PublisherIds = []; } data.PublisherIds.push(input.value); });
var $container = $("#create-game-form");
$.ajax("/game/create", {
var url = "/game/create";
var submittingAnEdit = $("#create-game-form > .edit-mode").val() == 1;
if (submittingAnEdit) {
url = "/game/edit";
data.GameId = $("#GameId").val();
}
$.ajax(url, {
type: "POST",
data: data,
traditional: true,
@ -372,9 +416,13 @@
return;
}
$("#GameId")
.append($("<option/>").attr({ value: data.Data.Id}).text(data.Data.Name))
.val(data.Data.Id);
if (!submittingAnEdit) {
$("#GameId")
.append($("<option/>").attr({ value: data.Data.Id}).text(data.Data.Name))
.val(data.Data.Id);
} else {
$("#GameId option[value='" + data.Data.Id + "']").text(data.Data.Name); //make sure the new name is up to date
}
toggleFormAndLink("game")();
}
@ -469,6 +517,38 @@
return false;
});
$("#edit-game-link").click(function() {
$("#edit-game-link").toggleClass("edit-link loading-link");
var gameId = $("#GameId").val();
$.vgquotes.getGame(gameId, function(game) {
if (game === null) {
alert("Unable to fetch game " + id);
return;
}
$("#edit-game-link").toggleClass("edit-link loading-link");
toggleFormAndLink("game")();
$("#create-game-form > .edit-mode").val(1);
$("#create-game-form > legend").text("Edit Game");
//populate game form with game data
$("#GameName").val(game.Name);
$("#GameWebsite").val(game.Website);
$.each(game.Regions, function() {
$("input[name='GameRegions'][value='" + this + "']").attr("checked", "checked");
});
$.each(game.Systems, function() {
$("input[name='SystemIds'][value='" + this.Id + "']").attr("checked", "checked");
});
$.each(game.Publishers, function() {
$("input[name='PublisherIds'][value='" + this.Id + "']").attr("checked", "checked");
});
});
return false;
});
};
(function(){
@ -476,6 +556,7 @@
setupSearch();
$(document).ready(function() {
$.vgquotes.preload([$.vgquotes.loadingGif]);
setupReportLink();
setupVoting();

View File

@ -116,11 +116,15 @@ namespace VideoGameQuotes.Api.Tests.NHibernate {
#region categories
var engrish = new Category { Name = "Engrish" };
var danger = new Category { Name = "Danger" };
var smoke = new Category { Name = "Smoke" };
var dolphins = new Category { Name = "Dolphins" };
using (var tx = session.BeginTransaction()) {
var repo = new NHibernateRepository<Category>(session);
repo.Save(engrish);
repo.Save(danger);
repo.Save(smoke);
repo.Save(dolphins);
tx.Commit();
}
#endregion
@ -157,23 +161,26 @@ namespace VideoGameQuotes.Api.Tests.NHibernate {
#endregion
#region quotes
var allYourBase = new Quote { Creator = creator, Game = zeroWing, Text = "All your base are belong to us" }
var allYourBase = new Quote { Creator = creator, Game = zeroWing, Text = "All your base are belong to us." }
.AddCategory(engrish)
.VoteFor(creator, VoteDirection.Up);
var dangerousToGoAlone = new Quote { Creator = creator, Game = loz, Text = "It is dangerous to go alone." }
var dangerousToGoAlone = new Quote { Creator = creator, Game = loz, Text = "It's dangerous to go alone! Take this." }
.AddCategory(danger)
.VoteFor(creator, VoteDirection.Up);
var dodongo = new Quote { Creator = creator, Game = loz, Text = "Dodongo dislikes smoke." }
.AddCategory(smoke);
var hopOnMyBack = new Quote { Creator = creator, Game = crystalis, Text = "Please hop on my back. I'll take you wherever you like." }
.AddCategory(new Category { Name = "Dolphins" })
.VoteFor(creator, VoteDirection.Up);
.AddCategory(dolphins);
using (var tx = session.BeginTransaction()) {
var repo = new NHibernateRepository<Quote>(session);
repo.Save(allYourBase);
repo.Save(dangerousToGoAlone);
repo.Save(hopOnMyBack);
repo.Save(dodongo);
tx.Commit();
}
#endregion

View File

@ -32,7 +32,7 @@ alter table quote_flag drop foreign key fk_flag_user
;
alter table quote_flag drop foreign key fk_quote_flag
alter table quote_flag drop foreign key fk_flag_quote
;
@ -87,7 +87,7 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
game_name VARCHAR(255) not null,
website VARCHAR(255),
created DATETIME not null,
screenshot BLOB,
icon BLOB,
game_region INTEGER not null,
creator INTEGER not null,
primary key (game_id)
@ -148,6 +148,9 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
modified DATETIME,
creator INTEGER not null,
game_id INTEGER not null,
score INTEGER,
upvotes INTEGER,
downvotes INTEGER,
primary key (quote_id)
);
@ -159,8 +162,8 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
create table system (
system_id INTEGER NOT NULL AUTO_INCREMENT,
system_name VARCHAR(255) not null,
system_abbreviation VARCHAR(12),
system_name VARCHAR(255) not null unique,
system_abbreviation VARCHAR(12) unique,
created DATETIME not null,
release_date DATETIME,
primary key (system_id)
@ -216,10 +219,12 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
alter table quote_flag
add index (quote_id),
add constraint fk_quote_flag
add constraint fk_flag_quote
foreign key (quote_id)
references game_quote (quote_id);
create index idx_score_upvotes on game_quote (score, upvotes);
alter table game_quote
add index (creator),
add constraint fk_quote_user