public static void GenerateTechs()
        {
            var db = new ZkDataContext();
            db.StructureTypes.DeleteAllOnSubmit(db.StructureTypes.Where(x => x.Unlock != null));
            db.SubmitAndMergeChanges();

            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.SubmitAndMergeChanges();

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

            return Content(string.Format("Thank you!! {0} Kudos have been added to your account {1}", contrib.KudosValue, contrib.AccountByAccountID.Name));
        }
        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 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.SubmitAndMergeChanges();
     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 Faction PerformLeaveFaction(int accountID, bool keepClan = false, ZkDataContext db = null)
        {
            if (db == null) db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            Faction faction = acc.Faction;

            if (!keepClan && acc.Clan != null) ClansController.PerformLeaveClan(Global.AccountID);
            db.AccountRoles.DeleteAllOnSubmit(acc.AccountRolesByAccountID.Where(x => !keepClan || x.ClanID == null));
            acc.ResetQuotas();

            foreach (var ps in acc.PlanetStructures)
            {
                ps.OwnerAccountID = null;
            }

            foreach (var planet in acc.Planets)
            {
                planet.OwnerAccountID = null;
            }

            // delete channel subscription
            if (true)   //(!acc.IsZeroKAdmin)
            {
                var channelSub = db.LobbyChannelSubscriptions.FirstOrDefault(x => x.AccountID == acc.AccountID && x.Channel == acc.Faction.Name);
                if (channelSub != null) db.LobbyChannelSubscriptions.DeleteOnSubmit(channelSub);
            }

            db.Events.InsertOnSubmit(Global.CreateEvent("{0} leaves faction {1}", acc, acc.Faction));
            db.SubmitChanges();
            PlanetwarsController.SetPlanetOwners(db);


            using (var db2 = new ZkDataContext())
            {
                Account acc2 = db2.Accounts.Single(x => x.AccountID == Global.AccountID);
                acc2.FactionID = null;
                db2.SubmitAndMergeChanges();

                PlanetwarsController.SetPlanetOwners(db2);
            }
            return faction;
        }
 public void ImportIpnPayment(NameValueCollection values, byte[] rawRequest) {
     try {
         var parsed = ParseIpn(values);
         var contribution = AddPayPalContribution(parsed);
         var verified = VerifyRequest(rawRequest);
         if (contribution != null && !verified) {
             Error(
                 string.Format(
                     "Warning, transaction {0} by {1} VERIFICATION FAILED, check that it is not a fake! {2}/Contributions ",
                     parsed.TransactionID,
                     parsed.Name,
                     GlobalConst.BaseSiteUrl));
             using (var db = new ZkDataContext()) {
                 db.Contributions.First(x => x.ContributionID == contribution.ContributionID).Comment = "VERIFICATION FAILED";
                 db.SubmitAndMergeChanges();
             }
         }
     } catch (Exception ex) {
         Trace.TraceError(ex.ToString());
         Error(ex.ToString());
     }
 }
        public static Faction PerformLeaveFaction(int accountID, bool keepClan = false, ZkDataContext db = null)
        {
            if (db == null) db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            Faction faction = acc.Faction;

            if (!keepClan && acc.Clan != null) ClansController.PerformLeaveClan(Global.AccountID);
            db.AccountRoles.DeleteAllOnSubmit(acc.AccountRolesByAccountID.Where(x => !keepClan || x.ClanID == null).ToList());
            acc.ResetQuotas();

            foreach (var ps in acc.PlanetStructures)
            {
                ps.OwnerAccountID = null;
            }

            foreach (var planet in acc.Planets)
            {
                planet.OwnerAccountID = null;
            }


            db.Events.InsertOnSubmit(Global.CreateEvent("{0} leaves faction {1}", acc, acc.Faction));
            db.SubmitChanges();
            PlanetwarsController.SetPlanetOwners(db);


            using (var db2 = new ZkDataContext())
            {
                Account acc2 = db2.Accounts.Single(x => x.AccountID == Global.AccountID);
                acc2.FactionID = null;
                db2.SubmitAndMergeChanges();

                PlanetwarsController.SetPlanetOwners(db2);
            }
            return faction;
        }
