public void GIVEN_multiple_input_metrics_AND_one_project_WHEN_estimating_time_to_completion_THEN_returned_number_of_work_days_depends_on_randomly_selected_metrics( IReadOnlyCollection <ThroughputPerDay> throughputs, Project project, Queue <int> selectedIndices, double expectedNumberOfDaysRequired) { var inputMetrics = ToInputMetrics(throughputs); var roadmap = new Roadmap(new[] { project }); randomNumberGeneratorMock .Setup(rng => rng.GetRandomIndex(throughputs.Count)) .Returns(selectedIndices.Dequeue); var estimator = new TimeTillCompletionEstimator(inputMetrics, randomNumberGeneratorMock.Object, someMaximumNumberOfIterations); var estimations = estimator.Estimate(roadmap); Assert.Equal(2, estimations.Count); WorkEstimate roadmapWorkEstimate = estimations[0]; Assert.Equal("Roadmap", roadmapWorkEstimate.Identifier); AssertExpectedNumberOfWorkingDaysIsEqual(expectedNumberOfDaysRequired, roadmapWorkEstimate); AssertEstimateIsDeterminate(roadmapWorkEstimate); WorkEstimate projectWorkEstimate = estimations[1]; Assert.Equal("Project", projectWorkEstimate.Identifier); AssertExpectedNumberOfWorkingDaysIsEqual(expectedNumberOfDaysRequired, projectWorkEstimate); AssertEstimateIsDeterminate(projectWorkEstimate); }
public void GIVEN_one_input_metric_AND_one_project_WHEN_estimating_time_to_completion_THEN_return_number_of_work_days( ThroughputPerDay throughput, Project project, double expectedNumberOfDaysRequired) { var inputMetrics = ToInputMetrics(new[] { throughput }); var roadmap = new Roadmap(new[] { project }); var estimator = new TimeTillCompletionEstimator(inputMetrics, randomNumberGeneratorMock.Object, someMaximumNumberOfIterations); var estimations = estimator.Estimate(roadmap); Assert.Equal(2, estimations.Count); WorkEstimate roadmapWorkEstimate = estimations[0]; Assert.Equal("Roadmap", roadmapWorkEstimate.Identifier); AssertExpectedNumberOfWorkingDaysIsEqual(expectedNumberOfDaysRequired, roadmapWorkEstimate); AssertEstimateIsDeterminate(roadmapWorkEstimate); WorkEstimate projectWorkEstimate = estimations[1]; Assert.Equal("Project", projectWorkEstimate.Identifier); AssertExpectedNumberOfWorkingDaysIsEqual(expectedNumberOfDaysRequired, roadmapWorkEstimate); AssertEstimateIsDeterminate(roadmapWorkEstimate); }
public async Task <Roadmap> UpdateRoadmapAsync(ContractSearch userContract, Roadmap roadmap) { var url = string.Format(Endpoints.RoadmapUpdateAdminEndpoint, userContract.Id, roadmap.Year); roadmap.Year = null; return(await RequestWrapper.PatchAsyncWrapper <Roadmap, Roadmap>(roadmap, url)); }
/// <exception cref="ArgumentNullException">Thrown when <paramref name="roadmap"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="roadmap"/> has no work to be completed.</exception> /// <exception cref="InvalidOperationException">Thrown when <see cref="inputMetrics"/> doesn't have at least 1 element.</exception> /// <returns>A collection of work estimates. The first element is the estimate the complete the whole <paramref name="roadmap"/>. /// The remaining elements are the work estimates for the projects in <paramref name="roadmap"/>.</returns> public IReadOnlyList <WorkEstimate> Estimate(Roadmap roadmap) { ValidateThatRoadmapHasWorkToBeCompleted(roadmap); ValidateThatInputMetricsHaveAtLeastOneElement(); return(EstimateWorkRequiredForFinishWorkItems(roadmap)); }
//------------------------------------------------------------------------- public EntityDlg(Roadmap roadmap, Entity entity) { try { Roadmap = roadmap; Entity = entity; InitializeComponent(); LookUpEntityTypes(); PopualteTypeDropdownList(); PopulateDependencies(); PopulateFields(); // Restore previous pos & size. if (LastPosition != Point.Empty) { StartPosition = FormStartPosition.Manual; Location = LastPosition; } if (LastSize != Size.Empty) { Size = LastSize; } } catch (Exception ex) { Program.HandleException(ex); } }
//------------------------------------------------------------------------- private void Main_Load(object sender, EventArgs e) { try { // Load roadmap from file if one was specified. if (RoadmapFilename != null) { LoadRoadmap(RoadmapFilename); UpdateAppTitle(); } // Create a new roadmap if we don't have one by now. if (ActiveRoadmap == null) { ActiveRoadmap = new Roadmap(); } // Update the UI. PopulateEntityLists(); } catch (Exception ex) { Program.HandleException(ex); } }
public WorkEstimate_specification() { originalThreadCulture = CultureInfo.DefaultThreadCurrentCulture; someFinishedProject = CreateFinishedProject(); someFinishedRoadmap = CreateFinishedRoadmap(); }
/// <returns>A collection of work estimates. The first element is the estimate the complete the whole <paramref name="roadmap"/>. /// The remaining elements are the work estimates for the projects in <paramref name="roadmap"/>.</returns> private IReadOnlyList <WorkEstimate> EstimateWorkRequiredForFinishWorkItems(Roadmap roadmap) { var estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject = roadmap.Projects.ToDictionary(p => p, p => 0.0); int iterationNumber = 0; double leftOverThroughput = 0.0; double numberOfDaysToFinishRoadmap = 0.0; var workedProjects = new HashSet <Project>(estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject.Count); var unworkedProjects = new HashSet <Project>(estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject.Keys); do { var throughputOfThatDay = GetThroughputOfThatDay() + leftOverThroughput; var amountOfWorkingDayConsumed = GetAmountOfWorkingDayConsumed(roadmap, throughputOfThatDay); double numberOfWorkItemsFinishedThisDay = Math.Floor(throughputOfThatDay); for (int i = 0; i < numberOfWorkItemsFinishedThisDay; i++) { var availableProjects = roadmap.GetCurrentAvailableProjectsThatHaveWorkToBeCompleted(); if (availableProjects.Count == 0) { // Nothing to do any more, so early exit from the loop. break; } var projectToWorkOn = GetRandomElement(availableProjects); projectToWorkOn.CompleteWorkItem(); unworkedProjects.Remove(projectToWorkOn); workedProjects.Add(projectToWorkOn); } // Projects actually worked on can finish sooner than 1 day: foreach (var p in workedProjects) { estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject[p] += amountOfWorkingDayConsumed; } numberOfDaysToFinishRoadmap += amountOfWorkingDayConsumed; // Projects not worked on always complete 1 day later: foreach (var p in unworkedProjects) { estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject[p] += 1; } leftOverThroughput = throughputOfThatDay - numberOfWorkItemsFinishedThisDay; iterationNumber++; foreach (var p in workedProjects.Where(p => p.HasWorkToBeCompleted)) { unworkedProjects.Add(p); } workedProjects.Clear(); }while (roadmap.HasWorkToBeCompleted && !IsMaximumNumberOfIterationsReached(iterationNumber)); return(CreateWorkEstimatesResult(roadmap, numberOfDaysToFinishRoadmap, estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject)); }
/// <exception cref="ArgumentNullException">Thrown when <paramref name="roadmap"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="roadmap"/> has no work to be completed.</exception> private void ValidateThatRoadmapHasWorkToBeCompleted(Roadmap roadmap) { if (roadmap is null) { throw new ArgumentNullException(nameof(roadmap)); } if (!roadmap.HasWorkToBeCompleted) { throw new ArgumentOutOfRangeException(nameof(roadmap), "Roadmap should have work to be completed."); } }
public void addDocument(Roadmap roadmap) { if (writer == null) { var analyzer = new StandardAnalyzer(LuceneVersion.LUCENE_48); IndexWriterConfig conf = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer); writer = new IndexWriter(directory, conf); } Document doc = new Document(); string title = roadmap.Title; string intro = roadmap.Summary; var roadmapTags = _dbContext.Entry(roadmap) .Collection(r => r.RoadmapTag) .Query().Select(roadmapTag => roadmapTag.Tag); var tags = String.Join(" ", roadmapTags); var idField = new StringField("Id", roadmap.RoadmapId.ToString(), Field.Store.YES); doc.Add(idField); var titleField = new TextField("Title", title, Field.Store.YES); titleField.Boost = 3; doc.Add(titleField); var introField = new TextField("Intro", intro, Field.Store.YES); introField.Boost = 4; doc.Add(introField); var tagField = new TextField("Tags", tags, Field.Store.YES); tagField.Boost = 1; doc.Add(tagField); foreach (var tag in roadmapTags) { var tokenizedTagField = new StringField("TokenizedTags", tag.TagName, Field.Store.YES); doc.Add(tokenizedTagField); } writer.AddDocument(doc); writer.Commit(); }
public void GIVEN_completed_roadmap_WHEN_estimating_time_to_completion_THEN_throw_ArgumentOutOfRangeException() { var inputMetrics = ToInputMetrics(new[] { new ThroughputPerDay(1) }); var project = new Project(1); var roadmap = new Roadmap(new[] { project }); project.CompleteWorkItem(); var estimator = new TimeTillCompletionEstimator(inputMetrics, randomNumberGeneratorMock.Object, someMaximumNumberOfIterations); void Call() => estimator.Estimate(roadmap); var actualException = Assert.Throws <ArgumentOutOfRangeException>("roadmap", Call); Assert.StartsWith("Roadmap should have work to be completed.", actualException.Message); }
private static IReadOnlyList <WorkEstimate> CreateWorkEstimatesResult( Roadmap roadmap, double numberOfDaysToFinishRoadmap, IReadOnlyDictionary <Project, double> estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject) { var workEstimates = new WorkEstimate[estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject.Count + 1]; workEstimates[0] = new WorkEstimate(roadmap, numberOfDaysToFinishRoadmap); var index = 1; foreach (KeyValuePair <Project, double> keyValuePair in estimatedNumberOfWorkingDaysRequiredToFinishWorkPerProject) { workEstimates[index++] = new WorkEstimate(keyValuePair.Key, keyValuePair.Value); } return(workEstimates); }
//------------------------------------------------------------------------- private void LoadRoadmap(string filename) { try { ActiveRoadmap = Roadmap.InstantiateFromFile(filename); UpdateAppTitle(); PopulateEntityLists(); } catch (Exception ex) { Program.HandleException( new Exception( "Failed to load Roadmap '" + filename + "'.", ex)); } }
public static void CleanData() { FrameNameTable = null; FrameResource = null; VertexBufferPool = null; IndexBufferPool = null; SoundSector = null; Actors = null; ItemDescs = null; Collisions = null; CityAreas = null; CityShops = null; roadMap = null; ATLoader = null; AIWorlds = null; OBJData = null; }
//------------------------------------------------------------------------- private void SaveRoadmap(string filename) { try { if (ActiveRoadmap != null) { Roadmap.WriteToFile(filename, ActiveRoadmap); } } catch (Exception ex) { Program.HandleException( new Exception( "Failed to load Roadmap '" + filename + "'.", ex)); } }
public void XmlPersistence() { // Set up allowed dependencies. EntityRelationshipManager.AddAllowedDependency( typeof(EntityMocks.EntityMock1), typeof(EntityMocks.EntityMock2)); // Add some entities. EntityMocks.EntityMock1 mock1 = TestObject.AddEntity <EntityMocks.EntityMock1>(); EntityMocks.EntityMock2 mock2_1 = TestObject.AddEntity <EntityMocks.EntityMock2>(); EntityMocks.EntityMock2 mock2_2 = TestObject.AddEntity <EntityMocks.EntityMock2>(); // Add dependencies. mock1.AddDependency(mock2_1); mock1.AddDependency(mock2_2); // Get as xml. XmlDocument xmlDoc = new XmlDocument(); XmlElement xml = xmlDoc.CreateElement("Roadmap"); TestObject.GetAsXml(xml); // Initialise a new roadmap using the xml. Roadmap newRoadmap = new Roadmap(); newRoadmap.InitialiseFromXml(xml); // Check the entities are present. Entity newMock1 = newRoadmap.GetEntity(mock1.Id); Entity newMock2_1 = newRoadmap.GetEntity(mock2_1.Id); Entity newMock2_2 = newRoadmap.GetEntity(mock2_2.Id); Assert.IsNotNull(newMock1.Title, "Entity not found."); Assert.IsNotNull(newMock2_1.Title, "Entity not found."); Assert.IsNotNull(newMock2_2.Title, "Entity not found."); // Check the dependencies are present. ReadOnlyCollection <Entity> dependencies; newMock1.GetDependencies(out dependencies); Assert.IsTrue(dependencies.Contains(newMock2_1), "Dependency not found."); Assert.IsTrue(dependencies.Contains(newMock2_2), "Dependency not found."); }
//------------------------------------------------------------------------- private void uiFileNew_Click(object sender, EventArgs e) { try { if (MessageBox.Show( "Discard any changes to current Roadmap?", "New Roadmap", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { RoadmapFilename = null; ActiveRoadmap = new Roadmap(); UpdateAppTitle(); PopulateEntityLists(); } } catch (Exception ex) { Program.HandleException(ex); } }
public void StoryIsValidWithCategories() { // Arrange var roadmap = new Roadmap(); roadmap.Categories.Add(new Category()); roadmap.Name = "StoryName"; var story = new Story(roadmap, Mock.Of <ISharpcloudClient2>()); var helper = CreateQueryConnectHelper(); // Act var isValid = helper.Validate(story, out var message); // Assert Assert.IsTrue(isValid); Assert.AreEqual(message, "Reading story 'StoryName'"); }
//------------------------------------------------------------------------- private void PopulateDependencies() { try { uiDependencies.Items.Clear(); // Iterate through all the entity types. foreach (Type type in EntityTypes.Values) { // Is the entity is allowed to depend on this type? bool dependencyAllowed = EntityRelationshipManager.GetIsDependencyAllowed( Entity.GetType(), type); if (dependencyAllowed) { // Get all the entities of the type (which we now know // the entity is allowed to depend on) and add to the UI list. ReadOnlyDictionary <int, Entity> entities; Roadmap.GetEntities(type, out entities); foreach (Entity e in entities.Values) { // Can't depend on itself. if (e != Entity) { uiDependencies.Items.Add( e, Entity.GetIsDependantOn(e)); } } } } } catch (Exception ex) { Program.HandleException(ex); } }
public void XmlFilePersistence() { // Set up allowed dependencies. EntityRelationshipManager.AddAllowedDependency( typeof(EntityMocks.EntityMock1), typeof(EntityMocks.EntityMock2)); // Add some entities. EntityMocks.EntityMock1 mock1 = TestObject.AddEntity <EntityMocks.EntityMock1>(); EntityMocks.EntityMock2 mock2_1 = TestObject.AddEntity <EntityMocks.EntityMock2>(); EntityMocks.EntityMock2 mock2_2 = TestObject.AddEntity <EntityMocks.EntityMock2>(); // Add dependencies. mock1.AddDependency(mock2_1); mock1.AddDependency(mock2_2); // Write to file. Roadmap.WriteToFile("XmlFilePersistence.roadmap", TestObject); // Initialise a new roadmap from file. Roadmap newRoadmap = Roadmap.InstantiateFromFile("XmlFilePersistence.roadmap"); // Check the entities are present. Entity newMock1 = newRoadmap.GetEntity(mock1.Id); Entity newMock2_1 = newRoadmap.GetEntity(mock2_1.Id); Entity newMock2_2 = newRoadmap.GetEntity(mock2_2.Id); Assert.IsNotNull(newMock1.Title, "Entity not found."); Assert.IsNotNull(newMock2_1.Title, "Entity not found."); Assert.IsNotNull(newMock2_2.Title, "Entity not found."); // Check the dependencies are present. ReadOnlyCollection <Entity> dependencies; newMock1.GetDependencies(out dependencies); Assert.IsTrue(dependencies.Contains(newMock2_1), "Dependency not found."); Assert.IsTrue(dependencies.Contains(newMock2_2), "Dependency not found."); }
//------------------------------------------------------------------------- private void uiType_SelectedIndexChanged(object sender, EventArgs e) { try { // Changing the type? if (uiType.Text != Entity.TypeName) { Roadmap.RemoveEntity(Entity); Entity newEntity = Roadmap.AddEntity(EntityTypes[uiType.Text]); newEntity.Title = Entity.Title; newEntity.Description = Entity.Description; Entity = newEntity; PopulateFields(); } } catch (Exception ex) { Program.HandleException(ex); } }
public bool LockAndCreate(int nRoadmapGroupId) { try { // Get the roadmap, do not create if missing RoadmapGroup mapGroup = GetRoadmapGroup(nRoadmapGroupId, false); if (mapGroup != null) { // Get the submaps (one per year in the roadmapgroup) List <Roadmap> maps = GetRoadmaps(mapGroup.RoadmapGroupId); if (maps != null) { // This should not be the case! } int nCurrentYear = mapGroup.StartYear; do { Roadmap tempMap = maps.Find(x => x.CurrentYear == nCurrentYear); if (tempMap == null) { // This creates a new roadmap, with all properties from the RoadmapGroup // except for the xml, and that the start/end-year is set to nCurrentYear DbCtx.Roadmaps.Add(new Roadmap(mapGroup, nCurrentYear)); } } while (++nCurrentYear <= mapGroup.EndYear); DbCtx.SaveChanges(); return(true); } return(false); } catch { } return(false); }
public async Task Store(RoadmapForm form) { var roadmap = new Roadmap { Title = form.Title, Summary = form.Summary, }; var roadmapTags = form.Tags .Select(tagId => new Tag // First we take our form.tags and convert it to Tag objects { TagName = tagId }) .Select(tag => new RoadmapTag // Then we take the result of the previous conversion and we { // transform again to RoadmapTags, we even could do this in one pass Roadmap = roadmap, // but this way is more clear what the transformations are Tag = tag }) .ToList(); _dbContext.AddRange(roadmapTags); await _dbContext.SaveChangesAsync(); _searchEngine.addDocument(roadmap); }
public void GIVEN_multiple_input_metrics_AND_one_project_AND_truely_random_number_generator_WHEN_estimating_time_to_completion_THEN_return_number_of_work_days_in_range( IReadOnlyCollection <ThroughputPerDay> throughputs, Project project, double lowerBoundExpectedNumberOfDaysRequired, double upperBoundExpectedNumberOfDaysRequired) { var inputMetrics = ToInputMetrics(throughputs); var roadmap = new Roadmap(new[] { project }); var estimator = new TimeTillCompletionEstimator(inputMetrics, realRandomNumberGenerator, someMaximumNumberOfIterations); var estimations = estimator.Estimate(roadmap); Assert.Equal(2, estimations.Count); WorkEstimate roadmapWorkEstimate = estimations[0]; Assert.Equal("Roadmap", roadmapWorkEstimate.Identifier); Assert.InRange(roadmapWorkEstimate.EstimatedNumberOfWorkingDaysRequired, lowerBoundExpectedNumberOfDaysRequired, upperBoundExpectedNumberOfDaysRequired); AssertEstimateIsDeterminate(roadmapWorkEstimate); WorkEstimate projectWorkEstimate = estimations[1]; Assert.Equal("Project", projectWorkEstimate.Identifier); Assert.InRange(projectWorkEstimate.EstimatedNumberOfWorkingDaysRequired, lowerBoundExpectedNumberOfDaysRequired, upperBoundExpectedNumberOfDaysRequired); AssertEstimateIsDeterminate(projectWorkEstimate); }
public static void BuildData() { List <FileInfo> vbps = new List <FileInfo>(); List <FileInfo> ibps = new List <FileInfo>(); List <ItemDescLoader> ids = new List <ItemDescLoader>(); List <Actor> act = new List <Actor>(); List <NAVData> aiw = new List <NAVData>(); List <NAVData> obj = new List <NAVData>(); DirectoryInfo dirInfo = new DirectoryInfo(ScenePath); FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories); XmlDocument document = new XmlDocument(); document.Load(ScenePath + "/SDSContent.xml"); XPathNavigator nav = document.CreateNavigator(); var nodes = nav.Select("/SDSResource/ResourceEntry"); while (nodes.MoveNext() == true) { string type; string name; nodes.Current.MoveToFirstChild(); type = nodes.Current.Value; nodes.Current.MoveToNext(); name = ScenePath + "/" + nodes.Current.Value; if (type == "IndexBufferPool") { ibps.Add(new FileInfo(name)); } else if (type == "VertexBufferPool") { vbps.Add(new FileInfo(name)); } else if (type == "Actors") { try { act.Add(new Actor(name)); } catch (Exception ex) { Console.WriteLine("Failed to read actor {0}", name); } } else if (type == "FrameResource") { FrameResource = new FrameResource(name); } else if (type == "ItemDesc") { ids.Add(new ItemDescLoader(name)); } else if (type == "FrameNameTable") { FrameNameTable = new FrameNameTable(name); } else if (type == "Collisions") { Collisions = new Collision(name); } else if (type == "AnimalTrafficPaths") { try { ATLoader = new AnimalTrafficLoader(new FileInfo(name)); } catch (Exception ex) { Console.WriteLine("Failed to read AnimalTrafficPaths {0}", ATLoader); } } else if (nodes.Current.Value == "roadmap.gsd") { roadMap = new Roadmap(new FileInfo(name)); } else if (type == "NAV_OBJ_DATA") { obj.Add(new NAVData(new FileInfo(name))); } else if (type == "Translokator") { Translokator = new TranslokatorLoader(new FileInfo(name)); } } IndexBufferPool = new IndexBufferManager(ibps); VertexBufferPool = new VertexBufferManager(vbps); ItemDescs = ids.ToArray(); Actors = act.ToArray(); OBJData = obj.ToArray(); }
public void Initialise() { TestObject = new Roadmap(); }
//Improve this, its bad. private void HandleFile(ListViewItem item) { if (ToolkitSettings.UseSDSToolFormat) { switch (item.SubItems[1].Text) { case "Directory": OpenDirectory((DirectoryInfo)item.Tag); return; case "SDS Archive": OpenSDS((FileInfo)item.Tag); break; default: Process.Start(((FileInfo)item.Tag).FullName); break; } return; } MaterialTool mTool; CollisionEditor cTool; ActorEditor aTool; PrefabLoader prefabs; SpeechEditor sTool; CutsceneLoader cutscene; IOFxFile iofx; EmitterFile emitterFile; TableEditor tTool; NAVData nav; ApexRenderMesh mesh; ApexClothingAssetLoader aca; CityAreaEditor caEditor; CityShopEditor csEditor; SoundSectorLoader soundSector; //DEBUG D3DForm d3dForm; //special case: if (item.SubItems[0].Text.Contains("SDSContent") && item.SubItems[1].Text == "XML") { new SDSContentEditor((FileInfo)item.Tag); return; } else if (item.SubItems[0].Text.Contains("cityareas") && item.SubItems[1].Text == "BIN") { caEditor = new CityAreaEditor((FileInfo)item.Tag); return; } else if (item.SubItems[0].Text.Contains("FrameProps") && item.SubItems[1].Text == "BIN") { FrameProps fProps = new FrameProps((FileInfo)item.Tag); return; } else if (item.SubItems[0].Text.Contains("cityshop") && item.SubItems[1].Text == "BIN") { csEditor = new CityShopEditor((FileInfo)item.Tag); return; } else if (item.SubItems[0].Text.Contains("roadmap") && item.SubItems[1].Text == "GSD") { Roadmap roadmap = new Roadmap((item.Tag as FileInfo)); return; } else if (item.SubItems[0].Text.Contains("shopmenu2") && item.SubItems[1].Text == "BIN") { ShopMenu2Editor editor = new ShopMenu2Editor((item.Tag as FileInfo)); return; } else if (item.SubItems[1].Text == "BIN" && HandleStreamMap((item.Tag as FileInfo))) { StreamEditor editor = new StreamEditor((item.Tag as FileInfo)); return; } else if (item.SubItems[1].Text == "BIN" && CGameData.CheckHeader((item.Tag as FileInfo))) { CGameData data = new CGameData((item.Tag as FileInfo)); return; } else if (item.SubItems[0].Text.Contains("sdsconfig") && item.SubItems[1].Text == "BIN") { using (BinaryReader reader = new BinaryReader(File.Open((item.Tag as FileInfo).FullName, FileMode.Open))) { SdsConfigFile sdsConfig = new SdsConfigFile(); sdsConfig.ReadFromFile(reader); } return; } switch (item.SubItems[1].Text) { case "ARM": mesh = new ApexRenderMesh((FileInfo)item.Tag); return; case "ATP": AnimalTrafficLoader loader = new AnimalTrafficLoader((FileInfo)item.Tag); return; case "ACA": aca = new ApexClothingAssetLoader((FileInfo)item.Tag); return; case "Directory": OpenDirectory((DirectoryInfo)item.Tag); return; case "Material Library": mTool = new MaterialTool((FileInfo)item.Tag); return; case "NAV": case "NOV": case "NHV": nav = new NAVData((FileInfo)item.Tag); return; case "Speech Data": sTool = new SpeechEditor((FileInfo)item.Tag); return; case "CUT": cutscene = new CutsceneLoader((FileInfo)item.Tag); return; case "SDS Archive": OpenSDS((FileInfo)item.Tag); break; case "PATCH Archive": OpenPATCH((FileInfo)item.Tag); break; case "FR": //fTool = new FrameResourceTool((FileInfo)item.Tag); d3dForm = new D3DForm((FileInfo)item.Tag); d3dForm.Dispose(); return; case "COL": cTool = new CollisionEditor((FileInfo)item.Tag); return; case "IOFX": iofx = new IOFxFile((FileInfo)item.Tag); return; case "AEA": emitterFile = new EmitterFile((FileInfo)item.Tag); return; case "Table": tTool = new TableEditor((FileInfo)item.Tag); return; case "TRA": TranslokatorEditor editor = new TranslokatorEditor((FileInfo)item.Tag); return; case "ACT": aTool = new ActorEditor((FileInfo)item.Tag); break; case "PRF": prefabs = new PrefabLoader((FileInfo)item.Tag); return; case "LUA": case "AP": case "SHP": HandleLuaFile((FileInfo)item.Tag); return; case "IFL": ResourceTypes.AnimatedTexture.AnimatedTextureLoader an = new ResourceTypes.AnimatedTexture.AnimatedTextureLoader((FileInfo)item.Tag); return; case "IDS": ResourceTypes.ItemDesc.ItemDescLoader itemDesc = new ResourceTypes.ItemDesc.ItemDescLoader((item.Tag as FileInfo).FullName); return; case "BIN": SoundSectorLoader sLoader = new SoundSectorLoader(item.Tag as FileInfo); return; default: Process.Start(((FileInfo)item.Tag).FullName); break; } }
public static void BuildData(bool forceBigEndian) { List <FileInfo> vbps = new List <FileInfo>(); List <FileInfo> ibps = new List <FileInfo>(); List <ItemDescLoader> ids = new List <ItemDescLoader>(); List <Actor> act = new List <Actor>(); List <NAVData> aiw = new List <NAVData>(); List <NAVData> obj = new List <NAVData>(); isBigEndian = forceBigEndian; VertexTranslator.IsBigEndian = forceBigEndian; if (isBigEndian) { MessageBox.Show("Detected 'Big Endian' formats. This will severely effect functionality!", "Toolkit", MessageBoxButtons.OK, MessageBoxIcon.Information); } DirectoryInfo dirInfo = new DirectoryInfo(ScenePath); sdsContent = new SDSContentFile(); sdsContent.ReadFromFile(new FileInfo(Path.Combine(ScenePath + "/SDSContent.xml"))); //IndexBuffers var paths = sdsContent.GetResourceFiles("IndexBufferPool", true); foreach (var item in paths) { ibps.Add(BuildFileInfo(item)); } //Vertex Buffers paths = sdsContent.GetResourceFiles("VertexBufferPool", true); foreach (var item in paths) { vbps.Add(BuildFileInfo(item)); } //Actors if (!isBigEndian) { paths = sdsContent.GetResourceFiles("Actors", true); foreach (var item in paths) { try { act.Add(new Actor(item)); } catch (Exception ex) { Console.WriteLine("Failed to read actor {0}", item); } } } //FrameResource if (sdsContent.HasResource("FrameResource")) { var name = sdsContent.GetResourceFiles("FrameResource", true)[0]; FrameResource = new FrameResource(name, isBigEndian); } //Item Desc if (!isBigEndian) { paths = sdsContent.GetResourceFiles("ItemDesc", true); foreach (var item in paths) { ids.Add(new ItemDescLoader(item)); } } //FrameNameTable if (sdsContent.HasResource("FrameNameTable")) { var name = sdsContent.GetResourceFiles("FrameNameTable", true)[0]; FrameNameTable = new FrameNameTable(name, isBigEndian); } //Collisions if (!isBigEndian && sdsContent.HasResource("Collisions")) { var name = sdsContent.GetResourceFiles("Collisions", true)[0]; Collisions = new Collision(name); } //~ENABLE THIS SECTION AT YOUR OWN RISK //AnimalTrafficPaths //if (!isBigEndian && sdsContent.HasResource("AnimalTrafficPaths")) //{ // var name = sdsContent.GetResourceFiles("AnimalTrafficPaths", true)[0]; // try // { // ATLoader = new AnimalTrafficLoader(new FileInfo(name)); // } // catch (Exception ex) // { // Console.WriteLine("Failed to read AnimalTrafficPaths {0}", ex.Message); // } //} //~ENABLE THIS SECTION AT YOUR OWN RISK if (!isBigEndian && sdsContent.HasResource("PREFAB")) { var name = sdsContent.GetResourceFiles("PREFAB", true)[0]; PrefabLoader loader = new PrefabLoader(new FileInfo(name)); Prefabs = loader; } //RoadMap if (!isBigEndian) { paths = sdsContent.GetResourceFiles("MemFile", true); foreach (var item in paths) { if (item.Contains("RoadMap") || item.Contains("roadmap")) { roadMap = new Roadmap(new FileInfo(item)); } } } //~ENABLE THIS SECTION AT YOUR OWN RISK //Translokator //if (!isBigEndian && sdsContent.HasResource("Translokator")) //{ // var name = sdsContent.GetResourceFiles("Translokator", true)[0]; // Translokator = new TranslokatorLoader(new FileInfo(name)); //} //~ENABLE THIS SECTION AT YOUR OWN RISK //~ENABLE THIS SECTION AT YOUR OWN RISK /* Kynapse OBJ_DATA * if (!isBigEndian) * { * tis' broken for now * paths = sdsContent.GetResourceFiles("NAV_OBJ_DATA", true); * foreach (var item in paths) * { * obj.Add(new NAVData(new FileInfo(item))); * } * * for (int i = 0; i < obj.Count; i++) * { * obj[i].WriteToFile(); * } * } * * AI WORLD * if (!isBigEndian) * { * paths = sdsContent.GetResourceFiles("NAV_AIWORLD_DATA", true); * foreach (var Item in paths) * { * aiw.Add(new NAVData(new FileInfo(Item))); * } * } * * if (!isBigEndian && sdsContent.HasResource("NAV_HPD_DATA")) * { * var name = sdsContent.GetResourceFiles("NAV_HPD_DATA", true)[0]; * var data = new NAVData(new FileInfo(name)); * HPDData = (data.data as HPDData); * data.WriteToFile(); * } */ //~ENABLE THIS SECTION AT YOUR OWN RISK IndexBufferPool = new IndexBufferManager(ibps, dirInfo, isBigEndian); VertexBufferPool = new VertexBufferManager(vbps, dirInfo, isBigEndian); ItemDescs = ids.ToArray(); Actors = act.ToArray(); OBJData = obj.ToArray(); AIWorlds = aiw.ToArray(); }
public bool ConvertToTUGVehicles(string strVehicleTemplateFile, string strSignatureFile, string strAxleTemplateFile, string strVectoXsd, bool bEnsureSignatureIsPresent, RoadmapGroup group, Roadmap map, DatabaseContext dbx, string strFailedWinsLogFile, string strPatchListFile) { int nCount = 0; try { Log.Debug("=>ConvertToTUGVehicles"); XNamespace ns = Reco3Common.Reco3_Defines.DeclarationNamespace; XElement signatureTemplate = XElement.Load(strSignatureFile); XElement signatureNode = signatureTemplate.Descendants(ns + "Signature").FirstOrDefault(); XElement axleTemplate = XElement.Load(strAxleTemplateFile); XElement axleTemplateNode = axleTemplate.Descendants(ns + "Axle").FirstOrDefault(); XElement vehicleTemplate = XElement.Load(strVehicleTemplateFile); /* * Roadmap previousmap = group.Roadmaps * .OrderByDescending(x => x.CurrentYear) * .Where(x => x.CurrentYear < map.CurrentYear) * .First(); */ Log.Debug("=>ConvertToTUGVehicles.Initialize"); if (true == Converter.Initialize(ns, signatureNode, axleTemplateNode, DBContext, bEnsureSignatureIsPresent, map.CurrentYear)) { using (XmlReader schemaReader = XmlReader.Create(strVectoXsd)) { // Prepare schemaset XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.Add(XmlSchema.Read(schemaReader, new ValidationEventHandler( delegate(Object sender, ValidationEventArgs e) { } ))); DateTime dtStart = DateTime.Now; // Protect the roadmap for the time we process it, will change the status afterwards but the protection remains. map.ImprovedVehicleCount = 0; map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.Processing; map.Validation_Status = Reco3_Enums.ValidationStatus.ValidatedWithSuccess; map.Protected = true; dbx.SaveChanges(); Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 vehicle-iteration"); List <Scania.Baseline.FailedPds.vehiclesVehicle> vehicleList = new List <Scania.Baseline.FailedPds.vehiclesVehicle>(); List <vehiclesVehicle> vehicles = Vehicles.vehicle.ToList(); List <Vehicle> readyVehicles = new List <Vehicle>(); // If we have a filtered VIN-list, then filter out the ones not listed List <string> strlVinList = GetVINList(strPatchListFile); if (strlVinList != null) { DateTime dtb4Filter = DateTime.Now; var hset = new HashSet <string>(strlVinList); vehicles = vehicles.Where(elem => hset.Contains(elem.VIN)).ToList(); DateTime dtafterFilter = DateTime.Now; TimeSpan span = dtafterFilter.Subtract(dtb4Filter); } foreach (vehiclesVehicle vehicle in vehicles) { // Thread.Sleep(10); nCount++; Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN); // 1: Make a copy of the template XElement currentVehicle = new XElement(vehicleTemplate); Console.WriteLine("=>ConvertToTUGVehicles.Initialized. B4 conversion: " + nCount + " VIN: " + vehicle.VIN); // 2: Construct the vehicle.xml bool bContainsImprovements = false; if (true == Converter.Convert2TUGVehicle(ref currentVehicle, vehicle, ref bContainsImprovements)) { // 3: Validate against the schema from TUG Log.Debug("=>ConvertToTUGVehicles.Initialized. B4 validating against schema."); bool errors = false; XDocument doc = new XDocument(currentVehicle); doc.Validate(schemaSet, (o, e) => { Log.Information("Schemafailure, vehicle: " + vehicle.VIN + ". " + e.Message); errors = true; }, true); if (errors == true) { Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with failures..."); /* * // Failures in the schema? * Scania.Baseline.FailedPds.vehiclesVehicle VIN = new Scania.Baseline.FailedPds.vehiclesVehicle(); * VIN.VIN = vehicle.VIN; * VIN.SchemaFailures = new Scania.Baseline.FailedPds.vehiclesVehicleSchemaFailure[strErrorList.Count]; * int n = 0; * foreach (string strError in strErrorList) * { * vehiclesVehicleSchemaFailure failure = new vehiclesVehicleSchemaFailure(); * failure.description = strError; * VIN.SchemaFailures[n++] = failure; * } * * vehicleList.Add(VIN); */ } else { try { Vehicle v = null; if (strlVinList != null) { v = dbx.Vehicle .Where(x => x.VIN == vehicle.VIN) .Where(x => x.GroupId == map.RoadmapId) .First(); } if (v != null) { // Update the existing vehicle v.XML = doc.AsString(); dbx.Entry(v).State = System.Data.Entity.EntityState.Modified; dbx.SaveChanges(); // Update the report for this vehicle too var pRoadmapGroupId = new SqlParameter("@pRoadmapGroupId", group.RoadmapGroupId); var pRoadmapId = new SqlParameter("@pRoadmapId", map.RoadmapId); var pVehicleId = new SqlParameter("@pVehicleId", v.VehicleId); // I know!!!! This is fu##ing ugly but hey, if it offends you, stop reading, ok? dbx.Database.ExecuteSqlCommand("exec GenerateRoadmapReportForVehicleId @pRoadmapGroupId , @pRoadmapId , @pVehicleId", pRoadmapGroupId, pRoadmapId, pVehicleId); } else { dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId); } /* * Vehicle v = new Vehicle(doc.AsString(), map.RoadmapId); * v.Vehicle_Mode = Reco3_Enums.VehicleMode.VectoDeclaration; * v.GroupId = map.RoadmapId; * dbx.Vehicle.Add(v); */ if (bContainsImprovements == true) { map.ImprovedVehicleCount += 1; } // dbx.SaveChanges(); //TriggerEvent(v); GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); /* * // 2.1: If no improvements where added,... * if (bContainsImprovements == false) * { * * // ...and we have the previous map,... * if (previousmap != null) * { * Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes and we have a previous version, so making a copy."); * // ...then fetch the previous version of the vehicle... * Vehicle oldVehicle = dbx.Vehicle * .Where(x => x.VIN == vehicle.VIN) * .Where(x => x.GroupId == previousmap.RoadmapId) * .First(); * * Vehicle clonedVehicle = oldVehicle.Clone(); * clonedVehicle.VehicleId = -1; * clonedVehicle.GroupId = map.RoadmapId; * dbx.Vehicle.Add(clonedVehicle); * dbx.SaveChanges(); * * // ..and copy the vsum... * List<VSumRecord> results = dbx.VSum.Where(x => x.VehicleId == oldVehicle.VehicleId).ToList(); * foreach (VSumRecord res in results) * { * // ...clone the result, patch with the new vehicle-id and roadmap-id * VSumRecord resCopy = res.Clone(); * resCopy.VehicleId = clonedVehicle.VehicleId; * resCopy.SimulationId = map.RoadmapId; * dbx.VSum.Add(resCopy); * } * } * else * { * map.ImprovedVehicleCount += 1; * Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, no changes but we dont have a previous version, so making a fresh vehicle."); * // ...and we dont have the previous map so just add it as a new one... * //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId); * } * * } * else * { * map.ImprovedVehicleCount += 1; * Log.Debug("=>ConvertToTUGVehicles.Initialized. Schema validated, with success, has changes so making a fresh vehicle."); * // ...(has changes) so just add it as a new one... * //dbx.AddVehicle(doc.AsString(), vehicle.VIN, Reco3_Enums.VehicleMode.VectoDeclaration, map.RoadmapId); * } * // ...and persist the changes... * dbx.SaveChanges(); * * GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; * GC.Collect(); */ } catch (Exception ex) { Log.Fatal(ex, "ConvertToTUGVehicles.Exception while updating db:"); Console.WriteLine("Exception while updating db: " + ex.Message); } } doc = null; } else { using (StreamWriter w = File.AppendText(strFailedWinsLogFile)) { w.WriteLine(vehicle.VIN); } Console.WriteLine(" ConvertToTUGVehicles==>Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")"); Log.Debug("=>ConvertToTUGVehicles.Convert2TUGVehicle failed." + " (VIN: " + vehicle.VIN + ")"); } currentVehicle = null; GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; GC.Collect(); } map.ConvertToVehicleInput_Status = Reco3_Enums.ConvertToVehicleInputStatus.ConvertedWithSuccess; dbx.SaveChanges(); // Add the new failures,.... if (Converter.PDFailures.vehicle != null) { List <Scania.Baseline.FailedPds.vehiclesVehicle> tmpList = Converter.PDFailures.vehicle.ToList(); tmpList.AddRange(vehicleList); Converter.PDFailures.vehicle = tmpList.ToArray(); } else { Converter.PDFailures.vehicle = vehicleList.ToArray(); } DateTime dtEnd = DateTime.Now; Console.WriteLine("Conversion started: " + dtStart.ToShortDateString() + " " + dtStart.ToShortTimeString()); Console.WriteLine("Conversion done: " + dtEnd.ToShortDateString() + " " + dtEnd.ToShortTimeString()); Log.Debug("<=ConvertToTUGVehicles"); return(true); } } } catch (Exception ex) { Log.Fatal(ex, "ConvertToTUGVehicles.OverallException"); Console.WriteLine(ex); } Log.Debug("<=ConvertToTUGVehicles"); return(false); }
public static void BuildData(bool forceBigEndian) { List <FileInfo> vbps = new List <FileInfo>(); List <FileInfo> ibps = new List <FileInfo>(); List <ItemDescLoader> ids = new List <ItemDescLoader>(); List <Actor> act = new List <Actor>(); List <NAVData> aiw = new List <NAVData>(); List <NAVData> obj = new List <NAVData>(); DirectoryInfo dirInfo = new DirectoryInfo(ScenePath); FileInfo[] files = dirInfo.GetFiles("*", SearchOption.AllDirectories); XmlDocument document = new XmlDocument(); document.Load(ScenePath + "/SDSContent.xml"); XPathNavigator nav = document.CreateNavigator(); var nodes = nav.Select("/SDSResource/ResourceEntry"); isBigEndian = forceBigEndian; Utils.Models.VertexTranslator.IsBigEndian = forceBigEndian; if (isBigEndian) { MessageBox.Show("Detected 'Big Endian' formats. This will severely effect functionality!", "Toolkit", MessageBoxButtons.OK, MessageBoxIcon.Information); } while (nodes.MoveNext() == true) { string type; string name; nodes.Current.MoveToFirstChild(); type = nodes.Current.Value; nodes.Current.MoveToNext(); name = ScenePath + "/" + nodes.Current.Value; if (type == "IndexBufferPool") { ibps.Add(new FileInfo(name)); } else if (type == "VertexBufferPool") { vbps.Add(new FileInfo(name)); } else if (type == "Actors" && !isBigEndian) { try { act.Add(new Actor(name)); } catch (Exception ex) { Console.WriteLine("Failed to read actor {0}", name); } } else if (type == "FrameResource") { FrameResource = new FrameResource(name, isBigEndian); } else if (type == "ItemDesc" && !isBigEndian) { ids.Add(new ItemDescLoader(name)); } else if (type == "FrameNameTable") { FrameNameTable = new FrameNameTable(name, isBigEndian); } else if (type == "Collisions" && !isBigEndian) { Collisions = new Collision(name); } else if (type == "AnimalTrafficPaths" && !isBigEndian) { try { ATLoader = new AnimalTrafficLoader(new FileInfo(name)); } catch (Exception ex) { Console.WriteLine("Failed to read AnimalTrafficPaths {0}", ex.Message); } } else if (nodes.Current.Value == "roadmap.gsd" && !isBigEndian) { roadMap = new Roadmap(new FileInfo(name)); } //else if (type == "NAV_OBJ_DATA" && !isBigEndian) // obj.Add(new NAVData(new FileInfo(name))); else if (type == "Translokator" && !isBigEndian) { Translokator = new TranslokatorLoader(new FileInfo(name)); } } IndexBufferPool = new IndexBufferManager(ibps, isBigEndian); VertexBufferPool = new VertexBufferManager(vbps, isBigEndian); ItemDescs = ids.ToArray(); Actors = act.ToArray(); OBJData = obj.ToArray(); }