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;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq; using System.Linq;
using Iesi.Collections.Generic; using Iesi.Collections.Generic;
using JetBrains.Annotations; using JetBrains.Annotations;
@ -14,14 +15,16 @@ namespace VideoGameQuotes.Api {
Created = DateTime.UtcNow; Created = DateTime.UtcNow;
} }
[CanBeNull]
public virtual string Website { get; set; } public virtual string Website { get; set; }
public virtual User Creator { get; set; } public virtual User Creator { get; set; }
public virtual DateTime Created { get; set; } public virtual DateTime Created { get; set; }
public virtual IEnumerable<GamingSystem> Systems { get { return systems; } } public virtual IEnumerable<GamingSystem> Systems { get { return systems; } }
[Required]
public virtual string Name { get; set; } public virtual string Name { get; set; }
public virtual IEnumerable<Publisher> Publishers { get { return publishers; } } public virtual IEnumerable<Publisher> Publishers { get { return publishers; } }
[CanBeNull] [CanBeNull, StringLength(1024)]
public virtual byte[] Screenshot { get; set; } public virtual byte[] Icon { get; set; }
public virtual Region Region { get; set; } public virtual Region Region { get; set; }
#region adding and removing stuff #region adding and removing stuff
@ -51,7 +54,7 @@ namespace VideoGameQuotes.Api {
Created = Created, Created = Created,
Systems = Systems.Select(system => system.ToDto()), Systems = Systems.Select(system => system.ToDto()),
Name = Name, Name = Name,
Region = Region, Regions = Region.ToString().Split(',').Select(region => region.Trim()),
Publishers = Publishers.Select(publisher => publisher.ToDto()) Publishers = Publishers.Select(publisher => publisher.ToDto())
}; };
} }
@ -86,6 +89,6 @@ namespace VideoGameQuotes.Api {
public IEnumerable<SystemDto> Systems { get; set; } public IEnumerable<SystemDto> Systems { get; set; }
public string Name { get; set; } public string Name { get; set; }
public IEnumerable<PublisherDto> Publishers { 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="Name" column="game_name" not-null="true" length="255"/>
<property name="Website" column="website" not-null="false" length="255"/> <property name="Website" column="website" not-null="false" length="255"/>
<property name="Created" column="created" not-null="true" /> <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" /> <property name="Region" column="game_region" not-null="true" />
<many-to-one name="Creator" column="creator" not-null="true" foreign-key="fk_game_user"/> <many-to-one name="Creator" column="creator" not-null="true" foreign-key="fk_game_user"/>

View File

@ -9,9 +9,13 @@
<property name="Text" column="quote_text" not-null="true" type="string" length="1024"/> <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="Created" column="created" not-null="true" type="DateTime" />
<property name="Modified" column="modified" not-null="false" 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="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"> <set access="nosetter.camelcase" name="Categories" table="quote_category_map">
<key column="quote_id" /> <key column="quote_id" />

View File

@ -65,6 +65,12 @@ namespace VideoGameQuotes.Api {
} }
votes.Remove(currentVote); votes.Remove(currentVote);
if (currentVote.Direction == VoteDirection.Up) {
UpVotes--;
} else {
DownVotes--;
}
currentVote.Direction = direction; currentVote.Direction = direction;
currentVote.Created = DateTime.UtcNow; currentVote.Created = DateTime.UtcNow;
votes.Add(currentVote); votes.Add(currentVote);
@ -72,6 +78,14 @@ namespace VideoGameQuotes.Api {
votes.Add(new Vote { Direction = direction, Quote = this, Voter = user }); votes.Add(new Vote { Direction = direction, Quote = this, Voter = user });
} }
if (direction == VoteDirection.Up) {
UpVotes++;
} else {
DownVotes++;
}
Score = UpVotes - DownVotes;
return this; return this;
} }
@ -84,9 +98,9 @@ namespace VideoGameQuotes.Api {
return vote.Direction; return vote.Direction;
} }
public virtual int UpVotes { get { return Votes.Count(vote => vote.Direction == VoteDirection.Up); } } public virtual int UpVotes { get; private set; }
public virtual int DownVotes { get { return Votes.Count(vote => vote.Direction == VoteDirection.Down); } } public virtual int DownVotes { get; private set; }
public virtual int Score { get { return Votes.Sum(vote => (int)vote); } } public virtual int Score { get; private set; }
public virtual QuoteDto ToDto() { public virtual QuoteDto ToDto() {
return new QuoteDto { 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.Util;
using Portoa.Web; using Portoa.Web;
using Portoa.Web.Controllers; using Portoa.Web.Controllers;
using Portoa.Web.Results;
using VideoGameQuotes.Api; using VideoGameQuotes.Api;
using VideoGameQuotes.Web.Models; using VideoGameQuotes.Web.Models;
using VideoGameQuotes.Web.Security; using VideoGameQuotes.Web.Security;
@ -17,8 +23,32 @@ namespace VideoGameQuotes.Web.Controllers {
this.userProvider = userProvider; 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] [HttpPost, VerifyUser]
public ActionResult Create(CreateGameModel model) { public JsonResult Create(EditGameModel model) {
if (!ModelState.IsValid) { if (!ModelState.IsValid) {
return Json(this.CreateJsonErrorResponse("Some errors occurred.")); return Json(this.CreateJsonErrorResponse("Some errors occurred."));
} }

View File

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

View File

@ -71,7 +71,7 @@ namespace VideoGameQuotes.Web {
//bullshit route so that RenderAction works //bullshit route so that RenderAction works
routes.MapRoute("mainmenu", "home/mainmenu", new { controller = "Home", action = "MainMenu" }); 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("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" }); 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.Collections.Generic;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Web;
using VideoGameQuotes.Api; using VideoGameQuotes.Api;
namespace VideoGameQuotes.Web.Models { namespace VideoGameQuotes.Web.Models {
public class CreateGameModel { public class EditGameModel {
public CreateGameModel() { public EditGameModel() {
GameRegions = Region.Unknown; GameRegions = Region.Unknown;
} }
@ -15,5 +16,7 @@ namespace VideoGameQuotes.Web.Models {
public List<int> PublisherIds { get; set; } public List<int> PublisherIds { get; set; }
[Required(ErrorMessage = "At least one system must be specified, uglyface")] [Required(ErrorMessage = "At least one system must be specified, uglyface")]
public List<int> SystemIds { get; set; } 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"; ActionName = "Edit";
} }
public User CurrentUser { get; set; }
public string ActionName { get; set; } public string ActionName { get; set; }
public string ControllerName { get; set; } public string ControllerName { get; set; }

View File

@ -9,6 +9,7 @@ namespace VideoGameQuotes.Web.Services {
[CanBeNull] [CanBeNull]
Game FindByNameAndSystems(string name, IEnumerable<int> systemIds); Game FindByNameAndSystems(string name, IEnumerable<int> systemIds);
Game Save(Game game); Game Save(Game game);
Game FindById(int id);
} }
public class GameService : IGameService { public class GameService : IGameService {
@ -29,5 +30,10 @@ namespace VideoGameQuotes.Web.Services {
public Game Save(Game game) { public Game Save(Game game) {
return repository.Save(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<Publisher> publisherRepository;
private readonly IRepository<Category> categoryRepository; private readonly IRepository<Category> categoryRepository;
private readonly IRepository<Vote> voteRepository; private readonly IRepository<Vote> voteRepository;
private static readonly Random random = new Random();
public QuoteService( public QuoteService(
IRepository<Quote> quoteRepository, IRepository<Quote> quoteRepository,
@ -117,25 +118,29 @@ namespace VideoGameQuotes.Web.Services {
[UnitOfWork] [UnitOfWork]
public Quote GetRandomQuote() { public Quote GetRandomQuote() {
var quotes = quoteRepository.Records.ToArray(); var length = quoteRepository.Records.Count();
if (quotes.Length == 0) { if (length == 0) {
return null; return null;
} }
return quotes[new Random().Next(quotes.Length)]; return quoteRepository
.Records
.Skip(random.Next(length))
.Take(1)
.Single();
} }
[UnitOfWork] [UnitOfWork]
public IEnumerable<Quote> GetBestQuotes(int start, int end, out int totalCount) { 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
var records = quoteRepository.Records.ToArray();
totalCount = records.Length;
return records
.OrderByDescending(quote => quote.Score) .OrderByDescending(quote => quote.Score)
.ThenByDescending(quote => quote.UpVotes) .ThenByDescending(quote => quote.UpVotes)
.Skip(start - 1) .Skip(start - 1)
.Take(end - start + 1); .Take(end - start + 1);
totalCount = quoteRepository.Records.Count();
return records;
} }
[UnitOfWork] [UnitOfWork]

View File

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

View File

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

View File

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

View File

@ -42,18 +42,53 @@
.hide(); .hide();
}; };
$.vgquotes = { $.vgquotes = function() {
refresh: function() { }, var callApi = function(url, type, data, callback) {
ajaxErrorHandler: function(xhr) { $.ajax(url, {
alert("An error occurred (" + xhr.statusCode + ")"); type: type,
}, data: data,
preload: function(images) { success: callback,
//MM_preloadImages(lulz) error: callback
$.each(images, function() {
$('<img/>')[0].src = this;
}); });
} };
};
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(){ (function(){
var refreshCookie = "vgquotes.refreshFragment"; var refreshCookie = "vgquotes.refreshFragment";
@ -106,10 +141,6 @@
var setupVoting = function() { var setupVoting = function() {
var voting = false; var voting = false;
var loadingGif = "/media/images/loading.gif";
$.vgquotes.preload([loadingGif]);
$(".vote-for, .vote-against").live("click", function() { $(".vote-for, .vote-against").live("click", function() {
if (voting) { if (voting) {
alert("Please wait for the current vote to process before voting again"); alert("Please wait for the current vote to process before voting again");
@ -128,7 +159,7 @@
type: "POST", type: "POST",
data: { QuoteId: quoteId, Direction: direction }, data: { QuoteId: quoteId, Direction: direction },
beforeSend: function() { 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) { success: function(data, status, $xhr) {
if (data.Error !== null) { if (data.Error !== null) {
@ -136,7 +167,7 @@
return; return;
} }
score = data.Data.netVotes; score = data.Data.score;
$score.attr("title", "+" + data.Data.upVotes + ", -" + data.Data.downVotes); $score.attr("title", "+" + data.Data.upVotes + ", -" + data.Data.downVotes);
//remove the voting arrow, and add the other one if needed //remove the voting arrow, and add the other one if needed
@ -284,7 +315,13 @@
var setupQuoteForm = function() { var setupQuoteForm = function() {
var toggleFormAndLink = function(type) { var toggleFormAndLink = function(type) {
return function() { 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(); $("#" + type + "-select").toggle();
return false; 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); }); $("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"); 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", type: "POST",
data: data, data: data,
traditional: true, traditional: true,
@ -372,9 +416,13 @@
return; return;
} }
$("#GameId") if (!submittingAnEdit) {
.append($("<option/>").attr({ value: data.Data.Id}).text(data.Data.Name)) $("#GameId")
.val(data.Data.Id); .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")(); toggleFormAndLink("game")();
} }
@ -469,6 +517,38 @@
return false; 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(){ (function(){
@ -476,6 +556,7 @@
setupSearch(); setupSearch();
$(document).ready(function() { $(document).ready(function() {
$.vgquotes.preload([$.vgquotes.loadingGif]);
setupReportLink(); setupReportLink();
setupVoting(); setupVoting();

View File

@ -116,11 +116,15 @@ namespace VideoGameQuotes.Api.Tests.NHibernate {
#region categories #region categories
var engrish = new Category { Name = "Engrish" }; var engrish = new Category { Name = "Engrish" };
var danger = new Category { Name = "Danger" }; var danger = new Category { Name = "Danger" };
var smoke = new Category { Name = "Smoke" };
var dolphins = new Category { Name = "Dolphins" };
using (var tx = session.BeginTransaction()) { using (var tx = session.BeginTransaction()) {
var repo = new NHibernateRepository<Category>(session); var repo = new NHibernateRepository<Category>(session);
repo.Save(engrish); repo.Save(engrish);
repo.Save(danger); repo.Save(danger);
repo.Save(smoke);
repo.Save(dolphins);
tx.Commit(); tx.Commit();
} }
#endregion #endregion
@ -157,23 +161,26 @@ namespace VideoGameQuotes.Api.Tests.NHibernate {
#endregion #endregion
#region quotes #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) .AddCategory(engrish)
.VoteFor(creator, VoteDirection.Up); .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) .AddCategory(danger)
.VoteFor(creator, VoteDirection.Up); .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." } 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" }) .AddCategory(dolphins);
.VoteFor(creator, VoteDirection.Up);
using (var tx = session.BeginTransaction()) { using (var tx = session.BeginTransaction()) {
var repo = new NHibernateRepository<Quote>(session); var repo = new NHibernateRepository<Quote>(session);
repo.Save(allYourBase); repo.Save(allYourBase);
repo.Save(dangerousToGoAlone); repo.Save(dangerousToGoAlone);
repo.Save(hopOnMyBack); repo.Save(hopOnMyBack);
repo.Save(dodongo);
tx.Commit(); tx.Commit();
} }
#endregion #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, game_name VARCHAR(255) not null,
website VARCHAR(255), website VARCHAR(255),
created DATETIME not null, created DATETIME not null,
screenshot BLOB, icon BLOB,
game_region INTEGER not null, game_region INTEGER not null,
creator INTEGER not null, creator INTEGER not null,
primary key (game_id) primary key (game_id)
@ -148,6 +148,9 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
modified DATETIME, modified DATETIME,
creator INTEGER not null, creator INTEGER not null,
game_id INTEGER not null, game_id INTEGER not null,
score INTEGER,
upvotes INTEGER,
downvotes INTEGER,
primary key (quote_id) primary key (quote_id)
); );
@ -159,8 +162,8 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
create table system ( create table system (
system_id INTEGER NOT NULL AUTO_INCREMENT, system_id INTEGER NOT NULL AUTO_INCREMENT,
system_name VARCHAR(255) not null, system_name VARCHAR(255) not null unique,
system_abbreviation VARCHAR(12), system_abbreviation VARCHAR(12) unique,
created DATETIME not null, created DATETIME not null,
release_date DATETIME, release_date DATETIME,
primary key (system_id) primary key (system_id)
@ -216,10 +219,12 @@ alter table quote_category_map drop foreign key FK5892F846C2AA09DD
alter table quote_flag alter table quote_flag
add index (quote_id), add index (quote_id),
add constraint fk_quote_flag add constraint fk_flag_quote
foreign key (quote_id) foreign key (quote_id)
references game_quote (quote_id); references game_quote (quote_id);
create index idx_score_upvotes on game_quote (score, upvotes);
alter table game_quote alter table game_quote
add index (creator), add index (creator),
add constraint fk_quote_user add constraint fk_quote_user