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.SaveChanges();
                acc.Kudos = acc.KudosGained - acc.KudosSpent;
                db.SaveChanges();
            }


            return RedirectToAction("Index");
        }
        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 Redeem(string code) {
            var db = new ZkDataContext();
            if (string.IsNullOrEmpty(code)) return Content("Code is empty");
            var contrib = db.Contributions.SingleOrDefault(x => x.RedeemCode == code);
            if (contrib == null) return Content("No contribution with that code found");
            if (contrib.AccountByAccountID != null) return Content(string.Format("This contribution has been assigned to {0}, thank you.", contrib.AccountByAccountID.Name));
            var acc = db.Accounts.Find(Global.AccountID);
            contrib.AccountByAccountID = acc;
            db.SaveChanges();
            acc.Kudos = acc.KudosGained - acc.KudosSpent;
            db.SaveChanges();

            return Content(string.Format("Thank you!! {0} Kudos have been added to your account {1}", contrib.KudosValue, contrib.AccountByAccountID.Name));
        }
        public ActionResult ChangeFeaturedOrder(int id, float? featuredOrder, string script)
        {
            var db = new ZkDataContext();
            var mis = db.Missions.SingleOrDefault(x => x.MissionID == id);
            mis.FeaturedOrder = featuredOrder;
            if (mis.IsScriptMission && !string.IsNullOrEmpty(script)) mis.Script = script;
            db.SaveChanges();

            var order = 1;
            if (featuredOrder.HasValue) foreach (var m in db.Missions.Where(x => x.FeaturedOrder != null).OrderBy(x => x.FeaturedOrder)) m.FeaturedOrder = order++;
            db.SaveChanges();

            return RedirectToAction("Index");
        }
 public ActionResult Delete(int id)
 {
     var db = new ZkDataContext();
     db.Missions.First(x => x.MissionID == id).IsDeleted = true;
     db.SaveChanges();
     return RedirectToAction("Index");
 }
 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 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 RemoveBlockedCompany(int companyID)
 {
     ZkDataContext db = new ZkDataContext();
     BlockedCompany todel = db.BlockedCompanies.First(x => x.CompanyID == companyID);
     string name = todel.CompanyName;
     db.BlockedCompanies.DeleteOnSubmit(todel);
     db.SaveChanges();
     var str = string.Format("{0} removed blocked VPN company: {1}", Global.Account.Name, name);
     Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, str);
     return RedirectToAction("BlockedVPNs");
 }
        public static ReturnValue DeleteResource(string internalName)
        {
            var db = new ZkDataContext();
            var todel = db.Resources.SingleOrDefault(x => x.InternalName == internalName);
            if (todel == null) return ReturnValue.ResourceNotFound;
            RemoveResourceFiles(todel);

            db.Resources.Remove(todel);
            db.SaveChanges();
            return ReturnValue.Ok;
        }
        public ActionResult ChangeHideCountry(int accountID, bool hideCountry)
        {
            var db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == accountID);

            if (hideCountry) acc.Country = "??";
            // TODO reimplement ? Global.Nightwatch.Tas.SetHideCountry(acc.Name, hideCountry);
            db.SaveChanges();

            return RedirectToAction("Detail", "Users", new { id = acc.AccountID });
        }
        public ActionResult DeletePost(int? postID) {
            var db = new ZkDataContext();
            var post = db.ForumPosts.Single(x => x.ForumPostID == postID);
            var thread = post.ForumThread;
            var threadID = thread.ForumThreadID;
            //int index = post.ForumThread.ForumPosts.IndexOf(post);
            var page = GetPostPage(post);

            db.ForumPosts.DeleteOnSubmit(post);
            if (thread.ForumPosts.Count() <= 1 && IsNormalThread(thread))
            {
                db.ForumThreadLastReads.DeleteAllOnSubmit(db.ForumThreadLastReads.Where(x => x.ForumThreadID == thread.ForumThreadID).ToList());
                db.ForumThreads.DeleteOnSubmit(thread);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            db.SaveChanges();
            ResetThreadLastPostTime(threadID);
            return RedirectToAction("Thread", new { id = threadID, page });
        }
        public ActionResult NewPoll(string question, string answers, bool? isAnonymous)
        {
            var p = new Poll() { CreatedAccountID = Global.AccountID, IsHeadline = true, QuestionText = question, IsAnonymous = isAnonymous == true, };
            var db = new ZkDataContext();

            foreach (var a in answers.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) p.PollOptions.Add(new PollOption() { OptionText = a });

            db.Polls.InsertOnSubmit(p);
            db.SaveChanges();
            return RedirectToAction("UserVotes", new { id = Global.AccountID });
        }
        public ActionResult JoinFaction(int id) {
            if (Global.Account.FactionID != null) return Content("Already in faction");
            if (Global.Account.Clan != null && Global.Account.Clan.FactionID != id) return Content("Must leave current clan first");
            var db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            acc.FactionID = id;

            Faction faction = db.Factions.Single(x => x.FactionID == id);
            if (faction.IsDeleted && !(Global.Account.Clan != null && Global.Account.Clan.FactionID == id)) throw new ApplicationException("Cannot join deleted faction");
            db.Events.InsertOnSubmit(PlanetwarsEventCreator.CreateEvent("{0} joins {1}", acc, faction));
            db.SaveChanges();
            return RedirectToAction("Index", "Factions");
        }
예제 #14
0
 private static void StoreDbValue(string varName, string value)
 {
     using (var db = new ZkDataContext())
     {
         var entry = db.MiscVars.FirstOrDefault(x => x.VarName == varName);
         if (entry == null)
         {
             entry = new MiscVar() { VarName = varName };
             db.MiscVars.Add(entry);
         }
         entry.VarValue = value;
         db.SaveChanges();
     }
 }
		public void UndeleteMission(int missionID, string author, string password)
		{
			var db = new ZkDataContext();
			var prev = db.Missions.Where(x => x.MissionID == missionID).SingleOrDefault();
			if (prev != null)
			{
				var acc = AuthServiceClient.VerifyAccountPlain(author, password);
				if (acc == null) throw new ApplicationException("Invalid login name or password");
				if (acc.AccountID != prev.AccountID && !acc.IsZeroKAdmin) throw new ApplicationException("You cannot undelete a mission from an other user");
				prev.IsDeleted = false;
			    db.SaveChanges();
			}
			else throw new ApplicationException("No such mission found");
		}
 /// <summary>
 /// Shows clan page
 /// </summary>
 /// <returns></returns>
 public ActionResult Detail(int id)
 {
     var db = new ZkDataContext();
     var clan = db.Clans.First(x => x.ClanID == id);
     if (Global.ClanID == clan.ClanID)
     {
         if (clan.ForumThread != null)
         {
             clan.ForumThread.UpdateLastRead(Global.AccountID, false);
             db.SaveChanges();
         }
     }
     return View(clan);
 }
예제 #17
0
		public bool Start()
		{

			tas.Connected += tas_Connected;
			tas.LoginDenied += tas_LoginDenied;
			tas.LoginAccepted += tas_LoginAccepted;

		    using (var db = new ZkDataContext()) {
		        var acc = db.Accounts.FirstOrDefault(x => x.Name == GlobalConst.NightwatchName);
		        if (acc != null) {
		            acc.SetPasswordPlain(config.AccountPassword);
		            acc.IsBot = true;
		            acc.IsZeroKAdmin = true;
		            db.SaveChanges();
		        }
		    }

            Auth = new AuthService(tas);
            offlineMessages = new OfflineMessages(tas);
            playerMover = new PlayerMover(tas);
            SteamHandler = new NwSteamHandler(tas, new Secrets().GetSteamWebApiKey());
            chatRelay = new ChatRelay(tas, new Secrets().GetNightwatchPassword(), new List<string>() { "zkdev", "sy", "moddev" }); 

		    PayPalInterface = new PayPalInterface();
		    PayPalInterface.Error += (e) =>
		        { tas.Say(SayPlace.Channel, "zkdev", "PAYMENT ERROR: " + e.ToString(), true); };

		    PayPalInterface.NewContribution += (c) =>
		        {
		            tas.Say(SayPlace.Channel,
		                    "zkdev",
		                    string.Format("WOOHOO! {0:d} New contribution of {1:F2}€ by {2} - for the jar {3}", c.Time, c.Euros, c.Name.Split(new[]{' '},StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(), c.ContributionJar.Name),
		                    true);
		            if (c.AccountByAccountID == null)
		                tas.Say(SayPlace.Channel,
		                        "zkdev",
                                string.Format("Warning, user account unknown yet, payment remains unassigned. If you know user name, please assign it manually {0}/Contributions", GlobalConst.BaseSiteUrl),
		                        true);
                    else tas.Say(SayPlace.Channel,
                                "zkdev",
                                string.Format("It is {0} {2}/Users/Detail/{1}", c.AccountByAccountID.Name, c.AccountID, GlobalConst.BaseSiteUrl),
                                true);
		        };
            

    		tas.Connect(config.ServerHost, config.ServerPort);

			return true;
		}
        public ActionResult AddBlockedHost(string hostname, string comment)
        {
            ZkDataContext db = new ZkDataContext();
            if (String.IsNullOrWhiteSpace(hostname)) return Content("Hostname cannot be empty");
            db.BlockedHosts.InsertOnSubmit(new BlockedHost()
            {
                HostName = hostname,
                Comment = comment,
            });
            db.SaveChanges();

            var str = string.Format("{0} added new blocked VPN host: {1}", Global.Account.Name, hostname);
            Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, str);
            return RedirectToAction("BlockedVPNs");
        }
        public ActionResult Detail(int id)
        {
            var db = new ZkDataContext();
            var mission = db.Missions.Single(x => x.MissionID == id);
            mission.ForumThread.UpdateLastRead(Global.AccountID, false);
            db.SaveChanges();

            return View("Detail",
                        new MissionDetailData
                        {
                            Mission = mission,
                            TopScores = mission.MissionScores.Where(x=> x.Score > 0).OrderByDescending(x => x.Score).AsQueryable(),
                            MyRating = mission.Ratings.SingleOrDefault(x => x.AccountID == Global.AccountID) ?? new Rating(),
                        });
        }
 /// <summary>
 ///     Set the last post time of the thread to current time (includes edits)
 /// </summary>
 void ResetThreadLastPostTime(int threadID) {
     var db = new ZkDataContext();
     var thread = db.ForumThreads.FirstOrDefault(x => x.ForumThreadID == threadID);
     var lastPost = thread.Created;
     foreach (var p in thread.ForumPosts.Reverse())
     {
         if (p.ForumPostEdits.Count > 0)
         {
             var lastEdit = p.ForumPostEdits.Last().EditTime;
             if (lastEdit > lastPost) lastPost = lastEdit;
         } else if (p.Created > lastPost) lastPost = p.Created;
     }
     thread.LastPost = lastPost;
     db.SaveChanges();
 }
        public ActionResult ChangeAccountDeleted(int accountID, bool isDeleted)
        {
            var db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == accountID);

            if (acc.IsDeleted != isDeleted)
            {
                Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format("Account {0} {1} deletion status changed by {2}", acc.Name, Url.Action("Detail", "Users", new { id = acc.AccountID }, "http"), Global.Account.Name));
                Global.Server.GhostChanSay(GlobalConst.ModeratorChannel, string.Format(" - {0} -> {1}", acc.IsDeleted, isDeleted));
                acc.IsDeleted = isDeleted;
            }
            db.SaveChanges();

            return RedirectToAction("Detail", "Users", new { id = acc.AccountID });
        }     
        //
        // GET: /Battles/

        /// <summary>
        ///     Returns the page of the <see cref="SpringBattle" /> with the specified ID
        /// </summary>
        public ActionResult Detail(int id, bool showWinners = false) {
            var db = new ZkDataContext();
            ViewBag.ShowWinners = showWinners;
            var bat = db.SpringBattles.FirstOrDefault(x => x.SpringBattleID == id);
            if (bat == null) return Content("No such battle exists");

            if (bat.ForumThread != null)
            {
                bat.ForumThread.UpdateLastRead(Global.AccountID, false);
                db.SaveChanges();
            }

            if (Global.AccountID != 0 && !showWinners && bat.SpringBattlePlayers.Any(y => y.AccountID == Global.AccountID && !y.IsSpectator)) ViewBag.ShowWinners = true; // show winners if player played thatbattle

            return View("BattleDetail", bat);
        }
 int GetWordID(string word) {
     int id;
     if (wordIDs.TryGetValue(word, out id)) return id;
     using (var db = new ZkDataContext())
     {
         var entry = db.IndexWords.FirstOrDefault(x => x.Text == word);
         if (entry == null)
         {
             entry = new Word { Text = word };
             db.IndexWords.Add(entry);
             db.SaveChanges();
         }
         wordIDs[entry.Text] = entry.WordID;
         return entry.WordID;
     }
 }
        public void IndexPost(ForumPost post) {
            var words = parser.Parse(post.Text)
                    .Where(x => x is LiteralTag && x.Text?.Length < 100)
                    .Select(x => SanitizeWord(x.Text))
                    .Where(x => !string.IsNullOrEmpty(x))
                    .ToList();

            using (var db = new ZkDataContext())
            {
                var dbPost = db.ForumPosts.Find(post.ForumPostID);
                dbPost.ForumPostWords.Clear();

                foreach (var grp in words.GroupBy(x => x)) dbPost.ForumPostWords.Add(new ForumPostWord { Count = grp.Count(), WordID = GetWordID(grp.Key) });
                db.SaveChanges();
            }
        }
 public async Task SendMissedMessages(ICommandSender sender, SayPlace place, string target, int accountID, int maxCount = OfflineMessageResendCount)
 {
     using (var db = new ZkDataContext()) {
         var acc = await db.Accounts.FindAsync(accountID);
         await
             db.LobbyChatHistories.Where(x => x.Target == target && x.SayPlace == place && x.Time >= acc.LastLogout)
                 .OrderByDescending(x => x.Time)
                 .Take(maxCount)
                 .OrderBy(x => x.Time)
                 .ForEachAsync(async (chatHistory) => { await sender.SendCommand(chatHistory.ToSay()); });
         
         if (place == SayPlace.User) { // don't keep PMs longer than needed
             db.LobbyChatHistories.DeleteAllOnSubmit(db.LobbyChatHistories.Where(x => x.Target == target && x.SayPlace == SayPlace.User).ToList());
             db.SaveChanges();
         }
     }
 }
		protected void lqResources_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
		{
			e.Cancel = true;
			if ((bool?)Session["login"] == true) {
				var db = new ZkDataContext();
				var todel = db.Resources.Single(x=>x.InternalName == ((Resource)e.OriginalObject).InternalName);
        PlasmaServer.RemoveResourceFiles(todel);

				
				db.Resources.DeleteOnSubmit(todel);
			    db.SaveChanges();

			    MessageBox.Show("Deleted " +  todel.InternalName);
        
			} else {
				MessageBox.Show("Not logged in");
			}
		}
		public void DeleteMission(int missionID, string author, string password)
		{
			var db = new ZkDataContext();
			var prev = db.Missions.Where(x => x.MissionID == missionID).SingleOrDefault();
			if (prev != null)
			{
				var acc = AuthServiceClient.VerifyAccountPlain(author, password);
                if (acc == null)
                {
                    Trace.TraceWarning("Invalid login attempt for {0}", author);
                    System.Threading.Thread.Sleep(new Random().Next(2000));
                    throw new ApplicationException("Cannot verify user account");
                }
                if (acc.AccountID != prev.AccountID && !acc.IsZeroKAdmin) throw new ApplicationException("You cannot delete a mission from an other user");
				prev.IsDeleted = true;
			    db.SaveChanges();
			}
			else throw new ApplicationException("No such mission found");
		}
        private static void ProcessElos(Spring.SpringBattleContext result, ZkLobbyServer.ZkLobbyServer server, ZkDataContext db, SpringBattle sb)
        {
            bool noElo = result.OutputExtras.Any(x => x?.StartsWith("noElo", true, System.Globalization.CultureInfo.CurrentCulture) == true);

            Dictionary<int, int> orgLevels = sb.SpringBattlePlayers.Select(x => x.Account).ToDictionary(x => x.AccountID, x => x.Level);

            sb.CalculateAllElo(noElo);
            foreach (var u in sb.SpringBattlePlayers.Where(x => !x.IsSpectator)) u.Account.CheckLevelUp();

            db.SaveChanges();

            try
            {
                foreach (Account a in sb.SpringBattlePlayers.Where(x => !x.IsSpectator).Select(x => x.Account)) server.PublishAccountUpdate(a);
            }
            catch (Exception ex)
            {
                Trace.TraceError("error updating extension data: {0}", ex);
            }

            foreach (Account account in sb.SpringBattlePlayers.Select(x => x.Account))
            {
                if (account.Level > orgLevels[account.AccountID])
                {
                    try
                    {
                        string message = string.Format("Congratulations {0}! You just leveled up to level {1}. {3}/Users/Detail/{2}",
                            account.Name,
                            account.Level,
                            account.AccountID,
                            GlobalConst.BaseSiteUrl);
                        //text.AppendLine(message);
                        server.GhostPm(account.Name, message);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Error sending level up lobby message: {0}", ex);
                    }
                }
            }
        }
        public ActionResult Index(int? campaignID = null)
        {
            var db = new ZkDataContext();

            Campaign camp;
            if (campaignID != null) camp = db.Campaigns.Single(x => x.CampaignID == campaignID);
            else camp = db.Campaigns.Single(x => x.CampaignID == 1);
            string cachePath = Server.MapPath(string.Format("/img/galaxies/campaign/render_{0}.jpg", camp.CampaignID));
            // /*
            if (camp.IsDirty || !System.IO.File.Exists(cachePath)) {
                using (Bitmap im = GenerateGalaxyImage(camp.CampaignID)) {
                    im.SaveJpeg(cachePath, 85);
                    camp.IsDirty = false;
                    camp.MapWidth = im.Width;
                    camp.MapHeight = im.Height;
                    db.SaveChanges();
                }
            }
            // */
            return View("CampaignMap", camp);
        }
		protected void lqContentFiles_Deleting(object sender, LinqDataSourceDeleteEventArgs e)
		{
			e.Cancel = true;
			if ((bool?)Session["login"] == true)
			{
				var db = new ZkDataContext();
				var todel = db.ResourceContentFiles.Single(x => x.Md5 == ((ResourceContentFile)e.OriginalObject).Md5);
				Utils.SafeDelete(PlasmaServer.GetTorrentPath(todel));

				db.ResourceContentFiles.DeleteOnSubmit(todel);
			    db.SaveChanges();

			    MessageBox.Show("Deleted " + todel.FileName);

			}
			else
			{
				MessageBox.Show("Not logged in");
			}

		}
예제 #31
0
        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);
            }
        }