public ActionResult Create([Bind(Include = "ProjectProjectId", Exclude = "MyProjectId,EmployeeEmployeeId")] MyProject myproject) { myproject.EmployeeEmployeeId = EmployeeId; var myprojects = db.MyProjects.Include(m => m.Project).Where(m => m.EmployeeEmployeeId == EmployeeId && m.ProjectProjectId == myproject.ProjectProjectId); if (ModelState.IsValid) { if (!myprojects.Any()) { db.MyProjects.Add(myproject); db.SaveChanges(); } //return Json(new { value = "Sucesse" }, JsonRequestBehavior.AllowGet); LoadAvaliableProjects(myproject); return(PartialView("Create", new MyProject())); } var errors = ModelState.Select(x => x.Value.Errors) .Where(y => y.Count > 0) .ToList(); ModelState.AddModelError("Error", errors.ToString()); LoadAvaliableProjects(myproject); return(PartialView("Create", myproject)); }
public void SaveState(string fileName, uint simulationStep) { try { string dataFolder = MyProject.MakeDataFolderFromFileName(fileName); MyNetworkState networkState = new MyNetworkState() { ProjectName = Owner.Name, MemoryBlocksLocation = dataFolder, SimulationStep = simulationStep }; YAXSerializer serializer = new YAXSerializer(typeof(MyNetworkState), YAXExceptionHandlingPolicies.ThrowErrorsOnly, YAXExceptionTypes.Warning); serializer.SerializeToFile(networkState, fileName); if (Directory.Exists(dataFolder)) { Directory.Delete(dataFolder, true); } Directory.CreateDirectory(dataFolder); MyMemoryManager.Instance.SaveBlocks(this, true, dataFolder); } catch (Exception e) { MyLog.ERROR.WriteLine("Saving state failed: " + e.Message); } }
// GET: /MyProject/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } MyProject myproject = db.MyProjects.Find(id); if (myproject != null) { try { db.MyProjects.Remove(myproject); db.SaveChanges(); } catch (Exception ex) { LoadAvaliableProjects(myproject); return(PartialView("Create", new MyProject())); } } LoadAvaliableProjects(myproject); return(PartialView("Create", new MyProject())); }
/// <summary> /// Creates the execution plan. /// </summary> /// <param name="project">The whole project from which the standard execution plan will be built.</param> /// <param name="initNodes">Ordered list of new nodes from which the initialization plan will be built.</param> /// <returns>The created execution plan.</returns> public MyExecutionPlan CreateExecutionPlan(MyProject project, IEnumerable <MyWorkingNode> initNodes = null) { MyExecutionPlan executionPlan = new MyExecutionPlan(); IMyOrderingAlgorithm ordering = new MyHierarchicalOrdering(); ordering.EvaluateOrder(project.Network); var initBlocks = new List <IMyExecutable>(); if (initNodes != null) { initBlocks.AddRange(initNodes.Select(node => CreateNodeExecutionPlan(node, true))); } executionPlan.InitStepPlan = new MyExecutionBlock(initBlocks.ToArray()) { Name = "Initialization" }; executionPlan.StandardStepPlan = new MyExecutionBlock( CreateNodeExecutionPlan(project.World, false), CreateNodeExecutionPlan(project.Network, false)) { Name = "Simulation" }; return(executionPlan); }
/// <summary> /// 向当前添加一个pictabpage /// </summary> /// <param name="page">要添加的page</param> public void AddPicTabPage(PicTabPage page) { AddLayoutDocument(ContentPanel, page); ///设置回调函数 page.CallBackFunction = this.ChileEventCallBack; MyProject.AddPicTabPage(page); }
// Check the dashboard for expected properties. private static void CheckDashboard(MyProject project) { Dashboard dashboard = project.Dashboard; var property1 = CheckDashboardProperty(project, dashboard, 338, "PerformTask", "SimilarityOperator"); var property2 = CheckDashboardProperty(project, dashboard, 331, "PerformTask", "SimilarityOperator"); CheckDashboardProperty(project, dashboard, 451, "ShareWeightsTask", "SourceNodeName"); MyWorkingNode nodeGroup = project.Network.GetChildNodeById(359) as MyWorkingNode; var property4 = dashboard.Get(nodeGroup, "InputBranches"); Assert.NotNull(property4); // Check the grouped dashboard for expected properties. GroupDashboard groupedDashboard = project.GroupedDashboard; var group = groupedDashboard.Get("f6af17f3-82b0-42b6-89b0-a4eaf6432316"); Assert.NotNull(@group); Assert.True(@group.GroupedProperties.Contains(property1)); Assert.True(@group.GroupedProperties.Contains(property2)); }
private void SaveProjectAs() { if (saveFileDialog.ShowDialog(this) != DialogResult.OK) { return; } string newName = saveFileDialog.FileName; string oldProjectDataPath = MyMemoryBlockSerializer.GetTempStorage(Project); string newProjectDataPath = MyMemoryBlockSerializer.GetTempStorage(MyProject.MakeNameFromPath(newName)); if (newProjectDataPath != oldProjectDataPath) { CopyDirectory(oldProjectDataPath, newProjectDataPath); } else { MyLog.WARNING.WriteLine("Projects with the same filename share the same temporal folder where the state is saved."); } Project.FileName = newName; // Also sets the name; SaveProject(); m_recentMenu.AddFile(newName); }
public override bool UpdateMemoryModel(MyProject project, List <MyNode> orderedNodes) { if (!orderedNodes.Any()) { return(true); } int attempts = 0; bool anyOutputChanged = false; try { while (attempts < MAX_BLOCKS_UPDATE_ATTEMPTS) { attempts++; anyOutputChanged = false; anyOutputChanged |= UpdateAndCheckChange(project.World); orderedNodes.ForEach(node => anyOutputChanged |= UpdateAndCheckChange(node)); if (!anyOutputChanged) { //MyLog.INFO.WriteLine("Successful update after " + attempts + " cycle(s)."); break; } } } catch (Exception e) { MyLog.ERROR.WriteLine("Exception occured while updating memory model: " + e.Message); throw; } return(anyOutputChanged); }
/// <summary> /// 创建一个空白的Pictabpage /// </summary> /// <param name="Title">页面的标题</param> public void CreatePicTabPage(string Title) { PicTabPage page = new PicTabPage(CreateID(), this.ChileEventCallBack, Title); AddLayoutDocument(ContentPanel, page); MyProject.AddPicTabPage(page); }
public async Task <MyProject> GetByUrlWithImagesAsync(string url) { if (url != null) { string[] splitUrl = url.Split('-', 2); if (splitUrl.Length == 2) { int id; bool idParseResult = int.TryParse(splitUrl[0], out id); if (idParseResult) { MyProject myProject = await _dbContext.MyProjects.SingleOrDefaultAsync(x => x.Id == id && string.Compare(splitUrl[1], x.Title) == 0); if (myProject != null) { myProject.MyProjectImages = await _dbContext.MyProjectImages.Where(x => x.MyProject.Id == myProject.Id).ToListAsync(); } return(myProject); } } } return(null); }
public void Schedule(MyProject project, IEnumerable <MyWorkingNode> newNodes = null) { // If there are any init tasks in the current plan, copy them over to the new one. // This is mostly for the first simulation step if there is also a model change. MyExecutionBlock oldPlan = null; if (ExecutionPlan != null) { oldPlan = ExecutionPlan.InitStepPlan; } m_project = project; ExecutionPlan = ExecutionPlanner.CreateExecutionPlan(project, newNodes); if (oldPlan != null) { var newInitPlan = new List <IMyExecutable>(); newInitPlan.AddRange(oldPlan.Children); newInitPlan.AddRange(ExecutionPlan.InitStepPlan.Children); ExecutionPlan.InitStepPlan = new MyExecutionBlock(newInitPlan.ToArray()) { Name = oldPlan.Name }; } ExtractAllNodes(m_project); // Allow subclasses to react to re-scheduling. ScheduleChanged(); }
/// <summary> /// Loads project from file /// </summary> /// <param name="path">Path to .brain/.brainz file</param> public void OpenProject(string path) { MyLog.INFO.WriteLine("Loading project: " + path); string content; try { string newProjectName = MyProject.MakeNameFromPath(path); content = ProjectLoader.LoadProject(path, MyMemoryBlockSerializer.GetTempStorage(newProjectName)); using (MyMemoryManager.Backup backup = MyMemoryManager.GetBackup()) { Project = MyProject.Deserialize(content, Path.GetDirectoryName(path)); backup.Forget(); } Project.FileName = path; } catch (Exception e) { MyLog.ERROR.WriteLine("Project loading failed: " + e.Message); throw; } }
/// <summary> /// /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task <(bool, string)> DeleteMyProjectByIdAsync(int id) { if (id != 0) { MyProject myProject = await _dbContext.MyProjects.SingleOrDefaultAsync(x => x.Id == id); if (myProject != null) { List <MyProjectImage> projectImages = await _dbContext.MyProjectImages.Where(x => x.MyProject.Id == myProject.Id).ToListAsync(); if (projectImages != null && projectImages.Count > 0) { for (int i = 0; i < projectImages.Count; i++) { var imgaePath = Path.Combine(_environment.WebRootPath, projectImages[i].Location); if (File.Exists(imgaePath)) { File.Delete(imgaePath); } } _dbContext.MyProjectImages.RemoveRange(projectImages); } _dbContext.MyProjects.Remove(myProject); await _dbContext.SaveChangesAsync(); return(true, "Project deleted."); } } return(false, "No project found."); }
//Filter By Design name public static void FilterByDeisgnName() { log4net.Config.XmlConfigurator.Configure(); ILog logger = LogManager.GetLogger(typeof(MyProjectsPage)); test = Base.extent.CreateTest("VerifyListOfTemplates"); try { IList <IWebElement> templates = Element.getElements(BeforeTemplates); Console.WriteLine("Number of templates present in a page is " + templates.Count()); for (int i = 0; i < templates.Count; i++) { SearchBox.Type(templates[i].Text); Wait.WaitVisible(SearchButton); SearchButton.Click(); SearchBox.Type(Keys.Control + "a"); SearchBox.Type(Keys.Clear); MyProject.Click(); if (i == 0) { break; } } } catch (Exception e) { test.Fail("Filter by deisgn name failed" + e); Driver.Quit(); throw e; } }
private string[] ProduceSubitemTexts(MyNodeConfig nodeConfig, MyObsoleteAttribute obsolete, out bool complete) { string author; string status; string summary; string labels = ""; complete = m_mainForm.Documentation.HasAuthor(nodeConfig.NodeType, out author); complete &= m_mainForm.Documentation.HasStatus(nodeConfig.NodeType, out status); complete &= m_mainForm.Documentation.HasSummary(nodeConfig.NodeType, out summary); if (obsolete != null) { status = "Obsolete"; summary = "Replaced by: " + MyProject.ShortenNodeTypeName(obsolete.ReplacedBy); } else if (!complete) { summary = "INCOMPLETE DOCUMENTATION! " + summary; } if ((nodeConfig.Labels != null) && (nodeConfig.Labels.Count > 0)) { labels = EscapeAmpersands(string.Join(" ", nodeConfig.Labels.Select(label => "#" + label))); } author = EscapeAmpersands(author); status = EscapeAmpersands(status); summary = EscapeAmpersands(summary); string nodeName = MyProject.ShortenNodeTypeName(nodeConfig.NodeType); return(new string[] { nodeName, author, status, summary, labels }); }
private static Image GenerateDefaultImage(Type nodeType, bool bigIcon) { string back_fileName = bigIcon ? @"plain_big.png" : @"plain.png"; float x = 0; float y = bigIcon ? 6 : 3; float size = bigIcon ? 36 : 17; string label = ""; string typeName = MyProject.ShortenNodeTypeName(nodeType); for (int i = 0; i < typeName.Length; i++) { if (Char.IsUpper(typeName[i])) { label += typeName[i]; if (label.Length == 2) { break; } } } if (label.Length < 2) { label = typeName.Substring(0, 2); } Image background = MyResources.GetImage(back_fileName); Graphics g = Graphics.FromImage(background); g.DrawString(label, new Font(new FontFamily("Consolas"), 17, FontStyle.Bold), Brushes.White, x, y); return(background); }
public override void UpdateMemoryBlocks() { /*Output.Count = GetInputSize(0); * Output.ColumnHint = Input != null ? Input.ColumnHint : 1;*/ if (Input != null && Input.Dims != null) { Output.Dims = Input.Dims; } else { Output.Count = 1; } if (!SignalName.Equals("<none>")) { ProxySignal.Source = MySignal.CreateSignalByDefaultName(SignalName); if (ProxySignal.Source != null) { ProxySignal.Source.Owner = this; ProxySignal.Source.Name = MyProject.RemovePostfix(ProxySignal.Source.DefaultName, "Signal"); } } else { ProxySignal.Source = null; } }
private async void OnTimer(object sender, ElapsedEventArgs args) { try { // Get the names and Ids of all active projects. List <MyProject> projects = GetActiveProjects(); // Authenticate using the token var tokenAuth = new Credentials(token); client.Credentials = tokenAuth; // Use Octokit to check if it has been updated since last update foreach (MyProject proj in projects) { var repo = await client.Repository.Get(username, proj.ProjectName); // Check if repository has been updated since last import, or has never been imported before if (proj.UpdatedAt == null || repo.UpdatedAt.DateTime >= proj.UpdatedAt) { // Get updated project Content, Languages, RepoUrl, LogoAltText MyProject project = await GetProjectDetails(proj, repo); // Update the project in the db UpdateProject(project); } } } catch (Exception ex) { LogException(ex); eventLog.WriteEntry(ex.ToString()); } }
//creates a new project private void CreateProject() { MyProject newProject = new MyProject(); newProject.name = NameTextBox.Text; newProject.projKey = System.Guid.NewGuid().ToString(); newProject.description = DescTextBox.Text; if ((bool)DueSwitch.IsChecked) //sets a due date if the button is checked { var dueDate = (DateTime)DueDatePicker.Value; var dueTime = (DateTime)DueTimePicker.Value; newProject.dueDate = (new DateTime(dueDate.Year, dueDate.Month, dueDate.Day, dueTime.Hour, dueTime.Minute, dueTime.Second)); } else newProject.dueDate = DateTime.MinValue; newProject.tasks = new ObservableCollection<MyTask>(); newProject.doneTasks = new ObservableCollection<MyTask>(); newProject.isComplete = false; newProject.status = "Incomplete"; if (this.RelayContext.Endpoint == null) newProject.creator = null; else newProject.creator = ((ObservableCollection<Person>)settings["ContactsList"])[0]; newProject.recipients = ""; ((ObservableCollection<MyProject>)settings["ProjectList"]).Add(newProject); settings["ProjectList"] = ProjectSort((ObservableCollection<MyProject>)settings["ProjectList"]); NavigationService.GoBack(); }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(new[] { SerializationIdSeparator }, StringSplitOptions.RemoveEmptyEntries); Node = FindNode(project, idSplit[0]); var workingNode = Node as MyWorkingNode; if (workingNode == null) { throw new SerializationException("A task dashboard property found a node without tasks"); } Task = workingNode.GetTaskByPropertyName(idSplit[1]); if (Task == null) { throw new SerializationException("A task dashboard property did not find the target task"); } PropertyInfo = Task.GetType().GetProperty(idSplit[2]); if (PropertyInfo == null) { throw new SerializationException("A task dashboard property was not found on the task"); } }
private void ExtractAllNodes(MyProject project) { AllNodes = new HashSet <MyWorkingNode>(); ModelChangingNodes = new List <IModelChanger>(); AllNodes.Add(project.World); var worldChanger = project.World as IModelChanger; if (worldChanger != null) { ModelChangingNodes.Add(worldChanger); } project.Network.Iterate(true, true, node => { var workingNode = node as MyWorkingNode; if (workingNode != null) { AllNodes.Add(workingNode); } var modelChanger = node as IModelChanger; if (modelChanger != null) { ModelChangingNodes.Add(modelChanger); } }); }
public override void Restore(MyProject project) { foreach (DashboardNodePropertyBase property in project.Dashboard.Properties.Where(p => p.GroupId == PropertyId)) { Add(property); } }
private void CreateNewProject() { var oldProject = Project; Project = new MyProject(); Project.Network = Project.CreateNode<MyNetwork>(); Project.Network.Name = "Network"; worldList.SelectedIndex = -1; worldList.SelectedItem = MyConfiguration.KnownWorlds.Values.First(); Text = TITLE_TEXT + " - New Project"; exportStateButton.Enabled = false; clearDataButton.Enabled = false; Project.Restore(); RestoreDashboardForm(); UndoManager.Clear(); SaveState(GetSerializedProject(), Project.FileName, "New project"); RefreshUndoRedoButtons(); ApplyProjectOptions(); // Apply default project options such as save on stop to UI. saveFileDialog.FileName = string.Empty; }
private void exportStateButton_Click(object sender, EventArgs e) { if (saveMemFileDialog.ShowDialog(this) == DialogResult.OK) { try { string dataFolder = MyProject.MakeDataFolderFromFileName(saveMemFileDialog.FileName); MyMemoryBlockSerializer.ExportTempStorage(Project, dataFolder); MyNetworkState networkState = new MyNetworkState() { ProjectName = Project.Name, MemoryBlocksLocation = dataFolder, SimulationStep = SimulationHandler.SimulationStep }; YAXSerializer serializer = new YAXSerializer(typeof(MyNetworkState), YAXExceptionHandlingPolicies.ThrowErrorsOnly, YAXExceptionTypes.Warning); serializer.SerializeToFile(networkState, saveMemFileDialog.FileName); MyLog.INFO.WriteLine("Saving state: " + saveMemFileDialog.FileName); } catch (Exception ex) { MyLog.ERROR.WriteLine("Saving state failed: " + ex.Message); } } }
private void InitIoBranches(int branchCount, NodeConnector connector, ICollection <NodeItem> branchList, IList <PropertyInfo> blocks, bool isInput) { if (branchCount == 1) { connector.Enabled = true; branchList.Add(m_iconItem); } else { for (int i = 0; i < branchCount; i++) { string name = (i + 1) + ""; if (Node is MyWorkingNode) { name = blocks[i].Name; } NodeLabelItem branch = new NodeLabelItem(MyProject.ShortenMemoryBlockName(name), isInput, !isInput) { Tag = i, IsPassive = true }; branchList.Add(branch); AddItem(branch); } } }
public int UpdateAfterDeserialization(int topId, MyProject parentProject) { if (topId < this.Id) { topId = this.Id; } this.Owner = parentProject; Dictionary <int, MyNode> nodes = new Dictionary <int, MyNode>(); topId = CollectNodesAndUpdate(this, nodes, topId); parentProject.ReadOnly = false; MyNodeGroup.IteratorAction findUnknownAction = delegate(MyNode node) { if (!MyConfiguration.KnownNodes.ContainsKey(node.GetType())) { MyLog.WARNING.WriteLine("Unknown node type in loaded project: " + node.GetType()); parentProject.ReadOnly = true; try { MyNodeConfig nodeConfig = new MyNodeConfig() { NodeType = node.GetType(), NodeTypeName = node.GetType().FullName }; nodeConfig.InitIcons(Assembly.GetExecutingAssembly()); nodeConfig.AddObservers(Assembly.GetExecutingAssembly()); MyConfiguration.KnownNodes[nodeConfig.NodeType] = nodeConfig; } catch (Exception e) { MyLog.ERROR.WriteLine("Node type loading failed: " + e.Message); } } }; Iterate(true, findUnknownAction); foreach (MyConnectionProxy cp in m_connections) { try { MyConnection connection = new MyConnection(nodes[cp.From], nodes[cp.To], cp.FromIndex, cp.ToIndex); connection.Connect(); } catch (Exception e) { MyLog.ERROR.WriteLine("Error during connection deserialization: From id " + cp.From + " to id " + cp.To); } } return(topId); }
public void WriteListToFile(MyProject myProject, string filePath) { using (var stream = _source.Open(filePath, FileMode.Create, FileAccess.Write) { BinaryFormatter bFormatter = new BinaryFormatter(); bFormatter.Serialize(stream, myProject); } }
public ActionResult DeleteConfirmed(int id) { MyProject proj = db.MyProjects.Find(id); db.MyProjects.Remove(proj); db.SaveChanges(); return(RedirectToAction("Index")); }
public void BothDashboardsSerialize() { var project = new MyProject(); project.CreateWorld(typeof(MyTestingWorld)); project.Network = new MyNetwork(); var node = project.CreateNode <Node>(); node.Name = "Foo"; project.Network.AddChild(node); var dashboard = new Dashboard(); foreach (PropertySetup propertySetup in GetPropertyExamples(project)) { dashboard.Add(propertySetup.Target, propertySetup.PropertyName); } var groupDashboard = new GroupDashboard(); groupDashboard.Properties.Add(new DashboardPropertyGroup("Group 1")); groupDashboard.Properties[0].Add(dashboard.Properties[0]); YAXSerializer serializer = MyProject.GetSerializer <Dashboard>(); YAXSerializer groupSerializer = MyProject.GetSerializer <GroupDashboard>(); string serializedDashboard = serializer.Serialize(dashboard); string serializedGroupDashboard = groupSerializer.Serialize(groupDashboard); Dashboard deserializedDashboard = (Dashboard)serializer.Deserialize(serializedDashboard); deserializedDashboard.RestoreFromIds(project); project.Dashboard = deserializedDashboard; GroupDashboard deserializedGroupDashboard = (GroupDashboard)groupSerializer.Deserialize(serializedGroupDashboard); deserializedGroupDashboard.RestoreFromIds(project); project.GroupedDashboard = deserializedGroupDashboard; var compareLogic = new CompareLogic(new ComparisonConfig { MaxDifferences = 20, MembersToIgnore = new List <string> { "Proxy", "GenericProxy" } }); ComparisonResult result = compareLogic.Compare(dashboard, deserializedDashboard); m_output.WriteLine(result.DifferencesString); Assert.True(result.AreEqual); result = compareLogic.Compare(groupDashboard, deserializedGroupDashboard); m_output.WriteLine(result.DifferencesString); Assert.True(result.AreEqual); }
public void IgnoresMissingProperty() { var serializer = MyProject.GetSerializer <PropertyMissingTest>(); var content = File.ReadAllText(@"Data\property_missing_test.txt"); var deserialized = serializer.Deserialize(content) as PropertyMissingTest; Assert.NotNull(deserialized); }
public async Task <ActionResult> DeleteConfirmed(int id) { MyProject myproject = await db.MyProjects.FindAsync(id); db.MyProjects.Remove(myproject); await db.SaveChangesAsync(); return(RedirectToAction("Index")); }
public void Schedule(MyProject project) { MyExecutionPlan singleCoreExecutionPlan = ExecutionPlanner.CreateExecutionPlan(project); ExecutionPlan = PartitioningStrategy.Divide(singleCoreExecutionPlan); //TODO: remove this and replace with proper project traversal to find nodes with no tasks! ExtractPartitioningFromExecutionPlan(); }
private static TestNode GetTestingNode() { var project = new MyProject {SimulationHandler = TypeMap.GetInstance<MySimulationHandler>()}; project.SimulationHandler.Simulation.IsStepFinished = true; var node = project.CreateNode<TestNode>(); node.UpdateMemoryBlocks(); MyMemoryManager.Instance.AllocateBlocks(node, false); return node; }
public static void ClearTempStorage(MyProject project) { if (TempDataExists(project)) { Directory.Delete(GetTempStorage(project), true); MyLog.INFO.WriteLine(project.Name + ": Temporal data deleted."); } else { MyLog.WARNING.WriteLine(project.Name + ": No temporal data to delete."); } }
private static DashboardNodePropertyBase CheckDashboardProperty(MyProject project, Dashboard dashboard, int nodeId, string taskName, string propertyName) { var node = project.Network.GetChildNodeById(nodeId) as MyWorkingNode; Assert.NotNull(node); MyTask task = node.GetTaskByPropertyName(taskName); Assert.NotNull(task); DashboardNodePropertyBase property = dashboard.Get(task, propertyName); Assert.NotNull(property); return property; }
public static void ExportTempStorage(MyProject project, string outputFolder) { string tempStorage = GetTempStorage(project); foreach (string path in Directory.GetDirectories(tempStorage, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(path.Replace(tempStorage, outputFolder)); } foreach (string filePath in Directory.GetFiles(tempStorage, "*.mb", SearchOption.AllDirectories)) { File.Copy(filePath, filePath.Replace(tempStorage, outputFolder), true); } }
public void SimulationStateChangedOnNodesTest() { var simulation = new MyLocalSimulation(); var handler = new MySimulationHandler(simulation); MyProject project = new MyProject { Network = new MyNetwork() }; project.CreateWorld(typeof(MyTestingWorld)); var node = project.CreateNode<TestingNode>(); node.Event = new AutoResetEvent(false); project.Network.AddChild(node); var connection = new MyConnection(project.Network.GroupInputNodes[0], project.Network.Children[0]); connection.Connect(); project.Network.PrepareConnections(); handler.Project = project; handler.UpdateMemoryModel(); handler.StartSimulation(oneStepOnly: false); node.Event.WaitOne(); Assert.Equal(MySimulationHandler.SimulationState.STOPPED, node.PreviousState); Assert.Equal(MySimulationHandler.SimulationState.RUNNING, node.CurrentState); handler.PauseSimulation(); node.Event.WaitOne(); Assert.Equal(MySimulationHandler.SimulationState.RUNNING, node.PreviousState); Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.CurrentState); handler.StartSimulation(oneStepOnly: true); node.Event.WaitOne(); // Here the sim goes from paused to RUNNING_STEP. Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.PreviousState); Assert.Equal(MySimulationHandler.SimulationState.RUNNING_STEP, node.CurrentState); node.Event.WaitOne(); // Here it goes to PAUSED. Assert.Equal(MySimulationHandler.SimulationState.RUNNING_STEP, node.PreviousState); Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.CurrentState); handler.StopSimulation(); node.Event.WaitOne(); Assert.Equal(MySimulationHandler.SimulationState.PAUSED, node.PreviousState); Assert.Equal(MySimulationHandler.SimulationState.STOPPED, node.CurrentState); handler.Finish(); }
public void Validate(MyProject project = null) { Validator.ClearValidation(); if (project == null) project = m_project; project.World.ValidateWorld(Validator); project.Network.Validate(Validator); }
private void ExtractAllNodes(MyProject project) { AllNodes = new HashSet<MyWorkingNode>(); ModelChangingNodes = new List<IModelChanger>(); AllNodes.Add(project.World); var worldChanger = project.World as IModelChanger; if (worldChanger != null) ModelChangingNodes.Add(worldChanger); project.Network.Iterate(true, true, node => { var workingNode = node as MyWorkingNode; if (workingNode != null) AllNodes.Add(workingNode); var modelChanger = node as IModelChanger; if (modelChanger != null) ModelChangingNodes.Add(modelChanger); }); }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(SerializationIdSeparator.ToCharArray()); var success = false; int nodeId; if (int.TryParse(idSplit[0], out nodeId)) { Node = project.GetNodeById(nodeId); if (Node != null) success = true; } if (!success) throw new SerializationException("A dashboard property target node was not found"); PropertyInfo = Node.GetType().GetProperty(idSplit[1]); if (PropertyInfo == null) throw new SerializationException("A dashboard property was not found on the node"); }
protected static MyNode FindNode(MyProject project, string nodeId) { var success = false; MyNode node = null; int parsedNodeId; if (int.TryParse(nodeId, out parsedNodeId)) { node = project.GetNodeById(parsedNodeId); if (node != null) success = true; } if (!success) throw new SerializationException("A dashboard property target node was not found"); return node; }
//Called when a project in the PLB is selected private void ProjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { System.Diagnostics.Debug.WriteLine("Hit PLBSelectionChanged: " + ProjectListBox.SelectedIndex); if (ProjectListBox.SelectedIndex == -1) return; _selectedProject = (MyProject)ProjectListBox.SelectedItem; if (ProjectListBox.ItemsSource == ((ObservableCollection<MyProject>)settings["DoneProjectList"])) { NavigationService.Navigate(new Uri("/ProjectView.xaml?Project=" + ((ObservableCollection<MyProject>)settings["DoneProjectList"]).IndexOf(_selectedProject) + "&Complete=1", UriKind.RelativeOrAbsolute)); //Navigate to ProjectView } else { NavigationService.Navigate(new Uri("/ProjectView.xaml?Project=" + ((ObservableCollection<MyProject>)settings["ProjectList"]).IndexOf(_selectedProject), UriKind.RelativeOrAbsolute)); //Navigate to ProjectView } ProjectListBox.SelectedIndex = -1; }
private void ParseProject(string from, string[] contents) { bool foundProject = false; foreach (MyProject search in ((ObservableCollection<MyProject>)settings["ProjectList"])) { if (contents[2].Equals(search.projKey)) { search.name = contents[1]; search.projKey = contents[2]; search.description = contents[3]; search.dueDate = DateTime.Parse(contents[4]); search.isComplete = Convert.ToBoolean(contents[5]); search.status = contents[6]; Person createP = new Person(); createP.name = contents[7]; createP.username = contents[8]; createP.hawaiiID = contents[9]; createP.reqSent = Convert.ToBoolean(contents[10]); createP.accepted = Convert.ToBoolean(contents[11]); search.creator = createP; search.recipients = contents[12]; settings["ProjectList"] = ProjectSort(((ObservableCollection<MyProject>)settings["ProjectList"])); foundProject = true; ((ObservableCollection<TaskMeMessage>)settings["MessageList"]).Insert(0, new TaskMeMessage { type = "Project Updated", content = "Project " + search.name + " was updated.", timeStamp = DateTime.Now }); break; } } if (!foundProject) { MyProject create = new MyProject(); create.name = contents[1]; create.projKey = contents[2]; create.description = contents[3]; create.dueDate = DateTime.Parse(contents[4]); create.isComplete = Convert.ToBoolean(contents[5]); create.status = contents[6]; Person createP = new Person(); createP.name = contents[7]; createP.username = contents[8]; createP.hawaiiID = contents[9]; createP.reqSent = Convert.ToBoolean(contents[10]); createP.accepted = Convert.ToBoolean(contents[11]); create.creator = createP; create.recipients = contents[12]; create.tasks = new ObservableCollection<MyTask>(); create.doneTasks = new ObservableCollection<MyTask>(); ((ObservableCollection<MyProject>)settings["ProjectList"]).Add(create); settings["ProjectList"] = ProjectSort(((ObservableCollection<MyProject>)settings["ProjectList"])); ((ObservableCollection<TaskMeMessage>)settings["MessageList"]).Insert(0, new TaskMeMessage { type = "Project Added", content = "Project " + create.name + " was added.", timeStamp = DateTime.Now }); } }
public MyExecutionPlan CreateExecutionPlan(MyProject project) { MyExecutionPlan executionPlan = new MyExecutionPlan(); IMyOrderingAlgorithm ordering = new MyHierarchicalOrdering(); ordering.EvaluateOrder(project.Network); executionPlan.InitStepPlan = new MyExecutionBlock( CreateNodeExecutionPlan(project.World, true), CreateNodeExecutionPlan(project.Network, true)); executionPlan.InitStepPlan.Name = "Initialization"; executionPlan.StandardStepPlan = new MyExecutionBlock( CreateNodeExecutionPlan(project.World, false), CreateNodeExecutionPlan(project.Network, false)); executionPlan.StandardStepPlan.Name = "Simulation"; return executionPlan; }
public void MyProjectInOut(string Act, int ProjectId, string Refer) { int UserId = Int32.Parse(CurrentUserInfo.UserID); try { if (Act == "Add") { //插入数据库前,查询是否已有数据,避免重复插入,ljk0830 if (MyDao.GetCountByProjectIdUserId(ProjectId,UserId)==0) { MyProject Model = new MyProject(); Model.ProjectId = ProjectId; Model.UserId = UserId; Model.AddTime = DateTime.Now; Model.Creator = CurrentUserInfo.UserName; MyDao.Insert(Model); } } else { MyDao.DeleteByProjectIdUserId(ProjectId, UserId); } Response.Redirect(Base64.DecodeBase64(Refer)); } catch (Exception Ex) { throw new Exception(Ex.Message); } }
private void RestoreObserverForms(MyProject project = null) { if (project == null) project = Project; foreach (MyAbstractObserver observer in project.Observers.Where(observer => observer.GenericTarget != null)) ShowObserverView(observer); project.Observers = null; }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(new[] { SerializationIdSeparator }, StringSplitOptions.RemoveEmptyEntries); Node = FindNode(project, idSplit[0]); var workingNode = Node as MyWorkingNode; if (workingNode == null) throw new SerializationException("A task dashboard property found a node without tasks"); Task = workingNode.GetTaskByPropertyName(idSplit[1]); if (Task == null) throw new SerializationException("A task dashboard property did not find the target task"); PropertyInfo = Task.GetType().GetProperty(idSplit[2]); if (PropertyInfo == null) throw new SerializationException("A task dashboard property was not found on the task"); }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(new[] { SerializationIdSeparator }, StringSplitOptions.RemoveEmptyEntries); MyNode node = FindNode(project, idSplit[0]); WorkingNode = node as MyWorkingNode; if (Node == null) throw new SerializationException(string.Format("Node id {0} was found but doesn't contain tasks", node.Id)); string taskGroupName = idSplit[1]; TaskGroup taskGroup; if (!WorkingNode.TaskGroups.TryGetValue(taskGroupName, out taskGroup)) throw new SerializationException(string.Format("Task group {0} not found", taskGroupName)); TaskGroup = taskGroup; }
public override void Restore(MyProject project) { foreach (DashboardNodePropertyBase property in project.Dashboard.Properties.Where(p => p.GroupId == PropertyId)) Add(property); }
public abstract void Restore(MyProject project);
public abstract bool UpdateMemoryModel(MyProject project, List<MyNode> orderedNodes);
public void Schedule(MyProject project, IEnumerable<MyWorkingNode> newNodes = null) { // If there are any init tasks in the current plan, copy them over to the new one. // This is mostly for the first simulation step if there is also a model change. MyExecutionBlock oldPlan = null; if (ExecutionPlan != null) oldPlan = ExecutionPlan.InitStepPlan; m_project = project; ExecutionPlan = ExecutionPlanner.CreateExecutionPlan(project, newNodes); if (oldPlan != null) { var newInitPlan = new List<IMyExecutable>(); newInitPlan.AddRange(oldPlan.Children); newInitPlan.AddRange(ExecutionPlan.InitStepPlan.Children); ExecutionPlan.InitStepPlan = new MyExecutionBlock(newInitPlan.ToArray()) {Name = oldPlan.Name}; } ExtractAllNodes(m_project); // Allow subclasses to react to re-scheduling. ScheduleChanged(); }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(new [] {SerializationIdSeparator}, StringSplitOptions.RemoveEmptyEntries); var success = false; int nodeId; if (int.TryParse(idSplit[0], out nodeId)) { Node = project.GetNodeById(nodeId); if (Node != null) success = true; } if (!success) throw new SerializationException("A task dashboard property did not find the specified node"); var workingNode = Node as MyWorkingNode; if (workingNode == null) throw new SerializationException("A task dashboard property found a node without tasks"); Task = workingNode.GetTaskByPropertyName(idSplit[1]); if (Task == null) throw new SerializationException("A task dashboard property did not find the target task"); PropertyInfo = Task.GetType().GetProperty(idSplit[2]); if (PropertyInfo == null) throw new SerializationException("A task dashboard property was not found on the task"); }
public static string GetTempStorage(MyProject project) { return GetTempStorage(project.Name); }
public static bool TempDataExists(MyProject project) { return Directory.Exists(GetTempStorage(project)); }
private int ProjectCmp(MyProject a, MyProject b) { if (a.dueDate.Equals(b.dueDate)) return a.name.CompareTo(b.name); return a.dueDate.CompareTo(b.dueDate); }
/// <summary> /// Creates the execution plan. /// </summary> /// <param name="project">The whole project from which the standard execution plan will be built.</param> /// <param name="initNodes">Ordered list of new nodes from which the initialization plan will be built.</param> /// <returns>The created execution plan.</returns> public MyExecutionPlan CreateExecutionPlan(MyProject project, IEnumerable<MyWorkingNode> initNodes = null) { MyExecutionPlan executionPlan = new MyExecutionPlan(); IMyOrderingAlgorithm ordering = new MyHierarchicalOrdering(); ordering.EvaluateOrder(project.Network); var initBlocks = new List<IMyExecutable>(); if (initNodes != null) initBlocks.AddRange(initNodes.Select(node => CreateNodeExecutionPlan(node, true))); executionPlan.InitStepPlan = new MyExecutionBlock(initBlocks.ToArray()); executionPlan.InitStepPlan.Name = "Initialization"; executionPlan.StandardStepPlan = new MyExecutionBlock( CreateNodeExecutionPlan(project.World, false), CreateNodeExecutionPlan(project.Network, false)); executionPlan.StandardStepPlan.Name = "Simulation"; return executionPlan; }
public int UpdateAfterDeserialization(int topId, MyProject parentProject) { if (topId < this.Id) { topId = this.Id; } this.Owner = parentProject; Dictionary<int, MyNode> nodes = new Dictionary<int,MyNode>(); topId = CollectNodesAndUpdate(this, nodes, topId); parentProject.ReadOnly = false; MyNodeGroup.IteratorAction findUnknownAction = delegate(MyNode node) { if (!MyConfiguration.KnownNodes.ContainsKey(node.GetType())) { MyLog.WARNING.WriteLine("Unknown node type in loaded project: " + node.GetType()); parentProject.ReadOnly = true; try { MyNodeConfig nodeConfig = new MyNodeConfig() { NodeType = node.GetType(), NodeTypeName = node.GetType().FullName }; nodeConfig.InitIcons(Assembly.GetExecutingAssembly()); nodeConfig.AddObservers(Assembly.GetExecutingAssembly()); MyConfiguration.KnownNodes[nodeConfig.NodeType] = nodeConfig; } catch (Exception e) { MyLog.ERROR.WriteLine("Node type loading failed: " + e.Message); } } }; Iterate(true, findUnknownAction); foreach (MyConnectionProxy cp in m_connections) { try { MyConnection connection = new MyConnection(nodes[cp.From], nodes[cp.To], cp.FromIndex, cp.ToIndex); connection.Connect(); } catch (Exception e) { MyLog.ERROR.WriteLine("Error during connection deserialization: From id " + cp.From +" to id " + cp.To); } } return topId; }
public override void Restore(MyProject project) { string[] idSplit = PropertyId.Split(SerializationIdSeparator.ToCharArray()); Node = FindNode(project, idSplit[0]); PropertyInfo = Node.GetType().GetProperty(idSplit[1]); if (PropertyInfo == null) throw new SerializationException("A dashboard property was not found on the node"); }