public override LuaTable GetLuaTable(Mission mission) { Dictionary<object, object> map = new Dictionary<object, object> { {"message", message}, {"fontSize", FontSize}, {"time", time}, }; if (!string.IsNullOrEmpty(imagePath) && File.Exists(ImagePath)) { var image = new BitmapImage(new Uri(ImagePath)); map.Add("image", Path.GetFileName(ImagePath)); map.Add("imageWidth", image.PixelWidth); map.Add("imageHeight", image.PixelHeight); } else if (!string.IsNullOrWhiteSpace(imagePath)) { map.Add("image", ImagePath); map.Add("imageFromArchive", true); } if (!string.IsNullOrEmpty(soundPath) && File.Exists(SoundPath)) { map.Add("sound", Path.GetFileName(soundPath)); } else if (!string.IsNullOrWhiteSpace(soundPath)) { map.Add("sound", soundPath); map.Add("soundFromArchive", true); } return new LuaTable(map); }
override protected void _setCompleted(Mission mission, bool up, bool notify) { AndroidJNI.PushLocalFrame(100); using(AndroidJavaClass jniMissionStorage = new AndroidJavaClass("com.soomla.levelup.data.MissionStorage")) { jniMissionStorage.CallStatic("setCompleted", mission.ID, up, notify); } AndroidJNI.PopLocalFrame(IntPtr.Zero); }
public void Random_Destination() { // randomly choose a mission // current_mission = missions[Random.Range(0,missions.Length)]; current_mission = new Mission(); current_mission.start_portal = startPoint[Random.Range(0,startPoint.Count)]; // the destination can not be the start point's location List<GData.LocationType> locs = new List<GData.LocationType>(GameObject.FindObjectOfType<PortalSystem>(). Get_Protals()[current_mission.start_portal].locations); Debug.Log("Locs : " + locs.Count); current_mission.destination = endPoint[Random.Range(0,endPoint.Count)]; while(locs.Contains(current_mission.destination)) { current_mission.destination = endPoint[Random.Range(0,endPoint.Count)]; } current_mission.comment = "Find a way to " + current_mission.destination.ToString(); current_mission.comment = current_mission.comment.Replace("_", " "); // place the player PortalSystem sys = GameObject.FindObjectOfType<PortalSystem>(); sys.Place_Player(current_mission.start_portal); }
public static Mission getMission(String id) { Mission mission = null; String parameter = "id"; String query = DB.SELECT + "*" + DB.FROM + Net7.Tables.missions + DB.WHERE + ColumnData.GetName(Net7.Table_missions._mission_id) + DB.EQUALS + DB.QueryParameterCharacter + parameter; DataTable dataTable = DB.Instance.executeQuery(query, new String[]{parameter}, new String[] {id}); if (dataTable.Rows.Count == 1) { mission = new Mission(); mission.setId(id); mission.setXml(ColumnData.GetString(dataTable.Rows[0], Net7.Table_missions._mission_XML)); mission.setName(ColumnData.GetString(dataTable.Rows[0], Net7.Table_missions._mission_name)); String type = ColumnData.GetString(dataTable.Rows[0], Net7.Table_missions._mission_type); CommonTools.MissionType missionType; CommonTools.Enumeration.TryParse<CommonTools.MissionType>(type, out missionType); mission.setType(missionType); mission.setKey(ColumnData.GetString(dataTable.Rows[0], Net7.Table_missions._mission_key)); } return mission; }
public void generateMission() { if (currentMission != null) return; MissionNumber++; currentMission = new Mission(MissionNumber, previousMission); if (previousMission == Mission.MissionType.Boss || previousMission == Mission.MissionType.BaseAssault) { spawnPoints = new List<enemySpawnPoint>(); enemySpawnPoint[] sp = FindObjectsOfType<enemySpawnPoint>(); foreach (enemySpawnPoint s in sp) { spawnPoints.Add(s); } } previousMission = currentMission.type; Title.Display(currentMission.missionTitle); Type.Display(currentMission.missionType); Objective.Display(currentMission.missionObjective); Bonus.Display(currentMission.missionBonusObjective); Reward.Display(currentMission.Reward); bReward.Display(currentMission.bonusReward); Difficulty.Display(currentMission.missionDifficulty); clearRemainingEnemies(); setUpMission(); }
public async Task<IHttpActionResult> PutMission(int id, Mission mission) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != mission.Id) { return BadRequest(); } db.Entry(mission).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!MissionExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public void LoadDataromServer(string json_data) { var Json = SimpleJSON.JSON.Parse(json_data); missions = new List<Mission>(Json["missions"].Count); for (int a = 0; a < Json["missions"].Count; a++) { Mission newMission = new Mission(); newMission.id = int.Parse(Json["missions"][a]["id"]); newMission.islandId = int.Parse(Json["missions"][a]["islandId"]); newMission.qty = int.Parse(Json["missions"][a]["qty"]); switch (Json["missions"][a]["element"]) { case "MADERA": newMission.element = Mission.elements.MADERA; break; case "PIEDRAS": newMission.element = Mission.elements.PIEDRAS; break; case "ARENA": newMission.element = Mission.elements.ARENA; break; } newMission.description = Json["missions"][a]["description"]; // newMission.description = GetDescription(newMission); missions.Add(newMission); } //foreach(Mission mission in missions) //{ // Debug.Log("M: " + mission.description); //} }
/// <summary> /// Creates the mission from a hashtable sent over the PhotonNetwork. /// </summary> /// <param name="missionData">The hashtable containing the mission data.</param> public void SetMissionFromHashtable(Hashtable missionData) { print("mission created from hashtable"); Mission newMission = new Mission(missionData); activeMission = newMission; SetMissionTimer(); }
protected void Page_Load(object sender, EventArgs e) { if (_Request.Get("missionID") != null) { int missionID = _Request.Get<int>("missionID", Method.Get, 0); Mission mission = MissionBO.Instance.GetMission(missionID, true); if (mission.ParentID != null) m_ParentMission = MissionBO.Instance.GetMission(mission.ParentID.Value); } else if(_Request.Get("type") == null) { m_ParentMission = MissionBO.Instance.GetMission(_Request.Get<int>("pid", 0)); if (m_ParentMission == null) { ShowError("任务组不存在"); return; } } if (_Request.IsClick("savemission")) SaveMission(); }
//private DatabaseModel.Database<Mission> ListOfMissions = new DatabaseModel.Database<Mission>("ToDoList.txt"); // Instead the above we need to call the parent window public CreateTaskWindow(DateTime taskDate, Mission editMission = null) { InitializeComponent(); this.taskDate = taskDate; this.editMission = editMission; // this.missionFileControler = new MissionFileControler(); List<PriorityLevel> priorityLevels = new List<PriorityLevel>(); priorityLevels.Add(PriorityLevel.Low); priorityLevels.Add(PriorityLevel.Medium); priorityLevels.Add(PriorityLevel.Urgent); this.ComboBoxPriority.ItemsSource = priorityLevels; // set default value if (this.editMission == null) { this.ComboBoxPriority.SelectedValue = priorityLevels[0]; } else { this.Title = "Edit task"; this.ComboBoxPriority.SelectedValue = this.editMission.Priority; this.TextBoxName.Text = this.editMission.Name; this.TextBoxDescription.Text = this.editMission.Description; this.addButton.Content = "Update"; } }
public void DeleteMission(Mission mission) { string tempFile = "temp.txt"; string serializedMissionForDeleting = mission.Serialize(); FileStream fsRead = new FileStream(MissionFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); FileStream fsWrite = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite); using (StreamReader reader = new StreamReader(fsRead)) { using (StreamWriter writer = new StreamWriter(fsWrite)) { while (!reader.EndOfStream) { string line = reader.ReadLine(); if (!line.Equals(serializedMissionForDeleting)) { writer.WriteLine(line); } } } } File.Delete(MissionFileControler.MissionFilePath); File.Move(tempFile, MissionFileControler.MissionFilePath); }
private void btnNewMission_Click(object sender, EventArgs e) { var mission = new Mission() {Name = "NEW MISSION", PartyLevel = 1}; MissionLoader.Add(mission); lstMissions.DataSource = null; lstMissions.DataSource = MissionLoader.Get(); }
public override LuaTable GetLuaTable(Mission mission) { if (string.IsNullOrEmpty(imagePath) || !File.Exists(ImagePath)) { var map = new Dictionary<object, object> { {"message", message}, {"width", Width}, {"height", Height}, {"pause", Pause}, {"fontSize", FontSize}, }; if(!string.IsNullOrWhiteSpace(imagePath)) { map.Add("image", imagePath); map.Add("imageFromArchive", true); } return new LuaTable(map); } else { var image = new BitmapImage(new Uri(ImagePath)); var map = new Dictionary<object, object> { {"message", message}, {"image", Path.GetFileName(ImagePath)}, {"imageWidth", image.PixelWidth}, {"imageHeight", image.PixelHeight}, {"pause", Pause}, {"fontSize", FontSize}, }; return new LuaTable(map); } }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"cutsceneID", CutsceneID}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"noContinue", noContinue}, }; return new LuaTable(map); }
public void AddMission(string missionName,string description,List<float> missionValues) { Mission tempMission = new Mission(); tempMission.name = missionName; tempMission.description = StringFormater.Format(description,20); tempMission.m_values = missionValues; missions.Add(tempMission); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"message", Message}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"frames", frames}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"groups", LuaTable.CreateSet(groups)}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"instant", Instant}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"group", Group}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"countdown", Countdown??string.Empty}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"strength", Strength}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"playerNumber", mission.Players.IndexOf(Player)}, }; return new LuaTable(map); }
void SpawnMission() { Mission mission = new Mission(); mission.SetRandomMissionValues(); missions.Add(mission); UpdateMissionList(); gm.missionButtonLabel.text = "Missions (" + missions.Count.ToString() + ")"; }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"codeStr", CodeStr}, {"synced", Synced}, }; return new LuaTable(map); }
public override LuaTable GetLuaTable(Mission mission) { var map = new Dictionary<object, object> { {"units", LuaTable.CreateArray(Units)}, {"players", LuaTable.CreateArray(Players.Select(p => mission.Players.IndexOf(p)))}, }; return new LuaTable(map); }
public MissionView(Mission model) { Mapper.CreateMap<Mission, MissionView>(); Mapper.Map<Mission, MissionView>(model, this); this.created = model.created.ToString().Replace('T', ' '); this.updated = model.updated.ToString().Replace('T', ' '); this.date = model.date == null ? String.Empty : model.date.ToString(); }
public MissionView(Mission input) { Mapper.CreateMap<Mission, MissionView>(); Mapper.Map<Mission, MissionView>(input, this); this.created = input.created.ToString().Replace('T', ' '); this.employeeId = input.employee == null ? null : (int?)input.employee.id; this.customerId = input.customer.id; }
public MissionCondition(Conditions condition, int checkValue, Mission mission = null) { _condition = condition; _checkValue = checkValue; _name = GetName(_condition); //_mission = mission; //if (_mission != null) // _missionId = _mission.MissionId; }
public void Remove() { mission = null; desc.text = " "; count.text = " "; }
public static void SolveCaptureMission(Mission mission) { foreach (var pair in mission.factory.links.OrderBy(p => p.Value)) { Factory ally = pair.Key; int distance = pair.Value; if (ally.isAlly && ally.count > 1 && distance < 10) { int robotsAvailable = ally.armyAvailable;//ally.count - robotsToDefend - 1; //Console.Error.WriteLine(ally.id + ": " + robotsAvailable); if (robotsAvailable <= 0) //check if we have enough robots to send { continue; } if (Bomb.bombs.Values.Any(b => b.isAlly && b.end == mission.factory && b.turns > distance)) { continue; } mission.acceptedMission.Add(ally, robotsAvailable); //ally factory accepts the mission if (distance > mission.largestDistance) { mission.largestDistance = distance; mission.longestFactory = ally; } } } //ordered by distance to the factory var orderedAllies = mission.acceptedMission.OrderByDescending(p => p.Value); //ordered by distance int production = mission.factory.team == Team.Neutral ? 0 : mission.factory.production * (mission.largestDistance + 1); mission.troopsNeeded += mission.factory.isAlly ? 0 : production; //Console.Error.WriteLine(mission.factory.id + ": " + mission.troopsNeeded); Dictionary <Factory, int> newEnlisted = new Dictionary <Factory, int>(); foreach (var pair in orderedAllies) { Factory ally = pair.Key; int robotsAvailable = pair.Value; int robotsToSend = Math.Min(mission.troopsNeeded, robotsAvailable); mission.troopsNeeded -= robotsToSend; newEnlisted.Add(ally, robotsToSend); if (mission.troopsNeeded <= 0) { break; } } if (mission.troopsNeeded <= 0) { foreach (var pair in newEnlisted) { Factory ally = pair.Key; int robotsToSend = pair.Value; Action newAction = new Action(MoveType.Move, ally, mission.factory, robotsToSend); AddAction(newAction); } } }
public void SetLabels(Mission m) { description.text = m.missionDescription; cost.text = "Fuel Cost: " + m.fuelCost; reward.text = m.availableResource.resourceName + " " + m.availableResource.resourceQuantity; }
public void AddMission(Mission mission) { this.missions.Add(mission); }
public CaptureMissionSolver(Mission mission) { this.mission = mission; }
public ActionResult <IEnumerable <Mission> > Put([FromBody] Mission mission) { db.Missions.Update(mission); db.SaveChanges(); return(db.Missions.ToList()); }
public void GetUserMissions_Validation_Test(int id, bool exists, ActionResult <List <MissionTaskViewModel> > expected, int expCode) { //Arrange User dbUser = new User { UserId = 1, UserName = "******", Password = "******", EMail = "*****@*****.**" }; Mission dbMission = new Mission { Created = new DateTime(2020, 8, 5), Description = "Project1 for DHL", Finished = null, MissionName = "DHL Project1", Color = "#F0D87B", Start = new DateTime(2020, 8, 6), Status = 1, UserId = 1, CustomerId = 1 }; Task dbTask = new Task { UserId = 1, MissionId = 1, Status = 0, ActualHours = null, Created = new DateTime(2020, 10, 5), Description = "DHL Project 1 Task1", EstimatedHour = 8.30, Invoice = InvoiceType.Invoicable, Name = "Task1 DHL Project1", Start = new DateTime(2020, 10, 6), Finished = null }; TaskViewModel dbTaskViewModel = new TaskViewModel(); MissionTaskViewModel dbMissionTaskViewModel = new MissionTaskViewModel(); Customer dbCustomer = new Customer { Name = "DHL", Created = new DateTime(2020, 8, 5) }; Mock <IUserRepository> userRepoMock = new Mock <IUserRepository>(); userRepoMock.Setup(u => u.GetById(It.IsAny <int>())).Returns(dbUser); Mock <IMissionRepository> missionRepoMock = new Mock <IMissionRepository>(); missionRepoMock.Setup(m => m.GetById(It.IsAny <int>())).Returns(dbMission); Mock <ITaskRepository> taskRepoMock = new Mock <ITaskRepository>(); taskRepoMock.Setup(t => t.GetById(It.IsAny <int>())).Returns(dbTask); taskRepoMock.Setup(t => t.Exists(It.IsAny <int>())).Returns(exists); Mock <ICustomerRepository> customerRepoMock = new Mock <ICustomerRepository>(); customerRepoMock.Setup(c => c.GetById(It.IsAny <int>())).Returns(dbCustomer); Mock <IMissionMemberRepository> missionMemberRepoMock = new Mock <IMissionMemberRepository>(); Mock <IUnitOfWork> mockUOF = new Mock <IUnitOfWork>(); mockUOF.Setup(uow => uow.UserRepository).Returns(userRepoMock.Object); mockUOF.Setup(uow => uow.MissionRepository).Returns(missionRepoMock.Object); mockUOF.Setup(uow => uow.TaskRepository).Returns(taskRepoMock.Object); mockUOF.Setup(uow => uow.CustomerRepository).Returns(customerRepoMock.Object); mockUOF.Setup(uow => uow.MissionMemberRepository).Returns(missionMemberRepoMock.Object); var controller = new MissionController(mockUOF.Object, httpContextAccessorMock); //Act var result = controller.GetUserMissions(id); //Assert if (expected.GetType() != StatusCodes.Status500InternalServerError.GetType()) { Assert.IsType(expected.GetType(), result); } else { Assert.Equal(expCode, (result.Result as StatusCodeResult).StatusCode); } }
public override LuaTable GetLuaTable(Mission mission) { return(new LuaTable()); }
public void SubmitMissionScore(string login, string passwordHash, string missionName, int score, int gameSeconds, string missionVars = "") { missionName = Mission.GetNameWithoutVersion(missionName); using (var db = new ZkDataContext()) { var acc = AuthServiceClient.VerifyAccountHashed(login, passwordHash); if (acc == null) { Trace.TraceWarning("Invalid login attempt for {0}", login); System.Threading.Thread.Sleep(new Random().Next(2000)); } acc.Xp += GlobalConst.XpForMissionOrBots; var mission = db.Missions.Single(x => x.Name == missionName); if (score != 0 || mission.RequiredForMultiplayer) { var scoreEntry = mission.MissionScores.FirstOrDefault(x => x.AccountID == acc.AccountID); if (scoreEntry == null) { scoreEntry = new MissionScore() { MissionID = mission.MissionID, AccountID = acc.AccountID, Score = int.MinValue }; mission.MissionScores.Add(scoreEntry); } if (score > scoreEntry.Score) { var max = mission.MissionScores.Max(x => (int?)x.Score); if (max == null || max <= score) { mission.TopScoreLine = login; acc.Xp += 150; // 150 for getting top score } scoreEntry.Score = score; scoreEntry.Time = DateTime.UtcNow; scoreEntry.MissionRevision = mission.Revision; scoreEntry.GameSeconds = gameSeconds; } } acc.CheckLevelUp(); db.SaveChanges(); if (!acc.CanPlayMultiplayer) { if ( db.Missions.Where(x => x.RequiredForMultiplayer) .All(y => y.MissionScores.Any(z => z.AccountID == acc.AccountID))) { acc.CanPlayMultiplayer = true; db.SaveChanges(); Global.Server.PublishAccountUpdate(acc); Global.Server.GhostPm(acc.Name, "Congratulations! You are now authorized to play MultiPlayer games!"); } } } }
static void Main(string[] args) { List <Private> privates = new List <Private>(); StringBuilder sb = new StringBuilder(); string command; while ((command = Console.ReadLine()) != "End") { string[] commTokens = command.Split(); string soldierType = commTokens[0]; int id = int.Parse(commTokens[1]); string firstName = commTokens[2]; string lastName = commTokens[3]; switch (soldierType) { case "Private": decimal privateSalary = decimal.Parse(commTokens[4]); Private newPrivate = new Private(id, firstName, lastName, privateSalary); sb.AppendLine(newPrivate.ToString()); privates.Add(newPrivate); break; case "LeutenantGeneral": decimal leutenantSalary = decimal.Parse(commTokens[4]); List <Private> tempPrivates = new List <Private>(); for (int i = 5; i < commTokens.Length; i++) { int currId = int.Parse(commTokens[i]); var currPrivate = privates.FirstOrDefault(x => x.Id == currId); if (currPrivate != null) { tempPrivates.Add(currPrivate); } } LeutenantGeneral newLeut = new LeutenantGeneral(id, firstName, lastName, leutenantSalary, tempPrivates); sb.AppendLine(newLeut.ToString()); break; case "Engineer": decimal engineerSalary = decimal.Parse(commTokens[4]); CorpsType currEngCorps; bool isEngCorpsValid = Enum.TryParse(commTokens[5], out currEngCorps); if (isEngCorpsValid) { List <Repair> repairs = new List <Repair>(); for (int i = 6; i < commTokens.Length; i += 2) { string partName = commTokens[i]; int workHours = int.Parse(commTokens[i + 1]); Repair newRepair = new Repair(partName, workHours); repairs.Add(newRepair); } Engineer newEngineer = new Engineer(id, firstName, lastName, engineerSalary, currEngCorps, repairs); sb.AppendLine(newEngineer.ToString()); } break; case "Commando": decimal commandoSalary = decimal.Parse(commTokens[4]); CorpsType currCorps; bool isCorpsValid = Enum.TryParse(commTokens[5], out currCorps); if (isCorpsValid) { List <Mission> missions = new List <Mission>(); for (int i = 6; i < commTokens.Length; i += 2) { string currCodeName = commTokens[i]; StateType missionState; bool isMissionValid = Enum.TryParse(commTokens[i + 1], out missionState); if (isMissionValid) { Mission addMission = new Mission(currCodeName, missionState); missions.Add(addMission); } } Commando newCommando = new Commando(id, firstName, lastName, commandoSalary, currCorps, missions); sb.AppendLine(newCommando.ToString()); } break; case "Spy": int codeNum = int.Parse(commTokens[4]); Spy newSpy = new Spy(id, firstName, lastName, codeNum); sb.AppendLine(newSpy.ToString()); break; default: break; } } string result = sb.ToString().TrimEnd(); Console.WriteLine(result); }
public static bool UpdateMissionDetailInformation(Mission mission, string descriptionTerm, MissionDetailPage page, ExtendedMissionDetails details) { // TODO: Cooperation with the other binder readers (multiple bombs, factory mode) is probably necessary. // There'll be race conditions. If they check first and then this, this should work, but // if this checks first and then they, they'll likely throw EM in the missing mod types pool again. // TODO: Submit a PR there to account for the new boy in town. Although I'm not entirely sure what takes care of // 'Factory Mode' mod type. I couldn't find anything about it in Factory Mode's code. A better system may be possible. List <string> missingModTypes = new List <string>(); int maxModuleCount = Math.Max(11, ModManager.Instance.GetMaximumModules()); int maxFrontFaceModuleCount = Math.Max(5, ModManager.Instance.GetMaximumModulesFrontFace()); int notModulesCount = 0; //int partialPools = 0; bool canStart = false; bool notSupported = false; TextMeshPro description = page.TextDescription; string moduleCountText = page.TextModuleCount.text; moduleCountText = moduleCountText.Split(' ')[0]; foreach (ComponentPool pool in details.GeneratorSetting.ComponentPools) { int counter = 0; foreach (string modType in pool.ModTypes) { if (modType == "Factory Mode") { notSupported = true; // TODO: Fix this together with the Multiple Bombs team. if (!FindMultipleBombs() || counter > 0) { missingModTypes.Add(modType); } else { notModulesCount++; } break; } if (modType.StartsWith("Multiple Bombs")) { notSupported = true; // TODO: Fix this together with the Multiple Bombs team, as right now this overrides multiple bombs doing a missing component error if one of the modules is missing. // Multiple Bombs tosses the entire component pool and only checks index 0. We will do the same. if (!FindMultipleBombs() || counter > 0) { missingModTypes.Add(modType); } else { notModulesCount++; } break; } if (!ModManager.Instance.HasBombComponent(modType)) { missingModTypes.Add(modType); } counter++; } } int totalComponentPools = details.GeneratorSetting.ComponentPools.Count; if (notSupported) { // todo: Support multiple bombs. page.TextDescription.text = "Using both Extended Mission Settings & Multiple Bombs/Factory Mode is not supported at this time."; canStart = false; } else if (description.text.StartsWith("A room that can support more bombs is required.")) { // multiple bombs already looked at this and determined we need a different room, so the mission can't start regardless. Don't bother. canStart = false; } else if (missingModTypes.Count > 0) { canStart = false; Localization.SetTerm("BombBinder/error_missingModules", description.gameObject); Localization.SetParameter("MISSING_MODULES_LIST", string.Join("\n", missingModTypes.ToArray()), description.gameObject); } else if (totalComponentPools - notModulesCount > maxModuleCount) { canStart = false; Localization.SetTerm("BombBinder/error_needABiggerBomb", description.gameObject); Localization.SetParameter("MAX_MODULE_COUNT", maxModuleCount.ToString(), description.gameObject); } else if (mission.GeneratorSetting.FrontFaceOnly && totalComponentPools - notModulesCount > maxFrontFaceModuleCount) { canStart = false; Localization.SetTerm("BombBinder/error_needABiggerBomb", description.gameObject); Localization.SetParameter("MAX_MODULE_COUNT", maxModuleCount.ToString(), description.gameObject); } else if (details.InvalidJson) { canStart = false; page.TextDescription.text = "An error occured reading the extended mission settings for this mission."; } else { canStart = true; Localization.SetTerm(descriptionTerm, description.gameObject); } int totalTotalComponentPools = mission.GeneratorSetting.ComponentPools.Count; int writtenModuleCount = -1; int selfCount = totalTotalComponentPools - totalComponentPools; if (!int.TryParse(moduleCountText, out writtenModuleCount)) { writtenModuleCount = totalTotalComponentPools; } if (writtenModuleCount > totalTotalComponentPools) { // Multiple Bombs established we have more modules due to multiple bombs. Localization.SetTerm("BombBinder/txtModuleCount", page.TextModuleCount.gameObject); Localization.SetParameter("MODULE_COUNT", (writtenModuleCount - selfCount).ToString(), page.TextModuleCount.gameObject); } else { Localization.SetTerm("BombBinder/txtModuleCount", page.TextModuleCount.gameObject); Localization.SetParameter("MODULE_COUNT", (totalComponentPools - notModulesCount).ToString(), page.TextModuleCount.gameObject); } return(canStart); }
private void MapWaypointMessengerAction(MapWaypointMessenger obj) { //NavTask.NavPath.Clear(); //ServiceLocator.Current.GetInstance<IMap>().RemoveAllShape(); byte index = 1; var mission = (MissionPackage.Mission)Mission; ITask first = null; foreach (Task task in mission.Tasks) { if (task.TaskID == obj.TaskId) { first = task; break; } } var taskNav = first as MavlinkTaskNav; if (taskNav != null) { taskNav.NavPath.Clear(); foreach (var waypoint in obj.Points) { double x = waypoint.X, y = waypoint.Y; //Utils.Utils.ConvertGeoToMercator(ref x, ref y); taskNav.NavPath.Add(new MavlinkWaypoint { Id = index, Command = (ushort)MissionMavCmd.WAYPOINT, Latitude = y, Longitude = x, Altitude = DefaultAltitude, Param1 = 0, Param2 = 0, Param3 = 0, Param4 = 0 }); index++; } } else { var mavlinkTaskNav = new MavlinkTaskNav("Task_" + (ushort)obj.TaskId, (ushort)obj.TaskId); foreach (var waypoint in obj.Points) { double x = waypoint.X, y = waypoint.Y; //Utils.Utils.ConvertGeoToMercator(ref x, ref y); mavlinkTaskNav.NavPath.Add(new MavlinkWaypoint { Id = index, Command = (ushort)MissionMavCmd.WAYPOINT, Latitude = y, Longitude = x, Altitude = DefaultAltitude, Param1 = 0, Param2 = 0, Param3 = 0, Param4 = 0 }); index++; } Mission.AddTask(mavlinkTaskNav); } Messenger.Default.Send(new UpdataMissionMessenger { MissionId = Mission.MissionID }); }
/// <exclude/> public override void OnMissionBehaviourInitialize(Mission mission) { base.OnMissionBehaviourInitialize(mission); SubModule.OnMissionBehaviourInitialize(mission); }
public ActionResult <IEnumerable <Mission> > Delete(Mission mission) { db.Missions.Remove(mission); db.SaveChanges(); return(db.Missions.ToList()); }
public void CompleteMission(Mission mission) { mission.State = "Finished"; }
// GET: Missions/duritanium-man public ActionResult Details(string link) { if (string.IsNullOrEmpty(link)) { return(RedirectToAction("index", "home")); } Mission mission = db.Missions.Where(m => m.MissionLink.Equals(link)).FirstOrDefault(); if (mission == null) { return(HttpNotFound()); } //if it is in review or unpubilshed only an aadministrator or the author can view it if (mission.Status == Models.FoundryMissionModels.Enums.MissionStatus.InReview || mission.Status == Models.FoundryMissionModels.Enums.MissionStatus.Unpublished) { if ((mission.Author != null && !mission.Author.UserName.Equals(User.Identity.Name)) && (!User.IsInRole("Administrator"))) { return(HttpNotFound()); } } //if it is removed only an admnistrator can view it if (mission.Status == Models.FoundryMissionModels.Enums.MissionStatus.Removed) { if (!User.IsInRole("Administrator")) { return(HttpNotFound()); } } ViewMissionViewModel viewMission = new ViewMissionViewModel() { Id = mission.Id, Author = mission.Author, AuthorCrypticTag = mission.AuthorUserId, CrypticId = mission.CrypticId.ToUpper(), Name = mission.Name, Description = mission.Description, Faction = mission.Faction, FactionImageUrl = MissionHelper.GetBigFactionImageUrl(mission.Faction), MinimumLevel = mission.MinimumLevel, MinimumLevelImageUrl = MissionHelper.GetBigLevelImageUrl(mission.MinimumLevel, mission.Faction), DateLastUpdated = mission.DateLastUpdated, Length = mission.Length, Tags = mission.Tags.OrderBy(t => t.TagName).ToList(), Videos = mission.Videos.OrderBy(v => v.Order).Select(v => v.YoutubeVideoId).ToList(), Status = mission.Status, MissionLink = mission.MissionLink, Images = mission.Images.OrderBy(i => i.Order).Select(i => i.Filename).ToList(), HasExport = MissionExportHelper.HasExport(mission.Id), }; //It's okay to show the mission now if (TempData["Message"] != null) { ViewBag.Message = TempData["Message"]; } return(View(viewMission)); }
public ActionResult Edit(string link) { if (string.IsNullOrEmpty(link)) { return(RedirectToAction("index", "home")); } Mission mission = db.Missions.Where(m => m.MissionLink.Equals(link)).FirstOrDefault(); if (mission == null) { return(HttpNotFound()); } //only people who can edit a mission are the author or an admin if (!mission.Author.UserName.Equals(User.Identity.Name) && !User.IsInRole(ConstantsHelper.AdminRole)) { return(HttpNotFound()); } //if the user is not an admin and it is removed it doesn't exist if (mission.Status == MissionStatus.Removed && !User.IsInRole(ConstantsHelper.AdminRole)) { return(HttpNotFound()); } var publishedSelectItems = new List <SelectListItem>(); #region Published Select List publishedSelectItems.Add(new SelectListItem() { Value = "false", Text = "No", }); publishedSelectItems.Add(new SelectListItem() { Value = "true", Text = "Yes", }); #endregion var editModel = new EditMissionViewModel(); editModel.Id = mission.Id; editModel.CrypticId = mission.CrypticId; editModel.Name = mission.Name; editModel.Description = mission.Description; editModel.Length = mission.Length; editModel.Faction = mission.Faction; editModel.MinimumLevel = mission.MinimumLevel; editModel.Spotlit = mission.Spotlit; editModel.Published = mission.Published; editModel.Status = mission.Status; editModel.Author = mission.Author; editModel.AutoApprove = mission.Author.AutoApproval; editModel.Tags = mission.Tags.Select(t => t.TagName).ToList(); editModel.OldImages = mission.Images.OrderBy(i => i.Order).Select(i => i.Filename).ToList(); editModel.OldVideos = mission.Videos.OrderBy(v => v.Order).Select(v => v.YoutubeVideoId).ToList(); mission.MissionLink = MissionHelper.GetMissionLink(db, mission); var unselectedTags = db.MissionTagTypes.Select(t => t.TagName).ToList(); foreach (var tags in editModel.Tags) { unselectedTags.Remove(tags); } ViewBag.AvailableTags = unselectedTags; ViewBag.PublishedSelectList = new SelectList(publishedSelectItems, "Value", "Text"); ViewBag.MinimumLevelSelectList = new SelectList(MissionHelper.GetMinimumLevelSelectList(), "Value", "Text"); return(View(editModel)); }
public Quickplay(string uid, string masterJid, RoomType roomType, GameMode?gameMode, Mission mission) { Uid = uid; //used when inviting, starting, cancelling and on_started, on_canceled events MasterJid = masterJid; //used in IsMaster check and during p2p sends RoomType = roomType; //used when starting and inviting GameMode = gameMode; //used when starting and inviting Mission = mission; //used when starting and inviting InvitedPlayers = new List <ProfileInfo>(); }
private string UploadExportFile(HttpPostedFileBase exportFile) { //first read the file var b = new BinaryReader(exportFile.InputStream); var binData = b.ReadBytes(exportFile.ContentLength); var text = System.Text.Encoding.UTF8.GetString(binData); var missionlink = ""; Mission mission = null; //Get the mission object try { mission = MissionExportHelper.ParseExportToMission(db, text); } catch { throw new Exception("Error parsing upload file. Please contact us at [email protected] or @STOMissions on twitter so we can determine what is wrong."); } //now that we have the mission we need to first check if it exists or not. var samemissions = db.Missions.Where(m => m.Name.Equals(mission.Name)).ToList(); if (samemissions.Count > 0) { foreach (var samemission in samemissions) { //We check with name check.then author check //if the author is null we cannot add it as we can't make sure it is the same if (samemission.Author == null) { throw new Exception("Another mission with the same name and ambiguous author already exists. Please add your mission manually. If you believe that mission belongs to you please contact us at [email protected] or @STOMissions on twitter so we can link it to your account."); } //now check author if (mission.AuthorUserId.ToUpper().Equals(samemission.Author.CrypticTag.ToUpper())) { missionlink = samemission.MissionLink; //if it is the same this is the exact same mission now make sure that the person uploading it is the author, or an admit if (User.Identity.Name.Equals(samemission.Author.UserName) || User.IsInRole(ConstantsHelper.AdminRole)) { samemission.DateLastUpdated = DateTime.Now; db.SaveChanges(); break; } else { //if it is not the same user name they are not allowed to update it. //just go to the mission return(missionlink); } } } } //if mission link is still empty means we haven't found the same mission so lets add it if (string.IsNullOrWhiteSpace(missionlink)) { missionlink = MissionHelper.GetMissionLink(db, mission); mission.MissionLink = missionlink; mission.DateLastUpdated = DateTime.Now; mission.DateAdded = DateTime.Now; mission.CrypticId = MissionExportHelper.GenerateRandomID(); mission.Length = MissionLength.FifteenToThirtyMinutes; mission.Published = false; mission.Spotlit = false; mission.Status = MissionStatus.Unpublished; db.Missions.Add(mission); db.SaveChanges(); } //get the mission's id var id = db.Missions.Where(m => m.MissionLink.Equals(missionlink)).FirstOrDefault().Id; //set the export file MissionExportHelper.SaveExportFile(text, id); return(missionlink); }
static void Main(string[] args) { var army = new List <ISoldier>(); string input; while ((input = Console.ReadLine()) != "End") { var inputArgs = input .Split(); var type = inputArgs[0]; var id = inputArgs[1]; var firstName = inputArgs[2]; var lastName = inputArgs[3]; var salary = decimal.Parse(inputArgs[4]); if (type == "Private") { var @private = new Private(id, firstName, lastName, salary); army.Add(@private); } else if (type == "LeutenantGeneral") { var general = new LeutenantGeneral(id, firstName, lastName, salary); for (int i = 5; i < inputArgs.Length; i++) { var currentId = inputArgs[i]; var @private = army .First(p => p.Id == currentId); general.AddPrivate(@private); } army.Add(general); } else if (type == "Engineer") { try { var corps = inputArgs[5]; var engineer = new Engineer(id, firstName, lastName, salary, corps); for (int i = 6; i < inputArgs.Length; i += 2) { var partName = inputArgs[i]; var workHours = int.Parse(inputArgs[i + 1]); var repair = new Repair(partName, workHours); engineer.AddRepair(repair); } army.Add(engineer); } catch (Exception) { } } else if (type == "Commando") { var corps = inputArgs[5]; try { var commando = new Commando(id, firstName, lastName, salary, corps); for (int i = 6; i < inputArgs.Length; i += 2) { try { var codeName = inputArgs[i]; var state = inputArgs[i + 1]; var mission = new Mission(codeName, state); commando.AddMission(mission); } catch (Exception) { continue; } } army.Add(commando); } catch (Exception) { } } else if (type == "Spy") { var codeNumber = (int)salary; var spy = new Spy(id, firstName, lastName, codeNumber); army.Add(spy); } } foreach (var soldier in army) { Type type = soldier.GetType(); var actual = Convert.ChangeType(soldier, type); Console.WriteLine(actual); } }
public ActionResult Submit([Bind(Include = "CrypticId,Name,Description,Length,Faction,MinimumLevel,Spotlit,Published,Tags,Images,Videos")] SubmitMissionViewModel missionViewModel, string submitButton) { if (ModelState.IsValid) { //check if cryptic id is already used if (db.Missions.Any(m => m.CrypticId.Equals(missionViewModel.CrypticId))) { ModelState.AddModelError("DuplicateCrypticID", "Cryptic ID already exists."); List <SelectListItem> publishedSelectItems = MissionHelper.GetYesNoSelectList(); ViewBag.AvailableTags = db.MissionTagTypes.Select(t => t.TagName).ToList(); ViewBag.PublishedSelectList = new SelectList(publishedSelectItems, "Value", "Text"); ViewBag.MinimumLevelSelectList = new SelectList(MissionHelper.GetMinimumLevelSelectList(), "Value", "Text"); return(View(missionViewModel)); } ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); Mission mission = new Mission(); #region Copy Info mission.CrypticId = missionViewModel.CrypticId.ToUpper(); mission.Description = missionViewModel.Description; mission.Faction = missionViewModel.Faction; mission.Length = missionViewModel.Length; mission.MinimumLevel = missionViewModel.MinimumLevel; mission.Name = missionViewModel.Name; mission.Published = missionViewModel.Published; mission.Spotlit = missionViewModel.Spotlit; #endregion if (missionViewModel.Tags != null && missionViewModel.Tags.Count > 0) { mission.Tags = db.MissionTagTypes.Where(t => missionViewModel.Tags.Contains(t.TagName)).ToList(); } else { mission.Tags = new List <MissionTagType>(); } mission.MissionLink = MissionHelper.GetMissionLink(db, mission); mission.Author = user; mission.DateAdded = DateTime.Now; mission.DateLastUpdated = DateTime.Now; if (submitButton.Equals("Save and Publish")) { if (user.AutoApproval) { mission.Status = Models.FoundryMissionModels.Enums.MissionStatus.Published; } else { mission.Status = Models.FoundryMissionModels.Enums.MissionStatus.InReview; //mission.Status = Models.FoundryMissionModels.Enums.MissionStatus.Published; try { EmailHelper.ReportMissionNeedsApproval(mission); } catch { } } } else //if (submitButton.Equals("Save")) { //don't do anything, leave it at the current status (default = unpublished) //mission.Status = Models.FoundryMissionModels.Enums.MissionStatus.Unpublished; } mission.Spotlit = false; db.Missions.Add(mission); db.SaveChanges(); //remove null if there is a null if (missionViewModel.Images.Count > 0) { if (missionViewModel.Images[missionViewModel.Images.Count - 1] == null) { missionViewModel.Images.RemoveAt(missionViewModel.Images.Count - 1); } } if (missionViewModel.Images.Count > 0) { try { var images = MissionImagesHelper.ValidateImages(missionViewModel.Images); MissionImagesHelper.AddImages(images, mission); db.SaveChanges(); } catch { TempData["Message"] = "An error occured while adding images."; } } //remove null if there is a null if (missionViewModel.Videos.Count > 0) { if (missionViewModel.Videos[missionViewModel.Videos.Count - 1] == null) { missionViewModel.Videos.RemoveAt(missionViewModel.Videos.Count - 1); } } if (missionViewModel.Videos.Count > 0) { try { var videos = MissionVideosHelper.GetVideoIds(missionViewModel.Videos); MissionVideosHelper.AddVideos(videos, mission); db.SaveChanges(); } catch { if (!string.IsNullOrEmpty(TempData[""] as string)) { TempData["Message"] = "Errors when adding images and videos."; } else { TempData["Message"] = "An error occured while adding videos."; } } } return(RedirectToAction("details", new { link = mission.MissionLink })); } return(View(missionViewModel)); }
public Controller() { this.astronautRepository = new AstronautRepository(); this.planetRepository = new PlanetRepository(); this.mission = new Mission(); }
static void Postfix(MissionUICtr __instance, GridPage ___missionTitleGrid) { void RestartMission(int index) { MissionType curShowType = curShowTypeByRef(__instance); List <MissionHistoryRecord> historyRecord = Module <MissionManager> .Self.HistoryRecord; List <Mission> missionProgress = Module <MissionManager> .Self.GetMissionRunning(); List <MissionHistoryRecord> missionNormalDone = new List <MissionHistoryRecord>(); for (int i = 0; i < historyRecord.Count; i++) { if (!historyRecord[i].IsOrderMission) { missionNormalDone.Add(historyRecord[i]); } } MissionBaseInfo m = null; if (curShowType == MissionUICtr.MissionType.progress && index < missionProgress.Count && index >= 0) { Dbgl("clicked progress mission"); m = MissionManager.GetmissionBaseInfo(missionProgress[index].InstanceID); } else if (curShowType == MissionUICtr.MissionType.normalDone && index < missionNormalDone.Count && index >= 0) { m = MissionManager.GetmissionBaseInfo(missionNormalDone[index].InstanceId); Dbgl("clicked done mission " + missionNormalDone[index].InstanceId + " " + missionNormalDone[index].MissionNo); List <Mission> doneMissions = missions_EndTypeByRef(MissionManager.GetInstance); Dbgl("done missions before: " + doneMissions.Count); doneMissions.RemoveAll((Mission it) => it.InstanceID == m.InstanceID); MissionManager.GetInstance.HistoryRecord.RemoveAll((MissionHistoryRecord hr) => hr.InstanceId == m.InstanceID); missionNormalDone.Remove(missionNormalDone[index]); Dbgl("done missions after: " + doneMissions.Count); MissionManager.GetInstance.GetType().GetField("m_missions_End", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(MissionManager.Self, doneMissions); Dbgl("real done missions after: " + missions_EndTypeByRef(MissionManager.Self).Count); } if (m != null) { Dbgl("clicked mission not null id:" + m.InstanceID + " number:" + m.MissionNO + " name: " + TextMgr.GetStr(m.MissionNameId, -1)); return; //MethodInfo dynMethod = MissionManager.GetInstance.GetType().GetMethod("InitSaveData", BindingFlags.NonPublic | BindingFlags.Instance); //dynMethod.Invoke(MissionManager.GetInstance, new object[] { }); MissionManager.GetInstance.UpgradeRecord(); MissionManager.GetInstance.RefreshAllNpcMissionIcon(); MissionManager.GetInstance.DispatcherMissionTargetRefresh(); MissionManager.GetInstance.FreshTrace(); Mission mi = new Mission(); mi.InitFromBaseInfo(m); MissionManager.GetInstance.DeliverMission(mi); } } ___missionTitleGrid.OnMiddleClick += RestartMission; }
public bool IsMission(Mission a_mission) { return(a_mission.m_type == m_type && a_mission.m_location == m_location && (m_type != eMissiontype.eDestroy || a_mission.m_objObject == m_objObject)); }
public void GetAllMissionsBySearchString_Validation_Test(string searchString, object expected) { //Arrange Mission dbMission = new Mission { Created = new DateTime(2020, 8, 5), Description = "Project1 for DHL", Finished = null, MissionName = "DHL Project1", Color = "#F0D87B", Start = new DateTime(2020, 8, 6), Status = 1, UserId = 1, CustomerId = 1 }; Customer dbCustomer = new Customer { Name = "DHL", Created = new DateTime(2020, 8, 5) }; List <Customer> dbCustomers = new List <Customer>(); dbCustomers.Add(dbCustomer); Task dbTask = new Task { UserId = 1, MissionId = 1, Status = 0, ActualHours = null, Created = new DateTime(2020, 10, 5), Description = "DHL Project 1 Task1", EstimatedHour = 8.30, Invoice = InvoiceType.Invoicable, Name = "Task1 DHL Project1", Start = new DateTime(2020, 10, 6), Finished = null }; Mock <IMissionRepository> missionRepoMock = new Mock <IMissionRepository>(); missionRepoMock.Setup(m => m.GetById(It.IsAny <int>())).Returns(dbMission); Mock <ICustomerRepository> customerRepoMock = new Mock <ICustomerRepository>(); customerRepoMock.Setup(c => c.GetById(It.IsAny <int>())).Returns(dbCustomer); customerRepoMock.Setup(c => c.Search <Customer>(It.IsAny <Func <Customer, string> >(), It.IsAny <string>())).Returns(dbCustomers); Mock <ITaskRepository> taskRepoMock = new Mock <ITaskRepository>(); taskRepoMock.Setup(t => t.GetById(It.IsAny <int>())).Returns(dbTask); Mock <IUnitOfWork> mockUOF = new Mock <IUnitOfWork>(); mockUOF.Setup(uow => uow.MissionRepository).Returns(missionRepoMock.Object); mockUOF.Setup(uow => uow.TaskRepository).Returns(taskRepoMock.Object); mockUOF.Setup(uow => uow.CustomerRepository).Returns(customerRepoMock.Object); var controller = new MissionController(mockUOF.Object, httpContextAccessorMock); //Act var result = controller.GetAllMissionsBySearchString(searchString); //Assert if (expected.GetType() != StatusCodes.Status500InternalServerError.GetType()) { Assert.IsType(expected.GetType(), result); } else if (searchString == " ") { Assert.Equal(expected, result.Value.Count()); } else { Assert.Equal(expected, (result.Result as StatusCodeResult).StatusCode); } }
public ModOptionsDialog() { InitializeComponent(); Mission = MainWindow.Instance.Mission; DataContext = Mission; }
public void GetSpecificMission_Validation_Test(int id, bool exists, object expected) { //Arrange User dbUser = new User { UserId = 1, UserName = "******", Password = "******", EMail = "*****@*****.**" }; Customer dbCustomer = new Customer(); Mission dbMission = new Mission { MissionId = 1, CustomerId = 1 }; List <Task> dbTasks = new List <Task> { new Task { TaskId = 1, } }; List <MissionMember> dbMissionMember = new List <MissionMember>(); Mock <IUserRepository> userRepoMock = new Mock <IUserRepository>(); userRepoMock.Setup(u => u.GetById(It.IsAny <int>())).Returns(dbUser); Mock <IMissionRepository> missionRepoMock = new Mock <IMissionRepository>(); missionRepoMock.Setup(r => r.Exists(It.IsAny <int>())).Returns(exists); missionRepoMock.Setup(r => r.GetById(It.IsAny <int>())).Returns(dbMission); Mock <ITaskRepository> taskRepoMock = new Mock <ITaskRepository>(); taskRepoMock.Setup(r => r.GetAllByMissionId(It.IsAny <int>())).Returns(dbTasks); Mock <IMissionMemberRepository> missionMemberRepoMock = new Mock <IMissionMemberRepository>(); missionMemberRepoMock.Setup(r => r.GetAllByMissionId(It.IsAny <int>())).Returns(dbMissionMember); Mock <ICustomerRepository> customerRepoMock = new Mock <ICustomerRepository>(); customerRepoMock.Setup(u => u.GetById(It.IsAny <int>())).Returns(dbCustomer); Mock <IUnitOfWork> mockUOF = new Mock <IUnitOfWork>(); mockUOF.Setup(uow => uow.UserRepository).Returns(userRepoMock.Object); mockUOF.Setup(uow => uow.MissionRepository).Returns(missionRepoMock.Object); mockUOF.Setup(uow => uow.MissionMemberRepository).Returns(missionMemberRepoMock.Object); mockUOF.Setup(uow => uow.TaskRepository).Returns(taskRepoMock.Object); mockUOF.Setup(uow => uow.CustomerRepository).Returns(customerRepoMock.Object); var controller = new MissionController(mockUOF.Object, httpContextAccessorMock); //Act var result = controller.GetSpecificMission(id); //Assert if (expected.GetType() != StatusCodes.Status400BadRequest.GetType()) { Assert.IsType(expected.GetType(), result.Value); } else { Assert.Equal(expected, (result.Result as ObjectResult).StatusCode); } }
public void SendMission(Mission mission, List <MissionSlot> slots, string author, string password, Mod modInfo) { if (mission == null) { throw new ApplicationException("Mission is null"); } Account acc = null; var db = new ZkDataContext(); if (Debugger.IsAttached) { acc = db.Accounts.SingleOrDefault(x => x.Name == "Testor303"); } else { acc = AuthServiceClient.VerifyAccountPlain(author, password); } if (acc == null) { Trace.TraceWarning("Invalid login attempt for {0}", author); System.Threading.Thread.Sleep(new Random().Next(2000)); throw new ApplicationException("Cannot verify user account"); } Mission prev = db.Missions.SingleOrDefault(x => x.MissionID == mission.MissionID || (x.Name == mission.Name && x.AccountID == acc.AccountID)); // previous mission by id or name + account if (prev == null && db.Missions.Any(x => x.Name == mission.Name)) { throw new ApplicationException("Mission name must be unique"); } var map = db.Resources.SingleOrDefault(x => x.InternalName == mission.Map && x.TypeID == ZkData.ResourceType.Map); if (map == null) { throw new ApplicationException("Map name is unknown"); } var mod = db.Resources.SingleOrDefault(x => x.InternalName == mission.Mod && x.TypeID == ZkData.ResourceType.Mod); if (mod == null) { throw new ApplicationException("Mod name is unknown"); } //if (db.Resources.Any(x => x.InternalName == mission.Name && x.MissionID != null)) throw new ApplicationException("Name already taken by other mod/map"); modInfo.MissionMap = mission.Map; if (prev != null) { if (prev.AccountID != acc.AccountID && acc.AdminLevel < AdminLevel.Moderator) { throw new ApplicationException("Invalid author or password"); } prev.Description = mission.Description; prev.DescriptionStory = mission.DescriptionStory; prev.Mod = mission.Mod; prev.Map = mission.Map; prev.Name = mission.Name; prev.ScoringMethod = mission.ScoringMethod; prev.ModRapidTag = mission.ModRapidTag; prev.ModOptions = mission.ModOptions; prev.Image = mission.Image; prev.MissionEditorVersion = mission.MissionEditorVersion; prev.SpringVersion = mission.SpringVersion; prev.Revision++; prev.Mutator = mission.Mutator; prev.ForumThread.Title = mission.Name; prev.Script = mission.Script; mission = prev; } else { mission.CreatedTime = DateTime.UtcNow; mission.ForumThread = new ForumThread() { Title = mission.Name, ForumCategory = db.ForumCategories.FirstOrDefault(x => x.ForumMode == ForumMode.Missions), CreatedAccountID = acc.AccountID, LastPostAccountID = acc.AccountID }; mission.ForumThread.UpdateLastRead(acc.AccountID, true); db.Missions.InsertOnSubmit(mission); } mission.AccountID = acc.AccountID; mission.Script = Regex.Replace(mission.Script, "GameType=([^;]+);", (m) => { return(string.Format("GameType={0};", mission.NameWithVersion)); }); mission.MinHumans = slots.Count(x => x.IsHuman && x.IsRequired); mission.MaxHumans = slots.Count(x => x.IsHuman); mission.ModifiedTime = DateTime.UtcNow; mission.IsDeleted = true; mission.IsCoop = slots.Where(x => x.IsHuman).GroupBy(x => x.AllyID).Count() == 1; db.SaveChanges(); var updater = new MissionUpdater(); updater.UpdateMission(db, mission, modInfo); mission.IsDeleted = false; db.SaveChanges(); }
public MissionPlanner(Mission mission) { this.mission = mission; }
public abstract bool SupportsContent(Mission mission);