Example #9
0
 public void ImportIpnPayment(NameValueCollection values, byte[] rawRequest)
 {
     try {
         var parsed       = ParseIpn(values);
         var contribution = AddPayPalContribution(parsed);
         var verified     = VerifyRequest(rawRequest);
         if (contribution != null && !verified)
         {
             Error(
                 string.Format(
                     "Warning, transaction {0} by {1} VERIFICATION FAILED, check that it is not a fake! {2}/Contributions ",
                     parsed.TransactionID,
                     parsed.Name,
                     GlobalConst.BaseSiteUrl));
             using (var db = new ZkDataContext()) {
                 db.Contributions.First(x => x.ContributionID == contribution.ContributionID).Comment = "VERIFICATION FAILED";
                 db.SubmitAndMergeChanges();
             }
         }
     } catch (Exception ex) {
         Trace.TraceError(ex.ToString());
         Error(ex.ToString());
     }
 }
        public ActionResult CounterProposal(int id) {
            var db = new ZkDataContext();
            var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id);
            var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            if (treaty.CanCancel(acc) && treaty.TreatyState == TreatyState.Proposed) {
                treaty.FactionByAcceptingFactionID = treaty.AcceptingFactionID == acc.FactionID
                                                         ? treaty.FactionByProposingFactionID
                                                         : treaty.FactionByAcceptingFactionID;
                treaty.AccountByProposingAccountID = acc;
                treaty.FactionByProposingFactionID = acc.Faction;
                treaty.TreatyState = TreatyState.Invalid;
                db.Events.InsertOnSubmit(Global.CreateEvent("{0} modified treaty proposal {1} between {2} and {3}", acc, treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID));
                db.SubmitAndMergeChanges();
               
                return View("FactionTreatyDefinition", treaty);

            }
            return Content("Not permitted");
        }
        public ActionResult AcceptTreaty(int id) {
            var db = new ZkDataContext();
            var treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == id);
            var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            if (treaty.CanAccept(acc) && treaty.ProcessTrade(true)) {
                treaty.AcceptedAccountID = acc.AccountID;
                treaty.TreatyState = TreatyState.Accepted;
                db.Events.InsertOnSubmit(Global.CreateEvent("Treaty {0} between {1} and {2} accepted by {3}", treaty, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, acc));
                db.SubmitAndMergeChanges();


                return RedirectToAction("Detail", new { id = Global.FactionID });
            }
            return Content("Cannot cancel");

        }
        public ActionResult SubmitCreate(Clan clan, HttpPostedFileBase image, HttpPostedFileBase bgimage, bool noFaction = false)
        {
            //using (var scope = new TransactionScope())
            //{
            ZkDataContext db = new ZkDataContext();
            bool created = clan.ClanID == 0; // existing clan vs creation

            //return Content(noFaction ? "true":"false");
            if (noFaction) clan.FactionID = null;

            var new_faction = db.Factions.SingleOrDefault(x => x.FactionID == clan.FactionID);
            if ((new_faction != null) && new_faction.IsDeleted) return Content("Cannot create clans in deleted factions");

            Clan orgClan = null;

            if (!created)
            {
                if (!Global.Account.HasClanRight(x => x.RightEditTexts) || clan.ClanID != Global.Account.ClanID) return Content("Unauthorized");
                orgClan = db.Clans.Single(x => x.ClanID == clan.ClanID);
                orgClan.ClanName = clan.ClanName;
                orgClan.Shortcut = clan.Shortcut;
                orgClan.Description = clan.Description;
                orgClan.SecretTopic = clan.SecretTopic;
                orgClan.Password = clan.Password;
            }
            else
            {
                if (Global.Clan != null) return Content("You already have a clan");
                // should just change their faction for them?
                if (Global.FactionID != 0 && Global.FactionID != clan.FactionID) return Content("Clan must belong to same faction you are in");
            }
            if (string.IsNullOrEmpty(clan.ClanName) || string.IsNullOrEmpty(clan.Shortcut)) return Content("Name and shortcut cannot be empty!");
            if (!ZkData.Clan.IsShortcutValid(clan.Shortcut)) return Content("Shortcut must have at least 1 characters and contain only numbers and letters");

            // check if our name or shortcut conflicts with existing clans
            // if so, allow us to create a new clan over it if it's a deleted clan, else block action
            var existingClans = db.Clans.Where(x => ((SqlFunctions.PatIndex(clan.Shortcut,x.Shortcut) > 0 || SqlFunctions.PatIndex(clan.ClanName, x.ClanName) > 0) && x.ClanID != clan.ClanID));
            if (existingClans.Count() > 0)
            {
                if (existingClans.Any(x => !x.IsDeleted)) return Content("Clan with this shortcut or name already exists");
                if (created)
                {
                    Clan deadClan = existingClans.First();
                    clan = deadClan;
                    if (noFaction) clan.FactionID = null;
                }
            }
            else if (created) db.Clans.InsertOnSubmit(clan);

            if (created && (image == null || image.ContentLength == 0)) return Content("A clan image is required");
            if (image != null && image.ContentLength > 0)
            {
                var im = Image.FromStream(image.InputStream);
                if (im.Width != 64 || im.Height != 64) im = im.GetResized(64, 64);
                db.SubmitChanges(); // needed to get clan id for image url - stupid way really
                im.Save(Server.MapPath(clan.GetImageUrl()));
            }
            if (bgimage != null && bgimage.ContentLength > 0)
            {
                var im = Image.FromStream(bgimage.InputStream);
                db.SubmitChanges(); // needed to get clan id for image url - stupid way really
                // DW - Actually its not stupid, its required to enforce locking.
                // It would be possbile to enforce a pre-save id
                im.Save(Server.MapPath(clan.GetBGImageUrl()));
            }
            db.SubmitChanges();

            if (created) // we created a new clan, set self as founder and rights
            {
                var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
                acc.ClanID = clan.ClanID;

                var leader = db.RoleTypes.FirstOrDefault(x => x.RightKickPeople && x.IsClanOnly);
                if (leader != null)
                    db.AccountRoles.InsertOnSubmit(new AccountRole()
                    {
                        AccountID = acc.AccountID,
                        Clan = clan,
                        RoleType = leader,
                        Inauguration = DateTime.UtcNow
                    });

                db.Events.InsertOnSubmit(Global.CreateEvent("New clan {0} formed by {1}", clan, acc));
            }
            else
            {
                if (clan.FactionID != orgClan.FactionID)   // set factions of members
                {
                    var originalID = orgClan.FactionID;
                    orgClan.FactionID = clan.FactionID;     // <- not possible to change faction // now it is!
                    if (orgClan.Faction != null && orgClan.Faction.IsDeleted)
                    {
                        orgClan.FactionID = originalID;
                        throw new ApplicationException("You cannot join deleted faction");
                    }
                    db.Events.InsertOnSubmit(Global.CreateEvent("Clan {0} moved to faction {1}", clan, orgClan.Faction));

                    db.SubmitAndMergeChanges();

                    foreach (Account member in orgClan.Accounts)
                    {
                        if (member.FactionID != clan.FactionID && member.FactionID != null)
                        {
                            FactionsController.PerformLeaveFaction(member.AccountID, true, db);
                        }
                        member.Faction = orgClan.Faction;
                    }
                }
            }

            db.SubmitChanges();
            //scope.Complete();
            Global.Nightwatch.Tas.AdminSetTopic(clan.GetClanChannel(), clan.SecretTopic);
            Global.Nightwatch.Tas.AdminSetChannelPassword(clan.GetClanChannel(), clan.Password);
            //}
            return RedirectToAction("Detail", new { id = clan.ClanID });
        }
        /// <summary>
        /// Create or modify a PlanetWars <see cref="FactionTreaty"/>
        /// </summary>
        /// <param name="factionTreatyID">Existing <see cref="FactionTreaty"/> ID, if modifying one</param>
        /// <param name="turns">How long the treaty lasts</param>
        /// <param name="acceptingFactionID"></param>
        /// <param name="effectTypeID"><see cref="TreatyEffect"/> to add or remove, if applicable</param>
        /// <param name="effectValue"></param>
        /// <param name="planetID">Specifies the <see cref="Planet"/> for planet-based effects</param>
        /// <param name="isReverse"></param>
        /// <param name="note">Diplomatic note readable by both parties, to better communicate their intentions</param>
        /// <param name="add">If not null or empty, add the specified <see cref="TreatyEffect"/></param>
        /// <param name="delete">Delete the specified <see cref="TreatyEffect"/>?</param>
        /// <param name="propose">If not null or empty, this is a newly proposed treaty</param>
        /// <returns></returns>
        public ActionResult ModifyTreaty(int factionTreatyID,
                                         int? turns,
                                         int? acceptingFactionID,
                                         int? effectTypeID,
                                         double? effectValue,
                                         int? planetID,
                                         bool? isReverse,
                                         string note,
                                         string add,int? delete,string propose) {
            if (!Global.Account.HasFactionRight(x => x.RightDiplomacy)) return Content("Not a diplomat!");

            FactionTreaty treaty;

            // submit, store treaty in db 
            var db = new ZkDataContext();

            if (factionTreatyID > 0) {
                treaty = db.FactionTreaties.Single(x => x.FactionTreatyID == factionTreatyID);
                if (treaty.TreatyState != TreatyState.Invalid) return Content("Treaty already in progress!");
            }
            else {
                treaty = new FactionTreaty();
                db.FactionTreaties.InsertOnSubmit(treaty);
                treaty.FactionByAcceptingFactionID = db.Factions.Single(x => x.FactionID == acceptingFactionID);
            }
            treaty.AccountByProposingAccountID = db.Accounts.Find(Global.AccountID);
            treaty.FactionByProposingFactionID = db.Factions.Single(x => x.FactionID == Global.FactionID);
            treaty.TurnsRemaining = turns;
            treaty.TurnsTotal = turns;
            treaty.TreatyNote = note;
            

            if (!string.IsNullOrEmpty(add)) {
                TreatyEffectType effectType = db.TreatyEffectTypes.Single(x => x.EffectTypeID == effectTypeID);
                var effect = new TreatyEffect
                             {
                                 FactionByGivingFactionID = isReverse == true ? treaty.FactionByAcceptingFactionID : treaty.FactionByProposingFactionID,
                                 FactionByReceivingFactionID = 
                                     isReverse == true ? treaty.FactionByProposingFactionID : treaty.FactionByAcceptingFactionID,
                                 TreatyEffectType = effectType,
                                 FactionTreaty = treaty
                             };
                if (effectType.HasValue) {
                    if (effectType.MinValue.HasValue && effectValue < effectType.MinValue.Value) effectValue = effectType.MinValue;
                    if (effectType.MaxValue.HasValue && effectValue > effectType.MaxValue.Value) effectValue = effectType.MaxValue;
                }
                if (effectType.HasValue) effect.Value = effectValue;
                if (effectType.IsPlanetBased) effect.PlanetID = planetID.Value;
                db.TreatyEffects.InsertOnSubmit(effect);
            }
            if (delete != null) {
                db.TreatyEffects.DeleteOnSubmit(db.TreatyEffects.Single(x=>x.TreatyEffectID == delete));
            }
            db.SubmitAndMergeChanges();

            if (!string.IsNullOrEmpty(propose)) {
                treaty.TreatyState = TreatyState.Proposed;
                
                db.Events.InsertOnSubmit(Global.CreateEvent("{0} proposes a new treaty between {1} and {2} - {3}",treaty.AccountByProposingAccountID, treaty.FactionByProposingFactionID, treaty.FactionByAcceptingFactionID, treaty));

                db.SubmitAndMergeChanges();
                return RedirectToAction("Detail", new { id = treaty.ProposingFactionID});
            }

            return View("FactionTreatyDefinition", treaty);
        }
        public ActionResult RemovePunishment(int punishmentID) {
            var db = new ZkDataContext();
            var todel = db.Punishments.First(x => x.PunishmentID == punishmentID);
            db.Punishments.DeleteOnSubmit(todel);
            db.SubmitAndMergeChanges();

            Account acc = todel.AccountByAccountID;
            string punisherName = "<unknown>";
            if (todel.CreatedAccountID != null)
            {
                Account adminAcc = db.Accounts.Find((int)todel.CreatedAccountID);
                punisherName = adminAcc.Name;
            }
            Global.Nightwatch.Tas.Say(SayPlace.Channel, AuthService.ModeratorChannel, string.Format("{0} removed a punishment given by {1} ", Global.Account.Name, punisherName), true);
            Global.Nightwatch.Tas.Say(SayPlace.Channel, AuthService.ModeratorChannel, string.Format("to {0} for: {1} ", acc.Name, todel.Reason), true);

            return RedirectToAction("Detail", "Users", new { id = todel.AccountID });
        }
