public static bool delete(SpacegameServer.Core.ShipTemplate template) { Core core = Core.Instance; List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(template); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { template.obsolete = true; template.isConstructable = true; List <AsyncSaveable> elementsToSave = new List <AsyncSaveable>(); elementsToSave.Add(template); core.dataConnection.saveAsync(elementsToSave); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public static bool createAlliance(User user, string name) { Core core = Core.Instance; List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(user); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { //Prüfen ob der Nutzer noch Mitlgied einer ALlianz ist if (user.allianceId != 0 || user.group != null) { LockingManager.unlockAll(elementsToLock); return(false); } //create alliance int newId = (int)Core.Instance.identities.allianceId.getNext(); Alliance alliance = new Alliance(newId, name, "", "", user.id, 1000, null); core.alliances.TryAdd(newId, alliance); //add owner AllianceMember fullRights = AllianceMember.fullRights(user.id, newId); alliance.join(user, fullRights); //All relations from and towards the user are now concerning his new alliance: List <DiplomaticRelation> relations = new List <DiplomaticRelation>(); foreach (var relation in core.userRelations.getDiplomatics(user, 1)) { core.userRelations.setDiplomaticEntityState(alliance, relation.target, (Relation)relation.relationSenderProposal); relations.Add(new DiplomaticRelation(alliance.GetHashCode(), relation.target.GetHashCode(), relation.relationSenderProposal)); core.userRelations.setDiplomaticEntityState(relation.target, alliance, (Relation)relation.relationTargetProposal); relations.Add(new DiplomaticRelation(relation.target.GetHashCode(), alliance.GetHashCode(), relation.relationTargetProposal)); } //save alliance: core.dataConnection.saveAlliances(alliance); // new relations: Core.Instance.dataConnection.saveDiplomaticEntities(relations); //members: Core.Instance.dataConnection.saveAllianceMembers(alliance); CommunicationNode.CreateAllianceNode(alliance); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public static TradeOffer createTrade(ClientTrade trade, int senderId) { Core core = Core.Instance; int newId = (int)core.identities.trades.getNext(); TradeOffer NewTradeOffer = new TradeOffer(newId, trade); NewTradeOffer.FetchUser(); List <Lockable> elementsToLock = new List <Lockable>(2); elementsToLock.Add(NewTradeOffer.Sender.Owner); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(null); } try { if (!NewTradeOffer.Check(senderId)) { return(null); } try { Core.Instance.dataConnection.SaveTradeOffer(NewTradeOffer); core.tradeOffer.TryAdd(NewTradeOffer.tradeOfferId, NewTradeOffer); } catch (Exception ex) { SpacegameServer.Core.Core.Instance.writeExceptionToLog(ex); } } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } if (NewTradeOffer != null) { NewTradeOffer.TradingShip = Core.Instance.ships[NewTradeOffer.spaceObjectId]; NewTradeOffer.TradingShip.TradeOffers.Add(NewTradeOffer); var offerSerialized = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(NewTradeOffer); Core.Instance.SendNewTrade(new { NewTradeOffer = offerSerialized }); } return(NewTradeOffer); }
public void ServiceLockingUnlockingTest() { var lockManager = new LockingManager(contextManager, userIdentificationMock); var service = servicesDbSet.First(); lockManager.LockEntity(service); var lockResult = lockManager.UnLockEntity(service); Assert.Equal(EntityLockEnum.Unlocked, lockResult); }
public static bool deconstruct(int userId, int colonyId, int buildingId) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; Colony colony = core.colonies[colonyId]; if (colony == null) { return(false); } if (!deconstructCheck(userId, colony, buildingId)) { return(false); } List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(colony); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { //owner may have been changed by another thread, so check it again after locking if (!deconstructCheck(userId, colony, buildingId)) { return(false); } ColonyBuilding itemToRemove = colony.colonyBuildings.Single(colonyBuilding => colonyBuilding.id == buildingId); itemToRemove.Recycle(colony); colony.colonyBuildings.Remove(itemToRemove); core.colonyBuildings.TryRemove(buildingId); Core.Instance.dataConnection.saveColonyGoods(colony); Core.Instance.dataConnection.DeconstructBuilding(userId, buildingId); } catch (Exception ex) { SpacegameServer.Core.Core.Instance.writeExceptionToLog(ex); return(false); } finally { //release the ressources LockingManager.unlockAll(elementsToLock); } return(true); }
void Start() { //groundMask = LayerMask.GetMask (new string[]{ "Ground", "Player" }); rg = GetComponent <Rigidbody2D> (); groundCheck = GetComponent <CircleCollider2D> (); rg.gravityScale = gravity; rg.freezeRotation = true; rg.useAutoMass = true; lockManager = new GameObject("Lock Manager").AddComponent <LockingManager>(); }
public void ServiceLockingTest() { var lockManager = new LockingManager(contextManager, userIdentificationMock); var service = servicesDbSet.First(); var lockResult = lockManager.LockEntity(service); Assert.Equal("TestUser", lockResult.LockedBy); Assert.Equal(EntityLockEnum.LockedForCurrent, lockResult.LockStatus); Assert.False(lockManager.IsLocked(service)); userIdentificationMockSetup.Setup(ui => ui.UserName).Returns("TestUserAnother"); Assert.True(lockManager.IsLocked(service)); }
private bool addToNode(User user) { List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(this); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { //add contact data from this commNode to users contacts: /* * foreach (var commNodeUser in this.commNodeUsers) * { * User commUser = Core.Instance.users[commNodeUser.Key]; * if (Core.Instance.userRelations.hasContact(user, commUser)) continue; * * Core.Instance.userRelations.addUserRelation(user, commUser, newContacts); * } * * * //save new contact data: * Core.Instance.dataConnection.saveDiplomaticEntities(newContacts); */ //add User to CommNode var newUser = new CommNodeUser(user.id, this.id); this.commNodeUsers.TryAdd(user.id, newUser); user.commNodeRights.Add(this.id, newUser); //and save to DB: var toSave = new List <CommNodeUser>(); toSave.Add(newUser); Core.Instance.dataConnection.saveCommNodeUsers(toSave); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public void setQuestRead(int userId, int questId) { if (!Core.Core.Instance.users.ContainsKey(userId)) { return; } var user = Core.Core.Instance.users[userId]; if (!user.quests.Any(e => e.questId == questId)) { return; } var quest = user.quests.First(e => e.questId == questId); List <Lockable> elementsToLock = new List <Lockable>(); elementsToLock.Add(quest); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { List <Core.UserQuest> UserQuestsToSave = new List <Core.UserQuest>(); UserQuestsToSave.Add(quest); quest.isRead = true; Core.Core.Instance.dataConnection.SaveUserQuests(Core.Core.Instance, UserQuestsToSave); } catch (Exception ex) { Core.Core.Instance.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } }
//Check and lock, then call DeleteTradeExecute public static void DeleteTrade(int tradeId, int senderId) { if (Core.Instance.tradeOffer.ContainsKey(tradeId)) { var trade = Core.Instance.tradeOffer[tradeId]; List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(trade); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { if (trade.Owner.id == senderId) { DeleteTradeExecute(trade); /* * trade.TradingShip.TradeOffers.Remove(trade); * trade.TradingShip = null; * * Core.Instance.dataConnection.deleteTradeOfferById(tradeId); * Core.Instance.tradeOffer.TryRemove(tradeId); * Core.Instance.DeleteTrade(tradeId); */ } } catch (Exception ex) { Core.Instance.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } } }
public void rename(string newName) { List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(this); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { this.name = newName; Core.Instance.dataConnection.saveColonies(this); } catch (Exception ex) { Core.Instance.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } }
public static bool leaveCheck(User user, User userToRemove, int allianceId) { Core core = Core.Instance; if (!core.alliances.ContainsKey(allianceId)) { return(false); } Alliance alliance = core.alliances[allianceId]; List <Lockable> elementsToLock = new List <Lockable>(2); elementsToLock.Add(userToRemove); elementsToLock.Add(alliance); if (user != userToRemove) { //check that both are in the same alliance if (user.allianceId != userToRemove.allianceId) { return(false); } //check that user may fire a member if (!alliance.memberRights.Any(e => e.userId == user.id && e.mayFire)) { return(false); } } //Test ob @userId Teil der ALlianz ist if (!alliance.members.Any(e => e.id == user.id)) { return(false); } if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { if (user != userToRemove) { //check that both are in the same alliance if (user.allianceId != userToRemove.allianceId) { LockingManager.unlockAll(elementsToLock); return(false); } //check that user may fire a member if (!alliance.memberRights.Any(e => e.userId == user.id && e.mayFire)) { LockingManager.unlockAll(elementsToLock); return(false); } } //Test ob @userId Teil der ALlianz ist if (!alliance.members.Any(e => e.id == user.id)) { LockingManager.unlockAll(elementsToLock); return(false); } //remove User alliance.leave(userToRemove); //members: Core.Instance.dataConnection.saveAllianceMembers(alliance); //delete alliance if the need exists: if (alliance.members.Count == 0) { int allianceHash = alliance.GetHashCode(); core.alliances.TryRemove(alliance.id); //delete all relations: core.userRelations.removeEntity(alliance); core.dataConnection.deleteAllianceRelations(allianceHash); //delete alliance in DB core.dataConnection.deleteAlliance(allianceId); } else { //check if alliance owner has left, if yes, choose a new one if (alliance.allianceowner == userToRemove.id) { alliance.allianceowner = 0; //first fullAdmin if (alliance.memberRights.Any(e => e.fullAdmin)) { alliance.allianceowner = alliance.memberRights.First(e => e.fullAdmin).userId; } //then first diplomaticAdmin if (alliance.allianceowner == 0 && alliance.memberRights.Any(e => e.diplomaticAdmin)) { alliance.allianceowner = alliance.memberRights.First(e => e.diplomaticAdmin).userId; } //then first diplomaticAdmin if (alliance.allianceowner == 0 && alliance.memberRights.Any(e => e.mayMakeDiplomaticProposals)) { alliance.allianceowner = alliance.memberRights.First(e => e.mayMakeDiplomaticProposals).userId; } //at last just anyone if (alliance.allianceowner == 0) { alliance.allianceowner = alliance.memberRights.First().userId; } //update alliance in DB core.dataConnection.saveAlliances(alliance); } } } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
//similar to Ship.createSpaceStation(), but not easily generalizable public bool build2(int shipTemplateId, int _userId, int _colonyId, bool fastBuild, ref int newShipId, ref ShipBuildErrorCode errorCode, ref int errorValue) { Core core = Core.Instance; GalaxyMap galaxyMap = null; // lock colony and field Colony colony = core.colonies[_colonyId]; if (colony == null) { return(false); } if (colony.userId != _userId) { return(false); } Field field = colony.field; ShipTemplate template = core.shipTemplate[shipTemplateId]; if (!(this.checkFreeOrbit(field, _userId, colony.systemXY(), ref errorCode, ref errorValue) && this.checkGoodsAvailability(colony, template, fastBuild, ref errorCode, ref errorValue) && this.checkSpaceport(colony, ref errorCode, ref errorValue) && this.checkTechnology(template, _userId, fastBuild, ref errorCode, ref errorValue) && this.checkUniqueness(field, template, colony.systemXY(), ref errorCode, ref errorValue))) { return(false); } //Lock List <Lockable> elementsToLock = new List <Lockable>(3); elementsToLock.Add(colony); elementsToLock.Add(field); //check for transcendence //ToDo: replace 220 with a sql data field if (template.hullid == 220 && core.GalaxyMap.transcendenceRequirement == 0) { galaxyMap = core.GalaxyMap; elementsToLock.Add(galaxyMap); } if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } newShipId = (int)Core.Instance.identities.shipLock.getNext(); try { //all checks again inside of lock if (!(this.checkFreeOrbit(field, _userId, colony.systemXY(), ref errorCode, ref errorValue) && this.checkGoodsAvailability(colony, template, fastBuild, ref errorCode, ref errorValue) && this.checkSpaceport(colony, ref errorCode, ref errorValue) && this.checkTechnology(template, _userId, fastBuild, ref errorCode, ref errorValue) && this.checkUniqueness(field, template, colony.systemXY(), ref errorCode, ref errorValue))) { return(false); } //everything checked and locked //now do the work Ship newShip = buildShip(newShipId, template, field, _userId, colony, fastBuild); newShip.SetTranscension(galaxyMap); //write SQL Core.Instance.dataConnection.insertShip(newShip); Core.Instance.dataConnection.saveColonyGoods(colony); } catch (Exception ex) { SpacegameServer.Core.Core.Instance.writeExceptionToLog(ex); } finally { //release the ressources LockingManager.unlockAll(elementsToLock); } return(true); }
/// <summary> /// All checks and preparations to accept a trade offer /// </summary> /// <param name="tradeId">The tradeId of the trade to be accepted</param> /// <param name="senderId">The userId of user thataccepts the trade</param> /// <param name="commNodeId">The place where the goods should be put on ships</param> public static void acceptTrade2(int tradeId, int senderId, int commNodeId) { if (!Core.Instance.tradeOffer.ContainsKey(tradeId)) { return; } if (!Core.Instance.users.ContainsKey(senderId)) { return; } if (!Core.Instance.commNodes.ContainsKey(commNodeId)) { return; } try { var TradeOffer = Core.Instance.tradeOffer[tradeId]; if (!Core.Instance.ships.ContainsKey(TradeOffer.spaceObjectId)) { return; } if (TradeOffer.Owner.id == senderId) { return; } var User = Core.Instance.users[senderId]; var PayoutNode = Core.Instance.commNodes[commNodeId]; var TradingShip = Core.Instance.ships[TradeOffer.spaceObjectId]; List <Ship> ShipsToPayGoods = new List <Ship>(); List <Ship> ShipsToReceiveGoods = new List <Ship>(); //checks: // 1) has the user enough goods to accept the trade? if (!CheckRequestedGoods(TradeOffer, User.ships)) { return; } // 2) has the user enough storage capacity at the payout location to accept the trade? if (!CheckStorageCapacity(TradeOffer, User.ships, commNodeId)) { return; } GetPayingShips(TradeOffer, User.ships, ShipsToPayGoods); GetReceivingShips(TradeOffer, User.ships, ShipsToReceiveGoods, commNodeId); List <Lockable> elementsToLock = new List <Lockable>(4); elementsToLock.Add(TradeOffer); elementsToLock.AddRange(ShipsToPayGoods.Union(ShipsToReceiveGoods)); elementsToLock.Add(TradeOffer.TradingShip); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { //Do the Checks again, this time only versus the locked objects // 1) has the user enough goods to accept the trade? if (!CheckRequestedGoods(TradeOffer, ShipsToPayGoods)) { return; } // 2) has the user enough storage capacity at the payout location to accept the trade? if (!CheckStorageCapacity(TradeOffer, ShipsToReceiveGoods, commNodeId)) { return; } //swap the goods ExecuteTrade(TradeOffer, ShipsToPayGoods, ShipsToReceiveGoods); //write new ship cargo holds to DB Core.Instance.dataConnection.saveShipGoods(TradeOffer.TradingShip); foreach (var ship in ShipsToPayGoods.Union(ShipsToReceiveGoods)) { Core.Instance.dataConnection.saveShipGoods(ship); } //cleanup trade references TradeOffer.TradingShip.TradeOffers.Remove(TradeOffer); TradeOffer.TradingShip = null; //remove trade Core.Instance.dataConnection.deleteTradeOfferById(tradeId); Core.Instance.tradeOffer.TryRemove(tradeId); //send to all players Core.Instance.DeleteTrade(tradeId); } catch (Exception ex) { Core.Instance.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } } catch (Exception ex) { Core.Instance.writeExceptionToLog(ex); } }
public static bool acceptTrade(int userId, int senderId, int senderType, int tradeOfferIdInt, int receiverId, int receiverType, ref string output) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; SpacegameServer.Core.UserSpaceObject sender = null; SpacegameServer.Core.UserSpaceObject receiver = null; if (senderType == 0) { if (core.ships.ContainsKey(senderId)) { sender = core.ships[senderId]; } } if (senderType == 1) { if (core.colonies.ContainsKey(senderId)) { sender = core.colonies[senderId]; } } if (receiverType == 0) { if (core.ships.ContainsKey(receiverId)) { receiver = core.ships[receiverId]; } } if (receiverType == 1) { if (core.colonies.ContainsKey(receiverId)) { receiver = core.colonies[receiverId]; } } if (sender == null || receiver == null) { return(false); } List <Lockable> toLock = new List <Lockable>(); toLock.Add(sender); toLock.Add(receiver); if (!LockingManager.lockAllOrSleep(toLock)) { return(false); } //make changes //Core.Instance.dataConnection.deconstructBuilding(userId, buildingId, ref xml); //atm : call sql procedure: Core.Instance.dataConnection.acceptTrade(userId, senderId, senderType, tradeOfferIdInt, ref output); //save changes /* * List<AsyncSaveable> toSave = new List<AsyncSaveable>(); * toSave.Add(sender); * toSave.Add(receiver); * DataConnectors.SqlConnector.saveAsync(toSave); */ // get colony data (goods, later population (colony ships)) //Core.Instance.dataConnection.getColonyStock(core, colony); List <UserSpaceObject> toUpdate = new List <UserSpaceObject>(); toUpdate.Add(sender); toUpdate.Add(receiver); Core.Instance.dataConnection.updateStock(toUpdate); //unlock LockingManager.unlockAll(toLock); Core.Instance.DeleteTrade(tradeOfferIdInt); return(true); }
public static bool createUpdate(string xml, int userId, ref SpacegameServer.Core.ShipTemplate template, ref SpacegameServer.Core.ShipTemplate oldTemplate) { /* * <?xml version="1.0" encoding="utf-8" ?> * <ShipTemplate> * <ShipTemplateId>1</ShipTemplateId> * <ShipTemplateHullId>1</ShipTemplateHullId> * <name>testName</name> * <gif>scout.png</gif> * <shipHullsImage>1</shipHullsImage> * <modulePositions> * <modulePosition> * <posX>3</posX> * <posY>3</posY> * <moduleId>1</moduleId> * </modulePosition> * <modulePosition> * <posX>2</posX> * <posY>3</posY> * <moduleId>2</moduleId> * </modulePosition> * </modulePositions> * </ShipTemplate> */ Core core = Core.Instance; List <Lockable> elementsToLock = new List <Lockable>(2); SpacegameServer.Core.User user = core.users[userId]; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); string templateIdString = doc.DocumentElement.SelectSingleNode("/ShipTemplate/ShipTemplateId").InnerText; int templateId; if (!Int32.TryParse(templateIdString, out templateId)) { return(false); } string templateHullIdString = doc.DocumentElement.SelectSingleNode("/ShipTemplate/ShipTemplateHullId").InnerText; byte templateHullId; if (!System.Byte.TryParse(templateHullIdString, out templateHullId)) { return(false); } string shipHullsImageString = doc.DocumentElement.SelectSingleNode("/ShipTemplate/shipHullsImage").InnerText; int shipHullsImage; if (!Int32.TryParse(shipHullsImageString, out shipHullsImage)) { return(false); } if (templateId != -1) { template = core.shipTemplate[templateId]; if (template.userId != userId) { return(false); } if (template.amountbuilt > 0) { oldTemplate = template; int newTemplateId = (int)SpacegameServer.Core.Core.Instance.identities.templateLock.getNext(); template = new SpacegameServer.Core.ShipTemplate(newTemplateId); } } else { int newTemplateId = (int)SpacegameServer.Core.Core.Instance.identities.templateLock.getNext(); template = new SpacegameServer.Core.ShipTemplate(newTemplateId); template.userId = userId; template.gif = "Dummy"; } template.name = doc.DocumentElement.SelectSingleNode("/ShipTemplate/name").InnerText; template.hullid = templateHullId; template.shipHullsImage = shipHullsImage; elementsToLock.Add(template); if (oldTemplate != null) { elementsToLock.Add(oldTemplate); } if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { template.shipModules.Clear(); System.Xml.XmlNodeList modules = doc.DocumentElement.SelectNodes("/ShipTemplate/modulePositions/modulePosition"); foreach (System.Xml.XmlNode node in modules) { string posXS = node.SelectSingleNode("posX").InnerText; //or loop through its children as well string posYS = node.SelectSingleNode("posY").InnerText; //or loop through its children as well string moduleIdS = node.SelectSingleNode("moduleId").InnerText; //or loop through its children as well byte posX, posY; short moduleId; if (!(Byte.TryParse(posXS, out posX) && Byte.TryParse(posYS, out posY) && Int16.TryParse(moduleIdS, out moduleId))) { LockingManager.unlockAll(elementsToLock); return(false); } ShipTemplateModules newModule = new ShipTemplateModules(); newModule.posX = posX; newModule.posY = posY; newModule.moduleId = moduleId; newModule.shiptemplateid = template.id; template.shipModules.Add(newModule); } StatisticsCalculator.calc(template, Core.Instance); template.isConstructable = template.energy >= 0 && template.crew >= 0; if (!core.shipTemplate.ContainsKey(template.id)) { core.shipTemplate[template.id] = template; } //save newTemplate and oldTemplate List <AsyncSaveable> elementsToSave = new List <AsyncSaveable>(); elementsToSave.Add(template); if (oldTemplate != null) { oldTemplate.obsolete = true; elementsToSave.Add(oldTemplate); } core.dataConnection.saveAsync(elementsToSave); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public static bool transfer(int userId,string transfer, ref string xml) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; SpacegameServer.Core.UserSpaceObject sender = null; SpacegameServer.Core.UserSpaceObject receiver = null; //check XML for sender and receiver XmlDocument doc = new XmlDocument(); doc.LoadXml(transfer); //string xml = "<transfer><sender><shipId>1760</shipId><goods></goods></sender><receiver><colonyId>11</colonyId><goods><good><goodsId>50</goodsId><amount>3</amount></good></goods></receiver></transfer>"; //.SelectSingleNode("/book/title"); XmlNode senderShipNode = doc.DocumentElement.SelectSingleNode("/transfer/sender/shipId"); XmlNode senderColonyNode = doc.DocumentElement.SelectSingleNode("/transfer/sender/colonyId"); XmlNode receiverShipNode = doc.DocumentElement.SelectSingleNode("/transfer/receiver/shipId"); XmlNode receiverColonyNode = doc.DocumentElement.SelectSingleNode("/transfer/receiver/colonyId"); int senderUserId = 0, receiverUserId = 0; if (senderShipNode != null) { string sendStr = senderShipNode.InnerText; int senderId; if (Int32.TryParse(sendStr, out senderId)) { if (core.ships.ContainsKey(senderId)) { sender = core.ships[senderId]; senderUserId = core.ships[senderId].userid; } } } if (senderColonyNode != null) { string ColonyStr = senderColonyNode.InnerText; int ColonyId; if (Int32.TryParse(ColonyStr, out ColonyId)) { if (core.colonies.ContainsKey(ColonyId)) { sender = core.colonies[ColonyId]; senderUserId = core.colonies[ColonyId].userId; } } } if (receiverShipNode != null) { string receiverStr = receiverShipNode.InnerText; int receiverId; if (Int32.TryParse(receiverStr, out receiverId)) { if (core.ships.ContainsKey(receiverId)) { receiver = core.ships[receiverId]; receiverUserId = core.ships[receiverId].userid; } } } if (receiverColonyNode != null) { string receiverStr = receiverColonyNode.InnerText; int receiverId; if (Int32.TryParse(receiverStr, out receiverId)) { if (core.colonies.ContainsKey(receiverId)) { receiver = core.colonies[receiverId]; receiverUserId = core.colonies[receiverId].userId; } } } if (sender == null || receiver == null) return false; //check that one does not move cargo from a neutral (0) space station (hullId 201) if( sender is Ship) { var SendShip = (Ship)sender; if (SendShip.hullid == 201 && SendShip.userid == 0) return false; } if (receiver is Ship) { var RecShip = (Ship)receiver; if (RecShip.hullid == 201 && RecShip.userid == 0) return false; } //test if goods are received: var receive = false; XmlNode sentNode = doc.DocumentElement.SelectSingleNode("/transfer/sender/goods/good"); XmlNode receiveNode = doc.DocumentElement.SelectSingleNode("/transfer/receiver/goods/good"); if (receiveNode != null) receive = true; //if trade is between users, and goods are received, check that they are at war if (receive && senderUserId != receiverUserId && receiverUserId != 0) { //check that both are enemies (or player 0 is involved) if (receive && Core.Instance.userRelations.getRelation(Core.Instance.users[senderUserId], Core.Instance.users[receiverUserId]) != 0) { return false; } } List<Lockable> toLock = new List<Lockable>(); toLock.Add(sender); toLock.Add(receiver); if (!LockingManager.lockAllOrSleep(toLock)) return false; //make changes //Core.Instance.dataConnection.deconstructBuilding(userId, buildingId, ref xml); //atm : call sql procedure: Core.Instance.dataConnection.transfer(userId, transfer, ref xml); //save changes /* List<AsyncSaveable> toSave = new List<AsyncSaveable>(); toSave.Add(sender); toSave.Add(receiver); DataConnectors.SqlConnector.saveAsync(toSave); */ // get colony data (goods, later population (colony ships)) //Core.Instance.dataConnection.getColonyStock(core, colony); List<UserSpaceObject> toUpdate = new List<UserSpaceObject>(); toUpdate.Add(sender); toUpdate.Add(receiver); Core.Instance.dataConnection.updateStock(toUpdate); //unlock LockingManager.unlockAll(toLock); return true; }
public static bool transfer2(int userId, SpacegameServer.Core.Transfer transfer, ref string xml) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; SpacegameServer.Core.UserSpaceObject sender = null; SpacegameServer.Core.UserSpaceObject receiver = null; Ship SenderShip = null; Ship TargetShip = null; Colony SenderColony = null; Colony TargetColony = null; int senderUserId = 0; int receiverUserId = 0; //for sender and receiver if (transfer.Sender < 1 || transfer.SenderType < 1 || transfer.TargetType < 1) return false; if (transfer.SenderType == 1) { if (core.ships.ContainsKey(transfer.Sender)) { SenderShip = core.ships[transfer.Sender]; sender = core.ships[transfer.Sender]; senderUserId = SenderShip.userid; } } if (transfer.SenderType == 2) { if (core.colonies.ContainsKey(transfer.Sender)) { SenderColony = core.colonies[transfer.Sender]; sender = core.colonies[transfer.Sender]; senderUserId = SenderColony.userId; } } if (transfer.TargetType == 1) { if (core.ships.ContainsKey(transfer.Target)) { TargetShip = core.ships[transfer.Target]; receiver = core.ships[transfer.Target]; receiverUserId = core.ships[transfer.Target].userid; } else { } } if (transfer.TargetType == 2) { if (core.colonies.ContainsKey(transfer.Target)) { TargetColony = core.colonies[transfer.Target]; receiver = core.colonies[transfer.Target]; receiverUserId = TargetColony.userId; } //mock a target for srap and recycling actions if (transfer.Target < 1) { TargetShip = Ship.createTransferMock(); receiver = TargetShip; receiverUserId = 0; } } if (sender == null || receiver == null) return false; if (!TransferChecks(userId, sender, receiver, transfer, SenderShip, TargetShip, SenderColony, TargetColony)) return false; List<Lockable> toLock = new List<Lockable>(); toLock.Add(sender); if (receiver.GetUserId() != 0) { toLock.Add(receiver); } if (!LockingManager.lockAllOrSleep(toLock)) return false; if (!TransferChecks(userId, sender, receiver, transfer, SenderShip, TargetShip, SenderColony, TargetColony)) { LockingManager.unlockAll(toLock); return false; } try { if (SenderShip != null) SenderShip.RemoveAllTrades(); if (TargetShip != null) TargetShip.RemoveAllTrades(); foreach (var transferLine in transfer.Goods) { //var Good = Core.Instance.Goods[transferLine.Id]; sender.addGood((short)transferLine.Id, -transferLine.Qty); //recycle: if (transfer.Target == 0) { Core.Instance.Goods[transferLine.Id].Recycle(sender, transferLine.Qty); } //add goods if it is not scrapping or rececling... if (TargetShip == null || TargetShip.id > 0) receiver.addGood((short)transferLine.Id, transferLine.Qty); } //Core.Instance.dataConnection.saveShipGoods(this); //core.dataConnection.saveColonyGoods(colony); if (SenderShip != null) Core.Instance.dataConnection.saveShipGoods(SenderShip); if (TargetShip != null && transfer.Target > 0) Core.Instance.dataConnection.saveShipGoods(TargetShip); if (SenderColony != null) Core.Instance.dataConnection.saveColonyGoods(SenderColony); if (TargetColony != null && transfer.Target > 0) Core.Instance.dataConnection.saveColonyGoods(TargetColony); } catch (Exception e) { Core.Instance.writeExceptionToLog(e); return false; } finally { //unlock LockingManager.unlockAll(toLock); } return true; }
public static bool BuildModules(int userId, SpacegameServer.Core.Transfer transfer, ref string xml) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; if (!core.colonies.ContainsKey(transfer.Sender)) { return(false); } Colony colony = core.colonies[transfer.Sender]; if (colony.userId != userId) { return(false); } User user = Core.Instance.users[userId]; //check if modules are researched: foreach (var moduleLine in transfer.Goods) { if (moduleLine.Qty < 0) { return(false); } //check that the Module exists if (!Core.Instance.Modules.Any(e => e != null && e.goodsId == moduleLine.Id)) { return(false); } Module toBuild = Core.Instance.Modules.First(e => e != null && e.goodsId == moduleLine.Id); if (!user.hasModuleResearch(toBuild)) { return(false); } } if (!Modules.checkGoodsAvailability(colony, transfer)) { return(false); } List <Lockable> elementsToLock = new List <Lockable>(3); elementsToLock.Add(colony); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { if (!Modules.checkGoodsAvailability(colony, transfer)) { return(false); } //remove TemplateModules foreach (var moduleLine in transfer.Goods) { Module toBuild = core.Modules.First(e => e != null && e.goodsId == moduleLine.Id); foreach (var costs in toBuild.ModulesCosts) { colony.addGood(costs.goodsId, -costs.amount * moduleLine.Qty, false); } colony.addGood(toBuild.goodsId, moduleLine.Qty, false); } Core.Instance.dataConnection.saveColonyGoods(colony); } catch (Exception ex) { SpacegameServer.Core.Core.Instance.writeExceptionToLog(ex); } finally { //release the ressources and return true LockingManager.unlockAll(elementsToLock); } return(true); }
public static bool build(int userId, int colonyId, int tileNr, short buildingId, ref int newBuildingId) { SpacegameServer.Core.Core core = SpacegameServer.Core.Core.Instance; //check against research if (!Core.Instance.users.ContainsKey(userId)) { return(false); } var User = Core.Instance.users[userId]; if (!User.hasGameObjectEnabled(3, buildingId)) { return(false); } Colony colony = core.colonies[colonyId]; if (colony == null) { return(false); } Building template = core.Buildings[buildingId]; if (template == null) { return(false); } //check on building count in case of mines, hydrocarbon, rare chemicals if (buildingId == 2 || buildingId == 6) { if (ColonyBuildingActions.countBuildings(colony, buildingId) >= ColonyBuildingActions.allowedBuildings(colony, buildingId)) { return(false); } } //check tile position if (colony.colonyBuildings.Any(e => e.planetSurfaceId == tileNr)) { return(false); } // lock colony List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(colony); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { //userId may have been changed by another thread, so check it again after locking if (colony.userId != userId) { colony.removeLock(); return(false); } //test ressources on colony var costOK = true; foreach (var cost in template.BuildingCosts) { if (!colony.goods.Any(e => e.goodsId == cost.goodsId)) { costOK = false; break; } if (colony.goods.Find(e => e.goodsId == cost.goodsId).amount < cost.amount) { costOK = false; break; } } if (!costOK) { colony.removeLock(); return(false); } if (template.oncePerColony) { if (colony.colonyBuildings.Any(e => e.buildingId == template.id)) { colony.removeLock(); return(false); } } //Special Ressourcen /* * if (template.id > 1029 && template.id < 1035) * { * var star = Core.Instance.stars[colony.starId]; * if (star.ressourceid != template.id - 1030) * { * colony.removeLock(); * return false; * } * } */ //Create Building var newId = (int)core.identities.colonyBuildingId.getNext(); newBuildingId = newId; var building = new ColonyBuilding(core, newId, colony, template, tileNr, userId); /* * var building = new ColonyBuilding(newId); * building.colonyId = colony.id; * building.colony = colony; * building.planetSurfaceId = tileNr; * building.userId = userId; * building.buildingId = buildingId; * building.isActive = true; * building.underConstruction = false; * building.remainingHitpoint = 100; * building.building = template; * colony.colonyBuildings.Add(building); * Core.Instance.colonyBuildings.Add(newId, building); */ foreach (var cost in template.BuildingCosts) { colony.addGood(cost.goodsId, -cost.amount); } /*check auf: * TODO - Feld frei? * TODO - Forschung */ //Todo: Scanrange, CommNode if (building.buildingId == 51) { building.colony.scanRange = Math.Max(building.colony.scanRange, (byte)7); core.dataConnection.saveSingleColony(building.colony); } if (building.buildingId == 64) { building.colony.scanRange = Math.Max(building.colony.scanRange, (byte)9); core.dataConnection.saveSingleColony(building.colony); } core.dataConnection.saveColonyBuildings(building); core.dataConnection.saveColonyGoods(colony); CommunicationNode.createCommNodeBuilding(building); //Core.Instance.dataConnection.buildBuilding(userId, colonyId, tileNr, buildingId, ref xml); // get colony data (goods, later population (colony ships)) //Core.Instance.dataConnection.getColonyStock(core, colony); //Core.Instance.dataConnection.getColonyBuildings(core, colony); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public static void removeInvitation(User sender, User receiver) { Core core = Core.Instance; //sender removes the invitation invites the receiver to his alliance: if (!(sender.allianceId != 0 && Core.Instance.alliances.ContainsKey(sender.allianceId))) { return; } Alliance alliance = Core.Instance.alliances[sender.allianceId]; //teste ob user erlaubt ist invites zu geben if (!alliance.getMemberRight(sender).mayInvite) { return; } //teste das kein invite vorhanden ist if (!(Core.Instance.invitesPerAlliance.ContainsKey(alliance.id) && Core.Instance.invitesPerAlliance[alliance.id].Any(user => user == receiver.id))) { return; } List <Lockable> elementsToLock = new List <Lockable>(2); elementsToLock.Add(alliance); elementsToLock.Add(receiver); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { //teste das kein invite vorhanden ist if (!(Core.Instance.invitesPerAlliance.ContainsKey(alliance.id) && Core.Instance.invitesPerAlliance[alliance.id].Any(userId => userId == receiver.id))) { LockingManager.unlockAll(elementsToLock); return; } Core.Instance.invitesPerAlliance[alliance.id].RemoveAll(userId => userId == receiver.id); if (Core.Instance.invitesPerUser.ContainsKey(receiver.id)) { Core.Instance.invitesPerUser[receiver.id].RemoveAll(allianceId => allianceId == alliance.id); } Core.Instance.dataConnection.removeInvite(alliance.id, receiver.id); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } }
public static void inviteTo(User sender, User receiver) { Core core = Core.Instance; //sender invites the receiver to his alliance: if (!(sender.allianceId != 0 && Core.Instance.alliances.ContainsKey(sender.allianceId))) { return; } Alliance alliance = Core.Instance.alliances[sender.allianceId]; //teste ob sich beide user kennen: //if (!core.userRelations.hasContact(sender, receiver)) return; //teste ob user erlaubt ist invites zu geben if (!alliance.getMemberRight(sender).mayInvite) { return; } //teste ob schon ein invite vorhanden ist if (core.invitesPerAlliance.ContainsKey(alliance.id) && core.invitesPerAlliance[alliance.id].Any(userId => userId == receiver.id)) { return; } List <Lockable> elementsToLock = new List <Lockable>(2); elementsToLock.Add(alliance); elementsToLock.Add(receiver); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return; } try { //teste ob schon ein invite vorhanden ist if (core.invitesPerAlliance.ContainsKey(alliance.id) && core.invitesPerAlliance[alliance.id].Any(userId => userId == receiver.id)) { LockingManager.unlockAll(elementsToLock); return; } //add into both dicts if (core.invitesPerAlliance.ContainsKey(alliance.id)) { core.invitesPerAlliance[alliance.id].Add(receiver.id); } else { core.invitesPerAlliance.TryAdd(alliance.id, new List <int>()); core.invitesPerAlliance[alliance.id].Add(receiver.id); } if (core.invitesPerUser.ContainsKey(receiver.id)) { core.invitesPerUser[receiver.id].Add(alliance.id); } else { core.invitesPerUser.TryAdd(receiver.id, new List <int>()); core.invitesPerUser[receiver.id].Add(alliance.id); } core.dataConnection.insertInvite(alliance.id, receiver.id); } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } }
public static bool joinCheck(User user, int allianceId) { Core core = Core.Instance; if (!core.alliances.ContainsKey(allianceId)) { return(false); } Alliance alliance = core.alliances[allianceId]; List <Lockable> elementsToLock = new List <Lockable>(2); elementsToLock.Add(user); elementsToLock.Add(alliance); if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { //Prüfen ob der Nutzer noch Mitlgied einer ALlianz ist if (user.allianceId != 0 || user.group != null) { LockingManager.unlockAll(elementsToLock); return(false); } //check that user is invited: if (!core.invitesPerAlliance.ContainsKey(allianceId) || !core.invitesPerAlliance[allianceId].Any(e => e == user.id)) { LockingManager.unlockAll(elementsToLock); return(false); } alliance.join(user); //save alliance: core.dataConnection.saveAlliances(alliance); //members: Core.Instance.dataConnection.saveAllianceMembers(alliance); //remove invitation: Core.Instance.invitesPerAlliance[alliance.id].RemoveAll(userId => userId == user.id); if (Core.Instance.invitesPerUser.ContainsKey(user.id)) { Core.Instance.invitesPerUser[user.id].RemoveAll(allyId => allyId == alliance.id); } Core.Instance.dataConnection.removeInvite(alliance.id, user.id); //add to alliance communication if (Core.Instance.commNodes.Any(e => e.Value.connectionType == 4 && e.Value.connectionId == alliance.id)) { Core.Instance.commNodes.First(e => e.Value.connectionType == 4 && e.Value.connectionId == alliance.id).Value.addUserAndSave(user); } } catch (Exception ex) { core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }
public bool Abandon(int previousOwnerId, ref List <Ship> ships) { Core Core = Core.Instance; if (!Core.users.Any(e => e.Value.AiId == 3)) { return(false); } User Separatist = Core.users.First(e => e.Value.AiId == 3).Value; User oldUser = Core.users[this.userId]; List <Lockable> elementsToLock = new List <Lockable>(1); elementsToLock.Add(this); List <Ship> shipsChangingOwnership = new List <Ship>(); foreach (var ship in this.field.ships.Where(e => e.userid == oldUser.id && e.systemX == this.SystemX && e.systemY == this.SystemY)) { shipsChangingOwnership.Add(ship); elementsToLock.Add(ship); } if (!LockingManager.lockAllOrSleep(elementsToLock)) { return(false); } try { if (this.userId != previousOwnerId) { return(false); } this.userId = Separatist.id; foreach (var colBuilding in this.colonyBuildings) { colBuilding.userId = this.userId; } foreach (var ship in shipsChangingOwnership) { ship.userid = Separatist.id; ships.Add(ship); } //save colony and buildings Core.dataConnection.saveColonyFull(this.planet, this, false); //save Ships Core.dataConnection.saveShips(shipsChangingOwnership); GalacticEvents.AddNewEvent(GalacticEventType.ColonyAbandoned, int1: previousOwnerId, int2: this.id, string1: this.name); } catch (Exception ex) { Core.writeExceptionToLog(ex); } finally { LockingManager.unlockAll(elementsToLock); } return(true); }