public BattleBalanceData(int battleID) { ZkDataContext db = new ZkDataContext(); SpringBattle game = db.SpringBattles.FirstOrDefault(x => x.SpringBattleID == battleID); this.battleID = battleID; this.t1Elo = new List<double>(); this.t2Elo = new List<double>(); this.t1Names = new List<string>(); this.t2Names = new List<string>(); double t1Sum = 0; double t2Sum = 0; int t1Count = 0; int t2Count = 0; foreach (SpringBattlePlayer player in game.SpringBattlePlayers.Where(x=> !x.IsSpectator)) { if (player.IsInVictoryTeam) { t1Sum += player.Account.EffectiveElo; this.t1Elo.Add(Math.Floor(player.Account.EffectiveElo+0.5)); this.t1Names.Add(player.Account.Name); t1Count++; } else { t2Sum += player.Account.EffectiveElo; this.t2Elo.Add(Math.Floor(player.Account.EffectiveElo + 0.5)); this.t2Names.Add(player.Account.Name); t2Count++; } } this.t1Avg = Math.Floor(t1Sum / t1Count + 0.5); this.t2Avg = Math.Floor(t2Sum / t2Count + 0.5); this.t1Variance = Math.Floor(Variance(this.t1Elo, this.t1Avg) + 0.5); this.t2Variance = Math.Floor(Variance(this.t2Elo, this.t2Avg) + 0.5); }
public ActionResult ChangePermissions(int accountID, bool zkAdmin, bool vpnException) { var db = new ZkDataContext(); Account acc = db.Accounts.Single(x => x.AccountID == accountID); Account adminAcc = Global.Account; Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format("Permissions changed for {0} {1} by {2}", acc.Name, Url.Action("Detail", "Users", new { id = acc.AccountID }, "http"), adminAcc.Name)); if (acc.IsZeroKAdmin != zkAdmin) { //reset chat priviledges to 2 if removing adminhood; remove NW subsciption to admin channel // FIXME needs to also terminate forbidden clan/faction subscriptions Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format(" - Admin status: {0} -> {1}", acc.IsZeroKAdmin, zkAdmin)); acc.IsZeroKAdmin = zkAdmin; } if (acc.HasVpnException != vpnException) { Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format(" - VPN exception: {0} -> {1}", acc.HasVpnException, vpnException)); acc.HasVpnException = vpnException; } db.SaveChanges(); Global.Server.PublishAccountUpdate(acc); return RedirectToAction("Detail", "Users", new { id = acc.AccountID }); }
public ActionResult AddContribution(int accountID,int kudos, string item, string currency, double gross, double grossEur, double netEur, string email, string comment, bool isSpring, DateTime date) { using (var db = new ZkDataContext()) { var acc = db.Accounts.Find(accountID); var contrib = new Contribution() { AccountID = accountID, ManuallyAddedAccountID = Global.AccountID, KudosValue = kudos, ItemName = item, IsSpringContribution = isSpring, Comment = comment, OriginalCurrency = currency, OriginalAmount = gross, Euros = grossEur, EurosNet = netEur, Time = date, Name = acc.Name, Email = email }; db.Contributions.InsertOnSubmit(contrib); db.SubmitAndMergeChanges(); acc.Kudos = acc.KudosGained - acc.KudosSpent; db.SubmitAndMergeChanges(); } return RedirectToAction("Index"); }
private static void CachePunishments() { lock (punishmentsLock) { using (var db = new ZkDataContext()) punishments = db.Punishments.Where(x => x.BanExpires > DateTime.UtcNow).Include(x=>x.AccountByAccountID).Include(x=>x.AccountByCreatedAccountID).ToList(); } }
public static void GenerateTechs() { var db = new ZkDataContext(); db.StructureTypes.DeleteAllOnSubmit(db.StructureTypes.Where(x => x.Unlock != null)); db.SaveChanges(); foreach (var u in db.Unlocks.Where(x => x.UnlockType == UnlockTypes.Unit)) { var s = new StructureType() { BattleDeletesThis = false, Cost = u.XpCost / 2, MapIcon = "techlab.png", DisabledMapIcon = "techlab_dead.png", Name = u.Name, Description = string.Format("Access to {0} and increases influence gains", u.Name), TurnsToActivate = u.XpCost / 100, IsBuildable = true, IsIngameDestructible = true, IsBomberDestructible = true, Unlock = u, UpkeepEnergy = u.XpCost / 5, IngameUnitName = "pw_" + u.Code, }; db.StructureTypes.InsertOnSubmit(s); } db.SaveChanges(); }
public ActionResult Index(int id, List<int> grSel) { var db = new ZkDataContext(); var post = db.ForumPosts.Find(id); string txt1; string txt2; if (grSel != null && grSel.Any()) { if (grSel.Count > 1) { txt1 = db.ForumPostEdits.Find(grSel.Min()).NewText; txt2 = db.ForumPostEdits.Find(grSel.Max()).NewText; } else { var edit = db.ForumPostEdits.Find(grSel.First()); txt1 = edit.OriginalText; txt2 = edit.NewText; } var sd = new SideBySideDiffBuilder(new Differ()); ViewBag.DiffModel = sd.BuildDiffModel(txt1, txt2); } else { var edit = post.ForumPostEdits.OrderByDescending(x => x.ForumPostEditID).FirstOrDefault(); if (edit != null) { var sd = new SideBySideDiffBuilder(new Differ()); ViewBag.DiffModel = sd.BuildDiffModel(edit.OriginalText, edit.NewText); } } return View("PostHistoryIndex", post); }
public NwSteamHandler(TasClient tas, string webApiKey) { steamApi = new SteamWebApi(GlobalConst.SteamAppID, webApiKey); tas.Said += (sender, args) => { if (args.Place == SayPlace.User && args.UserName != tas.UserName && args.Text.StartsWith("!linksteam")) { var token = args.Text.Substring(11); User user; if (tas.ExistingUsers.TryGetValue(args.UserName, out user)) { Utils.StartAsync(() => { Thread.Sleep(2000); // steam is slow to get the ticket from client .. wont verify if its checked too soon var steamID = steamApi.WebValidateAuthToken(token); var info = steamApi.WebGetPlayerInfo(steamID); using (var db = new ZkDataContext()) { var acc = db.Accounts.Find(user.AccountID); acc.SteamID = steamID; acc.SteamName = info.personaname; db.SubmitAndMergeChanges(); tas.Extensions.PublishAccountData(acc); } }); } } }; }
public Task StoreChatHistoryAsync(Say say) { return Task.Run(async () => { await storeHistorySemaphore.WaitAsync(); try { using (var db = new ZkDataContext()) { var historyEntry = new LobbyChatHistory(); historyEntry.SetFromSay(say); db.LobbyChatHistories.Add(historyEntry); db.SaveChanges(); } } catch (Exception ex) { Trace.TraceError("Error saving chat history: {0}", ex); } finally { storeHistorySemaphore.Release(); } }); }
public static string SubmitSpringBattleResult(Spring.SpringBattleContext result, ZkLobbyServer.ZkLobbyServer server) { try { if (!result.GameEndedOk) return "Game didn't end properly"; if (result.IsCheating) return "Cheats were enabled during this game"; var db = new ZkDataContext(); var text = new StringBuilder(); var sb = SaveSpringBattle(result, db); ProcessExtras(result.OutputExtras, sb, db); if (result.LobbyStartContext.Mode == AutohostMode.Planetwars) ProcessPlanetWars(result, server, sb, db, text); ProcessElos(result, server, db, sb); text.AppendLine(string.Format("BATTLE DETAILS AND REPLAY ----> {1}/Battles/Detail/{0} <-----", sb.SpringBattleID, GlobalConst.BaseSiteUrl)); return text.ToString(); } catch (Exception ex) { var data = JsonConvert.SerializeObject(result); Trace.TraceError($"{ex}\nData:\n{data}"); return $"{ex}\nData:\n{data}"; } }
public Mission GetMissionByID(int missionID) { var db = new ZkDataContext(); db.Configuration.ProxyCreationEnabled = false; var prev = db.Missions.Where(x => x.MissionID == missionID).Include(x=>x.Mutator).SingleOrDefault(); return prev; }
public override async Task ExecuteArmed(ServerBattle battle, Say e) { var b = battle; Dictionary<int, double> grouping; using (var db = new ZkDataContext()) { if (battle.IsInGame) grouping = b.spring.LobbyStartContext?.Players.Where(u => !u.IsSpectator) .GroupBy(u => u.AllyID) .ToDictionary(x => x.Key, x => x.Average(y => Account.AccountByName(db, y.Name).EffectiveMmElo)); else grouping = b.Users.Values.Where(u => !u.IsSpectator) .GroupBy(u => u.AllyNumber) .ToDictionary(x => x.Key, x => x.Average(y => y.LobbyUser.EffectiveMmElo)); } KeyValuePair<int, double>? oldg = null; foreach (var g in grouping) { if (oldg != null) { var t1elo = oldg.Value.Value; var t2elo = g.Value; await battle.Respond(e, $"team {oldg.Value.Key + 1} has {Utils.GetWinChancePercent(t2elo - t1elo)}% chance to win over team {g.Key + 1}"); } oldg = g; } }
public static void ConvertPage(string pageName, string newName, bool overwrite = false) { var db = new ZkDataContext(); ForumThread thread = db.ForumThreads.FirstOrDefault(x=> x.WikiKey == pageName); if (thread == null) { Console.WriteLine("No ZK wiki page with name {0} found", pageName); return; } string text = thread.ForumPosts.First().Text; text = BBCodeToMediaWiki(text); Page page = new Page(newWiki, newName); page.Load(); bool update = false; if (!page.IsEmpty()) { if (!overwrite) { Console.WriteLine("Page already exists, exiting"); return; } else update = true; } if (newName.StartsWith("Mission Editor", true, System.Globalization.CultureInfo.CurrentCulture)) page.AddToCategory("Mission Editor"); page.Save(text, update ? "" : "Ported from ZK wiki by DotNetWikiBot", update); }
public GalaxyDialog() { InitializeComponent(); var db = new ZkDataContext(); cmbGal.Items.Add("as new"); foreach (var g in db.Galaxies) cmbGal.Items.Add(g.GalaxyID.ToString()); }
public ResourceData GetResourceDataByInternalName(string internalName) { var db = new ZkDataContext(); var entry = db.Resources.SingleOrDefault(x => x.InternalName == internalName); if (entry != null) return PlasmaServer.ToResourceData(entry); else return null; }
// // GET: /News/ public ActionResult Index() { Response.ClearContent(); Response.ContentType = "application/rss+xml"; var db = new ZkDataContext(); return View(db.News.Where(x=>x.Created < DateTime.UtcNow).OrderByDescending(x=>x.Created)); }
void client_ChannelUserAdded(object sender, ChannelUserInfo e) { Task.Run(async () => { try { var chan = e.Channel.Name; List<LobbyMessage> messages; foreach (var user in e.Users) { using (var db = new ZkDataContext()) { messages = db.LobbyMessages.Where(x => x.TargetName == user.Name && x.Channel == chan).OrderBy(x => x.Created).ToList(); db.LobbyMessages.DeleteAllOnSubmit(messages); db.SubmitChanges(); } foreach (var m in messages) { var text = string.Format("!pm|{0}|{1}|{2}|{3}", m.Channel, m.SourceName, m.Created.ToString(CultureInfo.InvariantCulture), m.Message); await client.Say(SayPlace.User, user.Name, text, false); await Task.Delay(MessageDelay); } } } catch (Exception ex) { Trace.TraceError("Error adding user: {0}", ex); } }); }
// // GET: /Poll/ public ActionResult Index(int pollID) { var db = new ZkDataContext(); var poll = db.Polls.FirstOrDefault(x => x.PollID == pollID); if (poll != null) return PartialView("PollView", poll); return null; }
public async Task<bool> CanJoin(int accountID, string channel) { using (var db = new ZkDataContext()) { var acc = await db.Accounts.FindAsync(accountID); return CanJoin(acc, channel); } }
// // GET: /Maps/ public ActionResult Detail(int id) { var db = new ZkDataContext(); var res = db.Resources.Single(x => x.ResourceID == id); var data = GetMapDetailData(res, db); return View(data); }
protected void Page_Load(object sender, EventArgs e) { var db = new ZkDataContext(); if (!int.TryParse(Request["resourceID"], out resourceID)) { resourceID = db.Resources.Single(x => x.InternalName == Request["name"]).ResourceID; } if (!IsPostBack) { var res = db.Resources.Where(x => x.ResourceID == resourceID).Single(); lbDetails.Text = string.Format("Download count: {0}<br/>\nFailed downloads (no links): {1}<br/>\n", res.DownloadCount, res.NoLinkDownloadCount); lbName.Text = res.InternalName; litLinks.Text = string.Join("<br/>", res.ResourceDependencies.Select(x => x.NeedsInternalName).ToArray()); string name = res.InternalName.EscapePath(); var sb = new StringBuilder(); if (res.TypeID == ZkData.ResourceType.Map) { sb.AppendFormat("<img src='Resources/{0}.minimap.jpg'><br/>", name); sb.AppendFormat("<img src='Resources/{0}.heightmap.jpg'><br/>", name); sb.AppendFormat("<img src='Resources/{0}.metalmap.jpg'><br/>", name); } sb.AppendFormat("<a href='Resources/{0}.metadata.xml.gz'>metadata</a><br/>", name); litBasics.Text = sb.ToString(); } }
public ActionResult DeleteAllPostsByUser(int accountID, string accountName) { var db = new ZkDataContext(); var acc = db.Accounts.FirstOrDefault(x => x.AccountID == accountID); if (acc.Name != accountName) return Content("Invalid safety code"); foreach (var p in acc.ForumPosts) DeletePost(p.ForumPostID); return RedirectToAction("Index"); }
public static Account VerifyAccountHashed(string login, string passwordHash) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(passwordHash)) return null; var db = new ZkDataContext(); var acc = Account.AccountVerify(db, login, passwordHash); return acc; }
private void CopyExtraImages() { var db = new ZkDataContext(); var configs = Path.Combine(targetFolder, "LuaUI", "Configs"); Utils.CheckPath(configs); var tpath = Path.Combine(configs, "Avatars"); Utils.CheckPath(tpath); Trace.TraceInformation("Copying avatars"); var spath = Path.Combine(siteBase, "img", "Avatars"); foreach (var file in Directory.GetFiles(spath)) File.Copy(file, Path.Combine(tpath, Path.GetFileName(file)), true); Trace.TraceInformation("Copying clan icons"); tpath = Path.Combine(configs, "Clans"); Utils.CheckPath(tpath); spath = Path.Combine(siteBase, "img", "clans"); foreach (var clan in db.Clans.Where(x => !x.IsDeleted)) { var fileName = $"{clan.Shortcut}.png"; var src = Path.Combine(spath, fileName); if (File.Exists(src)) File.Copy(src, Path.Combine(tpath, fileName), true); } Trace.TraceInformation("Copying faction icons"); tpath = Path.Combine(configs, "Factions"); Utils.CheckPath(tpath); spath = Path.Combine(siteBase, "img", "factions"); foreach (var fac in db.Factions.Where(x => !x.IsDeleted)) { var fileName = $"{fac.Shortcut}.png"; var src = Path.Combine(spath, fileName); if (File.Exists(src)) File.Copy(src, Path.Combine(tpath, fileName), true); } }
public ActionResult Delete(int id) { var db = new ZkDataContext(); db.Missions.First(x => x.MissionID == id).IsDeleted = true; db.SubmitChanges(); return RedirectToAction("Index"); }
static void Main(string[] args) { var db = new ZkDataContext(); var dict = db.Accounts.ToDictionary(x => x.AccountID); var path = args.Length > 0 ? args[0] : @"accounts.txt"; using (var r = new StreamReader(path)) { string line; while ((line = r.ReadLine()) != null) { Account ac = null; try { var parts = line.Split(' '); if (parts.Length < 9) { Trace.TraceError("Faulty line: ", line); continue; } var name = parts[0]; var pass = parts[1]; var flags = parts[2]; //var cookie = int.Parse(parts[3]); var lastLogin = ConvertTimestamp(double.Parse(parts[4]) / 1000); var lastIP = parts[5]; var registered = ConvertTimestamp(double.Parse(parts[6]) / 1000); var country = parts[7]; var id = int.Parse(parts[8]); Account de = null; dict.TryGetValue(id, out de); Console.WriteLine(string.Format("{0} {1}", id, name)); if (de == null || name != de.Name || pass != de.Password || registered != de.FirstLogin ) { if (de == null) { ac = new Account(); db.Accounts.InsertOnSubmit(ac); } else ac = db.Accounts.SingleOrDefault(x => x.LobbyID == id); ac.LobbyID = id; ac.Name = name; //ac.Flags = flags; ac.Password = pass; //ac.UserCookie = cookie; if (lastLogin.HasValue) ac.LastLogin = lastLogin.Value; //ac.LastIP = lastIP; if (registered.HasValue) ac.FirstLogin = registered.Value; if (ac.LastLogin == DateTime.MinValue) ac.LastLogin = registered ?? DateTime.UtcNow; //ac.Created = registered; ac.Country = country; Console.Write(" CHANGED!"); db.SubmitChanges(); } } catch (Exception e) { Console.WriteLine("Problem importing line: {0}: {1}", line, e); db = new ZkDataContext(); } } } }
public async Task<List<string>> GetDefaultChannels(int accountID) { using (var db = new ZkDataContext()) { var acc = await db.Accounts.FindAsync(accountID); return GetDefaultChannels(acc); } }
/// <summary> /// Clan list /// </summary> public ActionResult Index(ClansModel model) { model = model ?? new ClansModel(); var db = new ZkDataContext(); var ret = db.Clans.Where(x => !x.IsDeleted && (x.Faction != null && !x.Faction.IsDeleted)); if (!string.IsNullOrEmpty(model.Search)) ret = ret.Where(x => x.ClanName.Contains(model.Search) || x.Shortcut.Contains(model.Search)); model.Data = ret.OrderBy(x => x.ClanName); return View("ClansIndex", model); }
public List<string> GetEloTop10() { DateTime lastMonth = DateTime.UtcNow.AddMonths(-1); using (var db = new ZkDataContext()) return db.Accounts.Where(x => x.SpringBattlePlayers.Any(y => y.SpringBattle.StartTime > lastMonth)).OrderByDescending( x => x.Effective1v1Elo).WithTranslations().Select(x => x.Name).Take(10).ToList(); }
public ActionResult NewTreaty(int? acceptingFactionID) { // first display of the form, target faction not yet set var db = new ZkDataContext(); var treaty = new FactionTreaty(); treaty.AccountByProposingAccountID = Global.Account; treaty.FactionByProposingFactionID = Global.Account.Faction; treaty.FactionByAcceptingFactionID = db.Factions.SingleOrDefault(x => x.FactionID == acceptingFactionID); return View("FactionTreatyDefinition", treaty); }
public async Task StoreChatHistory(Say say) { using (var db = new ZkDataContext()) { var historyEntry = new LobbyChatHistory(); historyEntry.SetFromSay(say); db.LobbyChatHistories.Add(historyEntry); await db.SaveChangesAsync(); } }
public static Account AccountByName(ZkDataContext db, string name) { return(db.Accounts.FirstOrDefault(x => x.Name == name) ?? db.Accounts.FirstOrDefault(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase))); }
public static Account AccountByName(ZkDataContext db, string name) { return(db.Accounts.FirstOrDefault(x => x.Name == name)); }
public EntityEntry(object entity, EntityState state, ZkDataContext context) { Entity = entity; State = state; Context = context; }
public string GetSteamWebApiKey(ZkDataContext db = null) { return(GetVarValue(db, "SteamWebApiKey")); }
public string GetGithubHookKey(ZkDataContext db = null) { return(GetVarValue(db, "GithubHookKey")); }
public void UpdateMission(ZkDataContext db, Mission mission, Mod modInfo) { var file = mission.Mutator.ToArray(); var tempName = Path.GetTempFileName() + ".zip"; File.WriteAllBytes(tempName, file); using (var zf = new ZipFile(tempName)) { zf.UpdateEntry("modinfo.lua", Encoding.UTF8.GetBytes(GetModInfo(mission.NameWithVersion, mission.Mod, mission.Name, "ZK"))); // FIXME hardcoded crap FixScript(mission, zf, "script.txt"); var script = FixScript(mission, zf, GlobalConst.MissionScriptFileName); modInfo.MissionScript = script; //modInfo.ShortName = mission.Name; modInfo.Name = mission.NameWithVersion; zf.Save(); } mission.Mutator = File.ReadAllBytes(tempName); mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => { return(string.Format("GameType={0};", mission.NameWithVersion)); }); File.Delete(tempName); var resource = db.Resources.FirstOrDefault(x => x.MissionID == mission.MissionID); if (resource == null) { resource = new Resource() { DownloadCount = 0, TypeID = ZkData.ResourceType.Mod }; db.Resources.Add(resource); } resource.InternalName = mission.NameWithVersion; resource.MissionID = mission.MissionID; resource.ResourceDependencies.Clear(); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Map }); resource.ResourceDependencies.Add(new ResourceDependency() { NeedsInternalName = mission.Mod }); resource.ResourceContentFiles.Clear(); // generate torrent var tempFile = Path.Combine(Path.GetTempPath(), mission.SanitizedFileName); File.WriteAllBytes(tempFile, mission.Mutator.ToArray()); var creator = new TorrentCreator(); creator.Path = tempFile; var torrentStream = new MemoryStream(); creator.Create(torrentStream); try { File.Delete(tempFile); } catch { } var md5 = Hash.HashBytes(mission.Mutator.ToArray()).ToString(); resource.ResourceContentFiles.Add(new ResourceContentFile() { FileName = mission.SanitizedFileName, Length = mission.Mutator.Length, LinkCount = 1, Links = string.Format(MissionFileUrl, mission.MissionID), Md5 = md5 }); var basePath = GlobalConst.SiteDiskPath + @"\resources\"; File.WriteAllBytes(string.Format(@"{2}\{0}_{1}.torrent", resource.InternalName.EscapePath(), md5, basePath), torrentStream.ToArray()); File.WriteAllBytes(string.Format(@"{1}\{0}.metadata.xml.gz", resource.InternalName.EscapePath(), basePath), MetaDataCache.SerializeAndCompressMetaData(modInfo)); File.WriteAllBytes(string.Format(GlobalConst.SiteDiskPath + @"\img\missions\{0}.png", mission.MissionID, basePath), mission.Image.ToArray()); }
public string GetNightwatchPassword(ZkDataContext db = null) { return(GetVarValue(db, "NightwatchPassword")); }
/// <summary> /// Finds active punishment /// </summary> /// <param name="accountID">0 is treated same as null</param> /// <param name="ip">"" is treated same as null</param> /// <param name="userID">0 is treated same as null</param> /// <param name="filter">additional filtering to punishments</param> /// <param name="db">db context to use</param> /// <returns></returns> public static Punishment GetActivePunishment(int?accountID, string ip, long?userID, Expression <Func <Punishment, bool> > filter = null, ZkDataContext db = null) { if (ip == "") { ip = null; } if (accountID == 0) { accountID = null; } if (userID == 0) { userID = null; } if (db == null) { db = new ZkDataContext(); } var ret = db.Punishments.Where(x => x.BanExpires > DateTime.UtcNow); // don't use IsExpired because it has no supported translation to SQL if (filter != null) { ret = ret.Where(filter); } ret = ret.Where( x => (accountID != null && x.AccountID == accountID) || (userID != null && x.UserID == userID) || (ip != null && x.BanIP == ip)); return(ret.OrderByDescending(x => x.BanExpires).FirstOrDefault()); }
Contribution AddPayPalContribution(ParsedData parsed) { try { if ((parsed.Status != "Completed" && parsed.Status != "Cleared") || parsed.Gross <= 0) { return(null); // not a contribution! } double netEur; double grossEur; if (parsed.Currency == "EUR") { netEur = parsed.Net; grossEur = parsed.Gross; } else { netEur = ConvertToEuros(parsed.Currency, parsed.Net); grossEur = ConvertToEuros(parsed.Currency, parsed.Gross); } int?accountID, jarID; TryParseItemCode(parsed.ItemCode, out accountID, out jarID); Contribution contrib; using (var db = new ZkDataContext()) { Account acc = null; ContributionJar jar; if (jarID == null) { jar = db.ContributionJars.FirstOrDefault(x => x.IsDefault); } else { jar = db.ContributionJars.FirstOrDefault(x => x.ContributionJarID == jarID); } if (accountID != null) { acc = db.Accounts.Find(accountID.Value); } if (!string.IsNullOrEmpty(parsed.TransactionID) && db.Contributions.Any(x => x.PayPalTransactionID == parsed.TransactionID)) { return(null); // contribution already exists } var isSpring = !parsed.ItemCode.StartsWith("ZK") || jar.IsDefault; contrib = new Contribution() { AccountByAccountID = acc, Name = parsed.Name, Euros = grossEur, KudosValue = (int)Math.Round(grossEur * GlobalConst.EurosToKudos), OriginalAmount = parsed.Gross, OriginalCurrency = parsed.Currency, PayPalTransactionID = parsed.TransactionID, ItemCode = parsed.ItemCode, Time = parsed.Time, EurosNet = netEur, ItemName = parsed.ItemName, Email = parsed.Email, RedeemCode = Guid.NewGuid().ToString(), IsSpringContribution = isSpring, ContributionJar = jar }; db.Contributions.Add(contrib); db.SaveChanges(); if (acc != null) { acc.Kudos = acc.KudosGained - acc.KudosSpent; } db.SaveChanges(); // technically not needed to sent when account is known, but perhaps its nice to get a confirmation like that SendEmail(contrib); NewContribution(contrib); } return(contrib); } catch (Exception ex) { Trace.TraceError("Error processing payment: {0}", ex); Error(ex.ToString()); return(null); } }