Example #15
0
 public static void RecalculateKudos()
 {
     var db = new ZkDataContext();
     foreach (var acc in db.Accounts.Where(x => x.KudosPurchases.Any() || x.ContributionsByAccountID.Any())) acc.Kudos = acc.KudosGained - acc.KudosSpent;
     db.SubmitAndMergeChanges();
 }
Example #16
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.SubmitAndMergeChanges();

                    if (acc != null)
                    {
                        acc.Kudos = acc.KudosGained - acc.KudosSpent;
                    }
                    db.SubmitAndMergeChanges();


                    // 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);
            }
        }
 public ActionResult RecallRole(int accountID, int roletypeID)
 {
     var db = new ZkDataContext();
     Account targetAccount = db.Accounts.Single(x => x.AccountID == accountID);
     Account myAccount = db.Accounts.Single(x => x.AccountID == Global.AccountID);
     RoleType role = db.RoleTypes.Single(x => x.RoleTypeID == roletypeID);
     if (myAccount.CanRecall(targetAccount, role))
     {
         db.AccountRoles.DeleteAllOnSubmit(db.AccountRoles.Where(x => x.AccountID == accountID && x.RoleTypeID == roletypeID));
         db.Events.InsertOnSubmit(Global.CreateEvent("{0} was recalled from the {1} role of {2} by {3}",
                                                     targetAccount,
                                                     role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction,
                                                     role,
                                                     myAccount));
         AuthServiceClient.SendLobbyMessage(targetAccount,
                                            string.Format("You were recalled from the function of {0} by {1}", role.Name, myAccount.Name));
         db.SubmitAndMergeChanges();
         return RedirectToAction("Detail", "Users", new { id = accountID });
     }
     else return Content("Cannot recall");
 }
        public ActionResult ActivateTargetedStructure(int planetID, int structureTypeID)
        {
            //This call is never to be called before/outside of SetStructureTarget
            var db = new ZkDataContext();
            //Get the pre-set target planet ID
            PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID);
            int targetID = structure.TargetPlanetID ?? -1;
            if (targetID == -1) return Content("Structure has no target");

            if (!structure.IsActive) return Content(String.Format("Structure {0} is inactive", structure.StructureType.Name));

            ActionResult ret = null;
            if (structure.StructureType.EffectCreateLink == true)
            {
                ret = CreateLink(planetID, structureTypeID, targetID);
            }
            if (ret != null) return ret;    // exit with message if error occurs
            if (structure.StructureType.EffectChangePlanetMap == true)
            {
                ret = ChangePlanetMap(planetID, structureTypeID, targetID, null);
            }
            if (ret != null) return ret;    // exit with message if error occurs

            if (structure.StructureType.EffectPlanetBuster == true)
            {
                ret = FirePlanetBuster(planetID, structureTypeID, targetID);
            }
            if (ret != null) return ret;    // exit with message if error occurs
            if (structure.StructureType.IsSingleUse)    // single-use structure, remove
            {
                db.PlanetStructures.DeleteOnSubmit(structure);
            }

            db.SubmitAndMergeChanges();
            SetPlanetOwners(db);    //this is needed for the buster to update ownership after planet destruction

            if (ret != null) return ret;
            return RedirectToAction("Planet", new { id = planetID });
        }
        public ActionResult CreateLink(int planetID, int structureTypeID, int targetID)
        {
            var db = new ZkDataContext();

            PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID);
            Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID);
            Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID);

            // warp jammers protect against link creation
            //var warpDefense = target.PlanetStructures.Where(x => x.StructureType.EffectBlocksJumpgate == true).ToList();
            //if (warpDefense.Count > 0) return Content("Warp jamming prevents link creation");

            if (source.GalaxyID != target.GalaxyID) return Content("Cannot form exo-galaxy link");

            db.Links.InsertOnSubmit(new Link { PlanetID1 = source.PlanetID, PlanetID2 = target.PlanetID, GalaxyID = source.GalaxyID });
            db.Events.InsertOnSubmit(Global.CreateEvent("A new link was created between {0} planet {1} and {2} planet {3} by the {4}", source.Faction, source, target.Faction, target, structure.StructureType));
            db.SubmitAndMergeChanges();
            return null;
        }
        public ActionResult SetStructureTarget(int planetID, int structureTypeID, int targetPlanetID)
        {
            var db = new ZkDataContext();
            var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            var planet = db.Planets.Single(x => x.PlanetID == planetID);
            var structure = planet.PlanetStructures.Single(x => x.StructureTypeID == structureTypeID);
            if (!acc.CanSetStructureTarget(structure)) return Content("Cannot set target");
            var target = db.Planets.Single(x => x.PlanetID == targetPlanetID);
            if (target != structure.PlanetByTargetPlanetID)
            {
                structure.IsActive = false; // deactivate on target change
                structure.ActivatedOnTurn = null;
            }
            structure.PlanetByTargetPlanetID = target;
            db.Events.InsertOnSubmit(Global.CreateEvent("{0} of {1} aimed {2} located at {3} to {4} planet {5}", acc, acc.Faction, structure.StructureType, planet, target.Faction, target));

            if (structure.IsActive && !structure.StructureType.IsSingleUse) return ActivateTargetedStructure(planetID, structureTypeID);

            db.SubmitAndMergeChanges();
            return RedirectToAction("Planet", new { id = planet.PlanetID });
        }
 public ActionResult SetEnergyPriority(int planetID, int structuretypeID, EnergyPriority priority)
 {
     var db = new ZkDataContext();
     var acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
     var planet = db.Planets.Single(x => x.PlanetID == planetID);
     var structure = planet.PlanetStructures.Single(x => x.StructureTypeID == structuretypeID);
     if (!acc.CanSetPriority(structure)) return Content("Cannot set priority");
     structure.EnergyPriority = priority;
     db.Events.InsertOnSubmit(Global.CreateEvent("{0} changed energy priority of {1} on {2} to {3}", acc, structure.StructureType, planet, priority));
     db.SubmitAndMergeChanges();
     return RedirectToAction("Planet", new { id = planet.PlanetID });
 }
 public ActionResult AppointRole(int accountID, int roletypeID)
 {
     var db = new ZkDataContext();
     Account targetAccount = db.Accounts.Single(x => x.AccountID == accountID);
     Account myAccount = db.Accounts.Single(x => x.AccountID == Global.AccountID);
     RoleType role = db.RoleTypes.Single(x => x.RoleTypeID == roletypeID);
     if (myAccount.CanAppoint(targetAccount, role))
     {
         Account previous = null;
         if (role.IsOnePersonOnly)
         {
             List<AccountRole> entries =
                 db.AccountRoles.Where(
                 x => x.RoleTypeID == role.RoleTypeID && (role.IsClanOnly ? x.ClanID == myAccount.ClanID : x.FactionID == myAccount.FactionID)).ToList();
             if (entries.Any())
             {
                 previous = entries.First().Account;
                 db.AccountRoles.DeleteAllOnSubmit(entries);
             }
         }
         var entry = new AccountRole
                     {
                         AccountID = accountID,
                         Inauguration = DateTime.UtcNow,
                         Clan = role.IsClanOnly ? myAccount.Clan : null,
                         Faction = !role.IsClanOnly ? myAccount.Faction : null,
                         RoleTypeID = roletypeID,
                     };
         db.AccountRoles.InsertOnSubmit(entry);
         if (previous != null)
         {
             db.Events.InsertOnSubmit(Global.CreateEvent("{0} was appointed to the {1} role of {2} by {3} - replacing {4}",
                                                         targetAccount,
                                                         role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction,
                                                         role,
                                                         myAccount,
                                                         previous));
         }
         else
         {
             db.Events.InsertOnSubmit(Global.CreateEvent("{0} was appointed to the {1} role of {2} by {3}",
                                                         targetAccount,
                                                         role.IsClanOnly ? (object)myAccount.Clan : myAccount.Faction,
                                                         role,
                                                         myAccount));
         }
         AuthServiceClient.SendLobbyMessage(targetAccount,
                                            string.Format("You were appointed for the function of {0} by {1}", role.Name, myAccount.Name));
         db.SubmitAndMergeChanges();
         return RedirectToAction("Detail", "Users", new { id = accountID });
     }
     else return Content("Cannot recall");
 }
 /// <summary>
 /// Set faction secret topic (applied to lobby channel as well)
 /// </summary>
 public ActionResult SetTopic(int factionID, string secretTopic) {
     var db = new ZkDataContext();
     var fac = db.Factions.Single(x => x.FactionID == factionID);
     if (Global.Account.FactionID == fac.FactionID && Global.Account.HasFactionRight(x=>x.RightEditTexts)) {
         fac.SecretTopic = secretTopic;
         db.SubmitAndMergeChanges();
         Global.Server.SetTopic(fac.Shortcut,secretTopic, Global.Account.Name);
         return RedirectToAction("Detail", new { id = fac.FactionID });
     }
     return Content("Denied");
 }
        public static void AutoClosePolls()
        {
            var db = new ZkDataContext();
            foreach (var p in db.Polls.Where(x => x.IsHeadline && x.ExpireBy != null && x.ExpireBy < DateTime.UtcNow && x.RoleTypeID != null).ToList())
            {
                var yes = p.PollVotes.Count(x => x.PollOption.OptionText == "Yes");
                var no = p.PollVotes.Count(x => x.PollOption.OptionText == "No");
                var acc = p.AccountByRoleTargetAccountID;
                if (yes > no)
                {
                    if (p.RoleIsRemoval)
                    {
                        var toDelete = db.AccountRoles.Where(x => x.AccountID == acc.AccountID && x.RoleTypeID == p.RoleTypeID);
                        db.AccountRoles.DeleteAllOnSubmit(toDelete);
                        db.Events.InsertOnSubmit(Global.CreateEvent("{0} was removed from the {1} role of {2} by a vote - {3} for, {4} against", acc, (object)p.Clan ?? p.Faction, p.RoleType, yes, no));

                        db.SubmitAndMergeChanges();

                        AuthServiceClient.SendLobbyMessage(acc, string.Format("You were recalled from the function of {0} by a vote", p.RoleType.Name));
                    }
                    else
                    {
                        if (!acc.AccountRolesByAccountID.Any(x => x.RoleTypeID == p.RoleTypeID))
                        {
                            Account previous = null;
                            if (p.RoleType.IsOnePersonOnly)
                            {
                                var entries = db.AccountRoles.Where(x => x.RoleTypeID == p.RoleTypeID && (p.RoleType.IsClanOnly ? x.ClanID == p.RestrictClanID : x.FactionID == p.RestrictFactionID)).ToList();

                                if (entries.Any())
                                {
                                    previous = entries.First().Account;
                                    db.AccountRoles.DeleteAllOnSubmit(entries);
                                    db.SubmitAndMergeChanges();
                                }
                            }

                            var entry = new AccountRole()
                                        {
                                            Account = acc,
                                            Inauguration = DateTime.UtcNow,
                                            Clan = p.Clan,
                                            Faction = p.Faction,
                                            RoleType = p.RoleType
                                        };
                            acc.AccountRolesByAccountID.Add(entry);
                            if (previous == null)
                                db.Events.InsertOnSubmit(Global.CreateEvent("{0} was elected for the {1} role of {2} by a vote - {3} for, {4} against",
                                                   acc,
                                                   (object)p.Clan ?? p.Faction,
                                                   p.RoleType,
                                                   yes,
                                                   no));

                            else db.Events.InsertOnSubmit(Global.CreateEvent("{0} was elected for the {1} role of {2} by a vote, replacing {3} - {4} for, {5} against",
                                                   acc,
                                                   (object)p.Clan ?? p.Faction,
                                                   p.RoleType,
                                                   previous,
                                                   yes,
                                                   no));

                            AuthServiceClient.SendLobbyMessage(acc, string.Format("Congratulations!! You were elected into a function of {0} by a vote", p.RoleType.Name));
                        }
                    }
                }

                p.IsHeadline = false;
                db.Polls.DeleteOnSubmit(p);
            }
            db.SubmitAndMergeChanges();
        }
 public static void AddClanLeader()
 {
     var db = new ZkDataContext();
     var role = db.RoleTypes.First(x => x.IsClanOnly);
     foreach (var clan in db.Clans.Where(x => !x.IsDeleted))
     {
         if (!clan.AccountRoles.Any(y => y.RoleType.IsClanOnly))
         {
             var picked = clan.Accounts.Where(x => x.LastLogin >= DateTime.UtcNow.AddDays(-7)).OrderByDescending(x => x.Level).FirstOrDefault();
             if (picked == null) clan.Accounts.OrderByDescending(x => x.LastLogin).FirstOrDefault();
             if (picked != null)
             {
                 clan.AccountRoles.Add(new AccountRole()
                 {
                     AccountID = picked.AccountID,
                     ClanID = clan.ClanID,
                     Inauguration = DateTime.UtcNow,
                     RoleTypeID = role.RoleTypeID
                 });
             }
         }
     }
     db.SubmitAndMergeChanges();
 }
        public ActionResult BombPlanet(int planetID, int count, bool? useWarp)
        {
            var db = new ZkDataContext();
            Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            if (acc.Faction == null) return Content("Join some faction first");
            Planet planet = db.Planets.Single(x => x.PlanetID == planetID);
            bool accessible = (useWarp == true) ? planet.CanBombersWarp(acc.Faction) : planet.CanBombersAttack(acc.Faction);
            if (!accessible) return Content("You cannot attack here");
            if (Global.Nightwatch.GetPlanetBattles(planet).Any(x => x.IsInGame)) return Content("Battle in progress on the planet, cannot bomb planet");

            bool selfbomb = acc.FactionID == planet.OwnerFactionID;
            if (count < 0) count = 0;
            double avail = Math.Min(count, acc.GetBombersAvailable());
            if (useWarp == true) avail = Math.Min(acc.GetWarpAvailable(), avail);

            var capa = acc.GetBomberCapacity();
            if (avail > capa) return Content("Too many bombers, increase bomber fleet size capacity");

            if (avail > 0)
            {
                double defense = planet.PlanetStructures.Where(x => x.IsActive).Sum(x => x.StructureType.EffectBomberDefense) ?? 0;
                double effective = avail;
                if (!selfbomb) effective = effective - defense;

                if (effective <= 0) return Content("Enemy defenses completely block your ships");

                acc.SpendBombers(avail);
                if (useWarp == true) acc.SpendWarps(avail);

                var r = new Random();

                double strucKillChance = !selfbomb ? effective * GlobalConst.BomberKillStructureChance : 0;
                int strucKillCount = (int)Math.Floor(strucKillChance + r.NextDouble());

                double ipKillChance = effective * GlobalConst.BomberKillIpChance;
                int ipKillCount = (int)Math.Floor(ipKillChance + r.NextDouble());

                List<PlanetStructure> structs = planet.PlanetStructures.Where(x => x.StructureType.IsBomberDestructible).ToList();
                var bombed = new List<PlanetStructure>();
                while (structs.Count > 0 && strucKillCount > 0)
                {
                    strucKillCount--;
                    PlanetStructure s = structs[r.Next(structs.Count)];
                    bombed.Add(s);
                    structs.Remove(s);
                    db.PlanetStructures.DeleteOnSubmit(s);
                }

                double ipKillAmmount = ipKillCount * GlobalConst.BomberKillIpAmount;
                if (ipKillAmmount > 0)
                {
                    foreach (PlanetFaction pf in planet.PlanetFactions.Where(x => x.FactionID != acc.FactionID))
                    {
                        pf.Influence -= ipKillAmmount;
                        if (pf.Influence < 0) pf.Influence = 0;
                    }
                }

                var args = new List<object>
                           {
                               acc,
                               acc.Faction,
                               !selfbomb ? planet.Faction : null,
                               planet,
                               avail,
                               defense,
                               useWarp == true ? "They attacked by warp. " : "",
                               ipKillAmmount
                           };
                args.AddRange(bombed.Select(x => x.StructureType));

                string str;
                if (selfbomb) str = "{0} of {1} bombed own planet {3} using {4} bombers against {5} defenses. {6}Ground armies lost {7} influence";
                else str = "{0} of {1} bombed {2} planet {3} using {4} bombers against {5} defenses. {6}Ground armies lost {7} influence";
                if (bombed.Count > 1)
                {
                    str += " and ";
                    int counter = 8;
                    foreach (PlanetStructure b in bombed)
                    {
                        str += "{" + counter + "}" + ", ";
                        counter++;
                    }
                    str += " were destroyed.";
                }
                else if (bombed.Count == 1)
                {
                    str += " and {8} was destroyed.";
                }
                else str += ".";

                db.Events.InsertOnSubmit(Global.CreateEvent(str, args.ToArray()));
            }

            db.SubmitAndMergeChanges();
            SetPlanetOwners();
            return RedirectToAction("Planet", new { id = planetID });
        }
        public ActionResult ChangePlanetMap(int planetID, int structureTypeID, int targetID, int? newMapID)
        {
            var db = new ZkDataContext();
            PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID);
            Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID);
            Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID);
            Galaxy gal = db.Galaxies.FirstOrDefault(x => x.GalaxyID == source.GalaxyID);

            if (newMapID == null)
            {
                List<Resource> mapList =
                    db.Resources.Where(
                        x =>
                            x.MapPlanetWarsIcon != null && x.Planets.Where(p => p.GalaxyID == gal.GalaxyID).Count() == 0 && x.FeaturedOrder != null &&
                            x.ResourceID != source.MapResourceID).ToList();
                if (mapList.Count > 0)
                {
                    int r = new Random().Next(mapList.Count);
                    newMapID = mapList[r].ResourceID;
                }
            }
            if (newMapID != null)
            {
                Resource newMap = db.Resources.Single(x => x.ResourceID == newMapID);
                target.Resource = newMap;
                gal.IsDirty = true;
                string word = "";
                if (target.Faction == source.Faction)
                {
                    if (target.TeamSize < GlobalConst.PlanetWarsMaxTeamsize) target.TeamSize++;
                    word = "terraformed";
                }
                else
                {
                    word = "nanodegraded";
                    if (target.TeamSize > 1) target.TeamSize--;
                }

                db.Events.InsertOnSubmit(Global.CreateEvent("{0} {1} has been {6} by {2} from {3} {4}. New team size is {5} vs {5}",
                    target.Faction,
                    target,
                    structure.StructureType,
                    source.Faction,
                    source,
                    target.TeamSize,
                    word));
            }
            else
            {
                return
                    Content(string.Format("Terraform attempt on {0} {1} using {2} from {3} {4} has failed - no valid maps",
                        target.Faction,
                        target,
                        structure.StructureType,
                        source.Faction,
                        source));
            }
            db.SubmitAndMergeChanges();
            return null;
        }
        public ActionResult Unlock(int id, bool useKudos = false)
        {
            using (var db = new ZkDataContext())
            using (var scope = new TransactionScope())
            {

                List<Unlock> unlocks;
                List<Unlock> future;

                GetUnlockLists(db, out unlocks, out future);

                if (unlocks.Any(x => x.UnlockID == id))
                {
                    Unlock unlock = db.Unlocks.FirstOrDefault(x => x.UnlockID == id);
                    if (!useKudos && unlock.IsKudosOnly == true) return Content("That unlock cannot be bought using XP");

                    if (useKudos) {
                        var acc = db.Accounts.Find(Global.AccountID);
                        if (acc.Kudos < unlock.KudosCost) return Content("Not enough kudos to unlock this");
                        acc.KudosPurchases.Add(new KudosPurchase() {Time = DateTime.UtcNow, Unlock = unlock, Account = acc, KudosValue = unlock.KudosCost??0});
                        db.SubmitAndMergeChanges();
                        acc.Kudos = acc.KudosGained - acc.KudosSpent;
                        db.SubmitAndMergeChanges();
                    }
                    
                    var au = db.AccountUnlocks.SingleOrDefault(x => x.AccountID == Global.AccountID && x.UnlockID == id);
                    if (au == null)
                    {
                        au = new AccountUnlock() { AccountID = Global.AccountID, UnlockID = id, Count = 1 };
                        db.AccountUnlocks.InsertOnSubmit(au);
                    }
                    else au.Count++;
                    db.SubmitAndMergeChanges();
                }
                scope.Complete();
            }
            return RedirectToAction("UnlockList");
        }
        public static string SubmitSpringBattleResult(BattleContext context,
                                                      string password,
                                                      BattleResult result,
                                                      List<BattlePlayerResult> players,
                                                      List<string> extraData)
        {
            try
            {
                Account acc = AuthServiceClient.VerifyAccountPlain(context.AutohostName, password);
                if (acc == null) throw new Exception("Account name or password not valid");
                AutohostMode mode = context.GetMode();
                var db = new ZkDataContext();

                if (extraData == null) extraData = new List<string>();


                var sb = new SpringBattle
                         {
                             HostAccountID = acc.AccountID,
                             Duration = result.Duration,
                             EngineGameID = result.EngineBattleID,
                             MapResourceID = db.Resources.Single(x => x.InternalName == result.Map).ResourceID,
                             ModResourceID = db.Resources.Single(x => x.InternalName == result.Mod).ResourceID,
                             HasBots = result.IsBots,
                             IsMission = result.IsMission,
                             PlayerCount = players.Count(x => !x.IsSpectator),
                             StartTime = result.StartTime,
                             Title = result.Title,
                             ReplayFileName = result.ReplayName,
                             EngineVersion = result.EngineVersion,
                         };
                db.SpringBattles.InsertOnSubmit(sb);

                foreach (BattlePlayerResult p in players)
                {
                    sb.SpringBattlePlayers.Add(new SpringBattlePlayer
                                               {
                                                   AccountID = db.Accounts.First(x => x.AccountID == p.LobbyID).AccountID,
                                                   AllyNumber = p.AllyNumber,
                                                   CommanderType = p.CommanderType,
                                                   IsInVictoryTeam = p.IsVictoryTeam,
                                                   IsSpectator = p.IsSpectator,
                                                   LoseTime = p.LoseTime
                                               });
                }

                db.SubmitChanges();

                // awards
                foreach (string line in extraData.Where(x => x.StartsWith("award")))
                {
                    string[] partsSpace = line.Substring(6).Split(new[] { ' ' }, 3);
                    string name = partsSpace[0];
                    string awardType = partsSpace[1];
                    string awardText = partsSpace[2];

                    SpringBattlePlayer player = sb.SpringBattlePlayers.FirstOrDefault(x => x.Account.Name == name);
                    if (player != null)
                    {
                        db.AccountBattleAwards.InsertOnSubmit(new AccountBattleAward
                                                              {
                                                                  AccountID = player.AccountID,
                                                                  SpringBattleID = sb.SpringBattleID,
                                                                  AwardKey = awardType,
                                                                  AwardDescription = awardText
                                                              });
                    }
                }

                var text = new StringBuilder();
                bool isPlanetwars = false;
                if (mode == AutohostMode.Planetwars && sb.SpringBattlePlayers.Count(x => !x.IsSpectator) >= 2 && sb.Duration >= GlobalConst.MinDurationForPlanetwars)
                {
                    // test that factions are not intermingled (each faction only has one ally number) - if they are it wasnt actually PW balanced
                    if (
                        sb.SpringBattlePlayers.Where(x => !x.IsSpectator && x.Account.Faction != null)
                          .GroupBy(x => x.Account.Faction)
                          .All(grp => grp.Select(x => x.AllyNumber).Distinct().Count() < 2))
                    {
                        isPlanetwars = true;

                        
                        List<int> winnerTeams =
    sb.SpringBattlePlayers.Where(x => x.IsInVictoryTeam && !x.IsSpectator).Select(x => x.AllyNumber).Distinct().ToList();
                        int? winNum = null;
                        if (winnerTeams.Count == 1)
                        {
                            winNum = winnerTeams[0];
                            if (winNum > 1)
                            {
                                winNum = null;
                                text.AppendLine("ERROR: Invalid winner");
                            } 
                        }

                        PlanetWarsTurnHandler.EndTurn(result.Map, extraData, db, winNum, sb.SpringBattlePlayers.Where(x => !x.IsSpectator).Select(x => x.Account).ToList(), text, sb, sb.SpringBattlePlayers.Where(x => !x.IsSpectator && x.AllyNumber == 0).Select(x => x.Account).ToList());

                        Global.PlanetWarsMatchMaker.RemoveFromRunningBattles(context.AutohostName);
                    }
                    else
                    {
                        text.AppendLine("Battle wasn't PlanetWars balanced, it counts as a normal team game only");
                    }

                }

                bool noElo = (extraData.FirstOrDefault(x => x.StartsWith("noElo", true, System.Globalization.CultureInfo.CurrentCulture)) != null);
                try
                {
                    db.SubmitChanges();
                }
                catch (System.Data.Linq.DuplicateKeyException ex)
                {
                    Trace.TraceError(ex.ToString());
                }

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

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

                try
                {
                    foreach (Account a in sb.SpringBattlePlayers.Where(x => !x.IsSpectator).Select(x => x.Account)) Global.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);
                            Global.Server.GhostPm(account.Name, message);
                        }
                        catch (Exception ex)
                        {
                            Trace.TraceError("Error sending level up lobby message: {0}", ex);
                        }
                    }
                }

                text.AppendLine(string.Format("BATTLE DETAILS AND REPLAY ----> {1}/Battles/Detail/{0} <-----", sb.SpringBattleID, GlobalConst.BaseSiteUrl));

                /*
                // create debriefing room, join players there and output message
                string channelName = "B" + sb.SpringBattleID;
                var joinplayers = new List<string>();
                joinplayers.AddRange(context.Players.Select(x => x.Name)); // add those who were there at start
                joinplayers.AddRange(sb.SpringBattlePlayers.Select(x => x.Account.Name)); // add those who played
                Battle bat = Global.Server.Battles.Values.FirstOrDefault(x => x.Founder.Name == context.AutohostName); // add those in lobby atm


                var conf = context.GetConfig();
                if (bat != null && (conf == null || conf.MinToJuggle == null)) // if not qm room do not join those who are in battle
                {
                    List<string> inbatPlayers = bat.Users.Keys.ToList();
                    joinplayers.RemoveAll(x => inbatPlayers.Contains(x));
                }
                foreach (string jp in joinplayers.Distinct().Where(x => x != context.AutohostName)) tas.ForceJoinChannel(jp, channelName);
                tas.JoinChannel(channelName); // join nightwatch and say it
                tas.Say(SayPlace.Channel, channelName, text.ToString(), true);
                tas.LeaveChannel(channelName);*/

                //text.Append(string.Format("Debriefing in #{0} - zk://chat/channel/{0}  ", channelName));
                return text.ToString();
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
                return ex.ToString();
            }
        }
        void SaveStateToDb()
        {
            var db = new ZkDataContext();
            Galaxy gal = db.Galaxies.First(x => x.IsDefault);

            gal.MatchMakerState = JsonConvert.SerializeObject((MatchMakerState)this);

            gal.AttackerSideCounter = AttackerSideCounter;
            gal.AttackerSideChangeTime = AttackerSideChangeTime;
            db.SubmitAndMergeChanges();
        }
        public ActionResult FirePlanetBuster(int planetID, int structureTypeID, int targetID)
        {
            var db = new ZkDataContext();
            PlanetStructure structure = db.PlanetStructures.FirstOrDefault(x => x.PlanetID == planetID && x.StructureTypeID == structureTypeID);
            Planet source = db.Planets.FirstOrDefault(x => x.PlanetID == planetID);
            Planet target = db.Planets.FirstOrDefault(x => x.PlanetID == targetID);

            Account acc = db.Accounts.Single(x => x.AccountID == Global.AccountID);
            if (acc.Faction == null) return Content("Join some faction first");
            if (!target.CanFirePlanetBuster(acc.Faction)) return Content("You cannot attack here");

            //Get rid of all strutures
            var structures = target.PlanetStructures.Where(x => x.StructureType.EffectIsVictoryPlanet == false);
            db.PlanetStructures.DeleteAllOnSubmit(structures);


            //kill all IP
            foreach (var pf in target.PlanetFactions.Where(x => x.Influence > 0))
            {
                pf.Influence = 0;
            }
            var links = db.Links.Where(x => (x.PlanetID1 == target.PlanetID || x.PlanetID2 == target.PlanetID));
            foreach (Link link in links)
            {
                Planet planet1 = db.Planets.FirstOrDefault(x => x.PlanetID == link.PlanetID1);
                Planet planet2 = db.Planets.FirstOrDefault(x => x.PlanetID == link.PlanetID2);
                if (!(planet1.PlanetStructures.Any(x => x.StructureType.EffectIsVictoryPlanet == true)) &&
                    !(planet2.PlanetStructures.Any(x => x.StructureType.EffectIsVictoryPlanet == true)))
                {
                    db.Links.DeleteOnSubmit(link);
                }
            }

            db.Events.InsertOnSubmit(Global.CreateEvent("A {4} fired from {0} {1} has destroyed {2} {3}!", source.Faction, source, target.Faction, target, structure.StructureType));
            db.SubmitAndMergeChanges();

            var residue = db.StructureTypes.First(x => x.Name == "Residue"); // todo not nice use constant instead
            target.PlanetStructures.Add(new PlanetStructure() { StructureType = residue, IsActive = true, ActivatedOnTurn = null});
            db.SubmitAndMergeChanges();



            return null;
        }
Example #32
0
 static void SetPlanetTeamSizes()
 {
     var db = new ZkDataContext();
     var gal = db.Galaxies.First(x => x.IsDefault);
     var planets = gal.Planets.ToList().OrderBy(x => x.Resource.MapDiagonal).ToList();
     var cnt = planets.Count;
     int num = 0;
     foreach (var p in planets)
     {
         //if (num < cnt*0.15) p.TeamSize = 1;else 
         if (num < cnt * 0.80) p.TeamSize = 2;
         //else if (num < cnt*0.85) p.TeamSize = 3;
         else p.TeamSize = 3;
         num++;
     }
     db.SubmitAndMergeChanges();
 }