Exemplo n.º 1
0
		public PropertiesForm(ProfilerProjectMode mode)
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
			projectMode = ProfilerProjectMode.CreateProject;

			project = new ProjectInfo( ProjectType.File );
			this.Mode = mode;
			if (mode == ProfilerProjectMode.CreateProject)
			{
				List<string> files=SerializationHandler.GetRecentlyUsed();
				foreach (string file in files.GetRange(0,Math.Min(files.Count,5)))
				{
					LinkLabel label=new LinkLabel();
					label.AutoSize = true;
					label.Text=file;
					label.Click += delegate
					{
						ProfilerForm.form.Project = SerializationHandler.OpenProjectInfo(label.Text);
						Close();
					};
					recentProjects.Controls.Add(label);

				}
			}
		}
 public ProjectMetadata(ProjectInfo projectInfo)
 {
     if (projectInfo == null)
         throw new ArgumentNullException("projectInfo");
     m_projectInfo = projectInfo;
     Init();
 }
Exemplo n.º 3
0
 public ProjectInfo GetProjectInfo()
 {
     var referenceProjectItems =
         from item in m_project.Items
         where item is ReferenceProjectItem
         select item as ReferenceProjectItem;
     var references =
         new List<ProjectReference>(referenceProjectItems.Count());
     referenceProjectItems.
         ForEach(item => references.Add(
             new ProjectReference
             {
                 Aliases = item.Aliases,
                 Name = item.Name,
                 Location = item.FileName,
                 Version = item.Version,
                 Culture = item.Culture,
                 PublicKeyToken = item.PublicKeyToken
             }));
     var projectInfo = new ProjectInfo
     {
         Name = m_project.Name,
         Configuration = m_project.ActiveConfiguration,
         Platform = m_project.ActivePlatform,
         OutputAssemblyPath = m_project.OutputAssemblyFullPath,
         Type = Guid.Parse(m_project.TypeGuid),
         References = references
     };
     return projectInfo;
 }
 private IList<ProjectReference> CreateUnusedReferencesList(ProjectInfo projectInfo)
 {
     var references =
         from item in projectInfo.References
         where !item.Name.Equals(MsCorLib, StringComparison.InvariantCultureIgnoreCase) &&
             !item.Name.Equals(SystemCore, StringComparison.InvariantCultureIgnoreCase)
         select item;
     return references.ToList();
 }
Exemplo n.º 5
0
		public ProjectProvider (ProjectInfo pinfo) : base (null) {
			AddTarget ("name", pinfo.Name);
			AddTarget ("version", pinfo.Version);
			AddTarget ("compat_code", pinfo.CompatCode);

			// Alias to line up better with how it's declared
			// in the buildfile. (Need the underscore version so
			// we can reference it in .bundles)

			AddTarget ("compat-code", pinfo.CompatCode);
		}
 public static ProjectAssemblyResolver Create(ProjectInfo projectInfo)
 {
     if (projectInfo == null)
         throw new ArgumentNullException("projectInfo");
     var assemblyResolver = new ProjectAssemblyResolver(projectInfo);
     assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(projectInfo.OutputAssemblyPath));
     //assemblyResolver.AddSearchDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
     foreach (var path in GetLocations(projectInfo.References))
     {
         assemblyResolver.AddSearchDirectory(path);
     }
     return assemblyResolver;
 }
        public void ProjectInfo_Serialization_InvalidFileName()
        {
            // 0. Setup
            ProjectInfo pi = new ProjectInfo();

            // 1a. Missing file name - save
            AssertException.Expects<ArgumentNullException>(() => pi.Save(null));
            AssertException.Expects<ArgumentNullException>(() => pi.Save(string.Empty));
            AssertException.Expects<ArgumentNullException>(() => pi.Save("\r\t "));

            // 1b. Missing file name - load
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load(null));
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load(string.Empty));
            AssertException.Expects<ArgumentNullException>(() => ProjectInfo.Load("\r\t "));
        }
 public static List<ProjectInfo> getValue(string sql)
 {
     List<ProjectInfo> list = new List<ProjectInfo>();
     OleDbDataReader odr = DBHelper.GetReader(sql);
     while (odr.Read())
     {
         ProjectInfo pi = new ProjectInfo();
         pi.ProjectID = Convert.ToInt32(odr["ProjectID"]);
         pi.ProjectName = odr["ProjectName"].ToString();
         pi.Province = odr["Province"].ToString();
         pi.Remarks = odr["remarks"].ToString();
         list.Add(pi);
     }
     odr.Close();
     return list;
 }
 public static UnusedReferencesAudit Create(ProjectInfo projectInfo)
 {
     if (projectInfo == null)
         throw new ArgumentNullException("projectInfo");
     switch (projectInfo.Type.ToString("D"))
     {
         case CSharpProjectTypeString:
             return new CSharpProjectAudit(projectInfo);
         case VBasicProjectTypeString:
             return new VBasicProjectAudit(projectInfo);
         case CppCliProjectTypeString:
             return new CppCliProjectAudit(projectInfo);
         default:
             throw new NotImplementedException();
     }
 }
Exemplo n.º 10
0
        public NemerleContainedLanguage(IVsTextBufferCoordinator bufferCoordinator, NemerleIntellisenseProvider intellisenseProject, uint itemId, IVsHierarchy pHierarchy)
        {
            if (null == bufferCoordinator)
            {
                throw new ArgumentNullException("bufferCoordinator");
            }
            if (null == intellisenseProject)
            {
                throw new ArgumentNullException("intellisenseProject");
            }
            _hierarchy = pHierarchy;

            object projectItem = null;
            pHierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out projectItem);

            _projectItem = projectItem as EnvDTE.ProjectItem;

            EnvDTE.Property prop = _projectItem.Properties.Item("FullPath");
            if (prop != null)
                _filePath = prop.Value as string;

            var project = _projectItem.ContainingProject as NemerleOAProject;
            if(project != null)
            {
                _projectInfo = ((NemerleProjectNode)project.Project).ProjectInfo;
            }

            _typeResolutionService = null;
            DynamicTypeService typeService = LanguageService.GetService(typeof(DynamicTypeService)) as DynamicTypeService;
            if (typeService != null)
                _typeResolutionService = typeService.GetTypeResolutionService(this._hierarchy);

            this.bufferCoordinator = bufferCoordinator;
            this.intellisenseProject = intellisenseProject;
            this.itemId = itemId;

            // Make sure that the secondary buffer uses the IronPython language service.
            IVsTextLines buffer;
            ErrorHandler.ThrowOnFailure(bufferCoordinator.GetSecondaryBuffer(out buffer));

            Guid languageGuid;
            this.GetLanguageServiceID(out languageGuid);
            ErrorHandler.ThrowOnFailure(buffer.SetLanguageServiceID(ref languageGuid));

            _documentClosingEventHandler = new _dispDocumentEvents_DocumentClosingEventHandler(OnDocumentClosing);
        }
        public void ProjectInfo_Serialization_SaveAndReload()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid projectGuid = Guid.NewGuid();

            ProjectInfo originalProjectInfo = new ProjectInfo();
            originalProjectInfo.FullPath = "c:\\fullPath\\project.proj";
            originalProjectInfo.ProjectLanguage = "a language";
            originalProjectInfo.ProjectType = ProjectType.Product;
            originalProjectInfo.ProjectGuid = projectGuid;
            originalProjectInfo.ProjectName = "MyProject";

            string fileName = Path.Combine(testFolder, "ProjectInfo1.xml");

            SaveAndReloadProjectInfo(originalProjectInfo, fileName);
        }
        public static void Open(ProjectInfo project)
        {
            foreach (var view in IdeApp.Workbench.Documents)
            {
                var sourceDoc = view.GetContent<SourceControlExplorerView>();
                if (sourceDoc != null)
                {
                    sourceDoc.Load(project.Collection);
                    sourceDoc.ExpandPath(VersionControlPath.RootFolder + project.Name);
                    view.Window.SelectWindow();
                    return;
                }
            }

            var sourceControlExplorerView = new SourceControlExplorerView();
            sourceControlExplorerView.Load(project.Collection);
            sourceControlExplorerView.ExpandPath(VersionControlPath.RootFolder + project.Name);
            IdeApp.Workbench.OpenDocument(sourceControlExplorerView, true);
        }
Exemplo n.º 13
0
			public override object GetResult(out int level)
			{
				level = 1;
				ProjectInfo project = new ProjectInfo();
				NProf.form.Project = project;
				Profiler profiler = new Profiler();
				//project.ApplicationName = @"D:\Meta\0.2\bin\Debug\Meta.exe";
				//project.Arguments = "-test";
				project.ApplicationName = Path.Combine(NProfDirectory, @"TestProfilee\bin\Debug\TestProfilee.exe");

				run = project.CreateRun(profiler);
				run.profiler.Completed += new EventHandler(profiler_Completed);
				run.Start();

				while (result == null)
				{
					Thread.Sleep(100);
				}
				return result;
			}
Exemplo n.º 14
0
        public ActionResult AddProject( [DataSourceRequest] DataSourceRequest request,ProjectInfoModel model)
        {
            ProjectInfo project = new ProjectInfo();
            var getSatusId = _projects.GetstatusName(model.StatusName);
            if(ModelState.IsValid)
            {
                project.Id = model.Id;
                project.PM = model.PM;
                project.Project = model.Project;
                project.ProjectComment = model.ProjectComment;
                project.statusId = getSatusId.Id;
                project.percentage = model.percentage;
                _projects.CreateProjects(project);
                TempData["success"] = "Edited Succefully";
            }
            else
            {
                TempData["fail"] = " Not Edited Succefully";
            }

            return RedirectToAction("ProjectOnDisplay", "AdminProject");
        }
Exemplo n.º 15
0
        public NemerleErrorTask(ProjectInfo projectInfo, CompilerMessage compilerMessage)
        {
            ErrorHelper.ThrowIsNull(projectInfo,     "projectInfo");
            ErrorHelper.ThrowIsNull(compilerMessage, "compilerMessage");

            ProjectInfo     = projectInfo;
            CompilerMessage = compilerMessage;

            var loc = compilerMessage.Location;

            if (loc.FileIndex != 0)
            {
                var span = Utils.SpanFromLocation(loc);
                Document = loc.File;
                Line     = span.iStartLine;
                Column   = span.iStartIndex;
            }

            Text = compilerMessage.Msg;

            switch (compilerMessage.Kind)
            {
                case MessageKind.Error:
                    Priority = TaskPriority.High;
                    ErrorCategory = TaskErrorCategory.Error;
                    break;
                case MessageKind.Warning:
                    Priority = TaskPriority.Normal;
                    ErrorCategory = TaskErrorCategory.Warning;
                    break;
                default:
                    Priority = TaskPriority.Low;
                    ErrorCategory = TaskErrorCategory.Message;
                    break;
            }

            Category = TaskCategory.BuildCompile;
            HierarchyItem = projectInfo.ProjectNode.InteropSafeHierarchy;
        }
        public void ProjectInfo_Serialization_AnalysisResults()
        {
            // 0. Setup
            string testFolder = TestUtils.CreateTestSpecificFolder(this.TestContext);

            Guid projectGuid = Guid.NewGuid();

            ProjectInfo originalProjectInfo = new ProjectInfo();
            originalProjectInfo.ProjectGuid = projectGuid;

            // 1. Null list
            SaveAndReloadProjectInfo(originalProjectInfo, Path.Combine(testFolder, "ProjectInfo_AnalysisResults1.xml"));

            // 2. Empty list
            originalProjectInfo.AnalysisResults = new List<AnalysisResult>();
            SaveAndReloadProjectInfo(originalProjectInfo, Path.Combine(testFolder, "ProjectInfo_AnalysisResults2.xml"));

            // 3. Non-empty list
            originalProjectInfo.AnalysisResults.Add(new AnalysisResult() { Id = string.Empty, Location = string.Empty }); // empty item
            originalProjectInfo.AnalysisResults.Add(new AnalysisResult() { Id = "Id1", Location = "location1" });
            originalProjectInfo.AnalysisResults.Add(new AnalysisResult() { Id = "Id2", Location = "location2" });
            SaveAndReloadProjectInfo(originalProjectInfo, Path.Combine(testFolder, "ProjectInfo_AnalysisResults3.xml"));
        }
        private ContextMenu CreateFilterButtonContextMenu()
        {
            var filterContextMenu = new ContextMenu();

            filterContextMenu.Placement       = PlacementMode.Bottom;
            filterContextMenu.PlacementTarget = _buttonFilter;
            _buttonFilter.ContextMenu         = filterContextMenu;

            var filterContextMenuItemAll = new MenuItem()
            {
                Header = "Show All"
            };

            filterContextMenuItemAll.Click += (sender, eventArgs) =>
            {
                foreach (TreeViewItem projectTreeViewItem in _treeViewProjects.Items)
                {
                    PerformActionOnTreeViewItems(projectTreeViewItem, (treeViewItem) => { treeViewItem.Visibility = Visibility.Visible; });
                }
                filterContextMenu.IsOpen = false;
            };
            filterContextMenu.Items.Add(filterContextMenuItemAll);

            var filterContextMenuItemOnlyExcluded = new MenuItem()
            {
                Header = "Show Only Excluded Files"
            };

            filterContextMenuItemOnlyExcluded.Click += (sender, eventArgs) =>
            {
                foreach (TreeViewItem projectTreeViewItem in _treeViewProjects.Items)
                {
                    ProjectInfo projectInfo = (ProjectInfo)projectTreeViewItem.DataContext;

                    PerformActionOnTreeViewItems(projectTreeViewItem, (treeViewItem) => { treeViewItem.Visibility = Visibility.Visible; });

                    PerformActionOnTreeViewItems(projectTreeViewItem,
                                                 (treeViewItem) =>
                    {
                        SolutionHierarchy.Item item = treeViewItem.DataContext as SolutionHierarchy.Item;
                        if (null != item && item.Type == SolutionHierarchy.Item.ItemType.CppFile)
                        {
                            treeViewItem.Visibility = _solutionSettings.IsExcludedCppFileNameForProject(projectInfo, item.Name) ?
                                                      Visibility.Visible : Visibility.Collapsed;
                        }
                        else
                        {
                            CollapseTreeViewItemIfAllChildrenCollapsed(treeViewItem);
                        }
                    });
                }
                filterContextMenu.IsOpen = false;
            };
            filterContextMenu.Items.Add(filterContextMenuItemOnlyExcluded);

            var filterContextMenuItemOnlyIncluded = new MenuItem()
            {
                Header = "Show Only Included Files"
            };

            filterContextMenuItemOnlyIncluded.Click += (sender, eventArgs) =>
            {
                foreach (TreeViewItem projectTreeViewItem in _treeViewProjects.Items)
                {
                    ProjectInfo projectInfo = (ProjectInfo)projectTreeViewItem.DataContext;

                    PerformActionOnTreeViewItems(projectTreeViewItem, (treeViewItem) => { treeViewItem.Visibility = Visibility.Visible; });

                    PerformActionOnTreeViewItems(projectTreeViewItem,
                                                 (treeViewItem) =>
                    {
                        SolutionHierarchy.Item item = treeViewItem.DataContext as SolutionHierarchy.Item;
                        if (null != item && item.Type == SolutionHierarchy.Item.ItemType.CppFile)
                        {
                            treeViewItem.Visibility = !_solutionSettings.IsExcludedCppFileNameForProject(projectInfo, item.Name) ?
                                                      Visibility.Visible : Visibility.Collapsed;
                        }
                        else
                        {
                            CollapseTreeViewItemIfAllChildrenCollapsed(treeViewItem);
                        }
                    });
                }
                filterContextMenu.IsOpen = false;
            };
            filterContextMenu.Items.Add(filterContextMenuItemOnlyIncluded);

            return(filterContextMenu);
        }
Exemplo n.º 18
0
        public async Task TestUpdatedDocumentHasTextVersionAsync()
        {
            var pid      = ProjectId.CreateNewId();
            var text     = SourceText.From("public class C { }");
            var version  = VersionStamp.Create();
            var docInfo  = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version)));
            var projInfo = ProjectInfo.Create(
                pid,
                version: VersionStamp.Default,
                name: "TestProject",
                assemblyName: "TestProject.dll",
                language: LanguageNames.CSharp,
                documents: new[] { docInfo });

            using var ws = new AdhocWorkspace();
            ws.AddProject(projInfo);
            var doc = ws.CurrentSolution.GetDocument(docInfo.Id);

            Assert.False(doc.TryGetText(out var currentText));
            Assert.False(doc.TryGetTextVersion(out var currentVersion));

            // cause text to load and show that TryGet now works for text and version
            currentText = await doc.GetTextAsync();

            Assert.True(doc.TryGetText(out currentText));
            Assert.True(doc.TryGetTextVersion(out currentVersion));
            Assert.Equal(version, currentVersion);

            // change document
            var root = await doc.GetSyntaxRootAsync();

            var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation());

            Assert.NotSame(root, newRoot);
            var newDoc = doc.WithSyntaxRoot(newRoot);

            Assert.NotSame(doc, newDoc);

            // text is now unavailable since it must be constructed from tree
            Assert.False(newDoc.TryGetText(out currentText));

            // version is available because it is cached
            Assert.True(newDoc.TryGetTextVersion(out currentVersion));

            // access it the hard way
            var actualVersion = await newDoc.GetTextVersionAsync();

            // version is the same
            Assert.Equal(currentVersion, actualVersion);

            // accessing text version did not cause text to be constructed.
            Assert.False(newDoc.TryGetText(out currentText));

            // now access text directly (force it to be constructed)
            var actualText = await newDoc.GetTextAsync();

            actualVersion = await newDoc.GetTextVersionAsync();

            // prove constructing text did not introduce a new version
            Assert.Equal(currentVersion, actualVersion);
        }
Exemplo n.º 19
0
        public void WriteSettingsForProject(ProjectInfo project, IEnumerable <string> files, string fxCopReportFilePath, string codeCoverageFilePath)
        {
            if (this.FinishedWriting)
            {
                throw new InvalidOperationException();
            }

            if (project == null)
            {
                throw new ArgumentNullException("project");
            }
            if (files == null)
            {
                throw new ArgumentNullException("files");
            }

            Debug.Assert(files.Any(), "Expecting a project to have files to analyze");
            Debug.Assert(files.All(f => File.Exists(f)), "Expecting all of the specified files to exist");

            this.projects.Add(project);

            string guid = project.GetProjectGuidAsString();

            AppendKeyValue(sb, guid, SonarProperties.ProjectKey, this.config.SonarProjectKey + ":" + guid);
            AppendKeyValue(sb, guid, SonarProperties.ProjectName, project.ProjectName);
            AppendKeyValue(sb, guid, SonarProperties.ProjectBaseDir, project.GetProjectDirectory());

            if (fxCopReportFilePath != null)
            {
                string property = null;
                if (ProjectLanguages.IsCSharpProject(project.ProjectLanguage))
                {
                    property = "sonar.cs.fxcop.reportPath";
                }
                else if (ProjectLanguages.IsVbProject(project.ProjectLanguage))
                {
                    property = "sonar.vbnet.fxcop.reportPath";
                }

                if (property != null)
                {
                    AppendKeyValue(sb, guid, property, fxCopReportFilePath);
                }
                else
                {
                    Debug.Fail("FxCopReportFilePath is set but the language is unrecognised. Language: " + project.ProjectLanguage);
                }
            }

            if (codeCoverageFilePath != null)
            {
                AppendKeyValue(sb, guid, "sonar.cs.vscoveragexml.reportsPaths", codeCoverageFilePath);
            }

            if (project.ProjectType == ProjectType.Product)
            {
                sb.AppendLine(guid + @".sonar.sources=\");
            }
            else
            {
                AppendKeyValue(sb, guid, "sonar.sources", "");
                sb.AppendLine(guid + @".sonar.tests=\");
            }

            IEnumerable <string> escapedFiles = files.Select(f => Escape(f));

            sb.AppendLine(string.Join(@",\" + Environment.NewLine, escapedFiles));

            sb.AppendLine();

            if (project.AnalysisSettings != null && project.AnalysisSettings.Any())
            {
                foreach (Property setting in project.AnalysisSettings)
                {
                    sb.AppendFormat("{0}.{1}={2}", guid, setting.Id, Escape(setting.Value));
                    sb.AppendLine();
                }
                sb.AppendLine();
            }
        }
Exemplo n.º 20
0
    /// <summary>
    /// Saves control with actual data.
    /// </summary>
    public bool Save()
    {
        if (!CheckPermissions("CMS.ProjectManagement", PERMISSION_MANAGE))
        {
            return false;
        }

        // Validate the form
        if (Validate())
        {
            // Indicates whether project is new
            bool isNew = false;

            int progress = 0;

            // Ensure the info object
            if (ProjectObj == null)
            {
                // New project

                ProjectInfo pi = new ProjectInfo();
                // First initialization of the Access property - allow authenticated users
                pi.ProjectAccess = 1222;
                pi.ProjectCreatedByID = CMSContext.CurrentUser.UserID;

                pi.ProjectOwner = 0;

                if (CommunityGroupID != 0)
                {
                    pi.ProjectGroupID = CommunityGroupID;
                    // Set default access to the group
                    pi.ProjectAccess = 3333;
                }

                mProjectObj = pi;
                isNew = true;
            }
            else
            {
                // Existing project

                // Reset ProjectOrder if checkbox was unchecked
                if ((ProjectObj.ProjectAllowOrdering)
                    && (!chkProjectAllowOrdering.Checked))
                {
                    ProjectInfoProvider.ResetProjectOrder(ProjectObj.ProjectID);
                }

                // Clear the hashtables if the codename has been changed
                if ((ProjectObj.ProjectGroupID > 0)
                    && ProjectObj.ProjectName != txtProjectName.Text)
                {
                    ProjectInfoProvider.Clear(true);
                }

                progress = ProjectInfoProvider.GetProjectProgress(ProjectObj.ProjectID);
            }

            ltrProjectProgress.Text = ProjectTaskInfoProvider.GenerateProgressHtml(progress, true);

            // Initialize object
            ProjectObj.ProjectSiteID = CMSContext.CurrentSiteID;

            if (DisplayMode == ControlDisplayModeEnum.Simple)
            {
                if (isNew)
                {
                    ProjectObj.ProjectName = ValidationHelper.GetCodeName(txtProjectDisplayName.Text, 50) + ((CommunityGroupID > 0) ? "_group_" : "_general_") + CodenameGUID;
                }
            }
            else
            {
                ProjectObj.ProjectName = txtProjectName.Text.Trim();
            }
            ProjectObj.ProjectDisplayName = txtProjectDisplayName.Text.Trim();
            ProjectObj.ProjectDescription = txtProjectDescription.Text.Trim();
            ProjectObj.ProjectStartDate = dtpProjectStartDate.SelectedDateTime;
            ProjectObj.ProjectDeadline = dtpProjectDeadline.SelectedDateTime;
            ProjectObj.ProjectOwner = ValidationHelper.GetInteger(userSelector.UniSelector.Value, 0);
            ProjectObj.ProjectStatusID = ValidationHelper.GetInteger(drpProjectStatus.SelectedValue, 0);
            ProjectObj.ProjectAllowOrdering = chkProjectAllowOrdering.Checked;

            // Set ProjectNodeID
            if (!ShowPageSelector)
            {
                // Set current node id for new project
                if (isNew && (CMSContext.CurrentDocument != null))
                {
                    ProjectObj.ProjectNodeID = CMSContext.CurrentDocument.NodeID;
                }
            }
            else
            {
                TreeProvider treeProvider = new TreeProvider();
                TreeNode node = treeProvider.SelectSingleNode(ValidationHelper.GetGuid(pageSelector.Value, Guid.Empty), TreeProvider.ALL_CULTURES, CMSContext.CurrentSiteName);
                if (node != null)
                {
                    ProjectObj.ProjectNodeID = node.NodeID;
                }
                else
                {
                    ProjectObj.ProjectNodeID = 0;
                }
            }

            // Use try/catch due to license check
            try
            {
                // Save object data to database
                ProjectInfoProvider.SetProjectInfo(ProjectObj);
                ProjectID = ProjectObj.ProjectID;

                ItemID = ProjectObj.ProjectID;
                RaiseOnSaved();

                // Set the info message
                ShowChangesSaved();
                return true;
            }
            catch (Exception ex)
            {
                ShowError(ex.Message);
            }
        }
        return false;
    }
Exemplo n.º 21
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Handle the OK button.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/// ------------------------------------------------------------------------------------
		private void btnOK_Click(object sender, System.EventArgs e)
		{
			Enabled = false;
			DialogResult = DialogResult.OK;

			Logger.WriteEvent(string.Format(
				"Creating new language project: name: {0}, vernacular ws: {1}, anal ws: {2}",
				ProjectName, m_cbVernWrtSys.Text, m_cbAnalWrtSys.Text));

			m_projInfo = GetProjectInfoByName(ProjectName);
			// Project with this name already exists?
			if (m_projInfo != null)
			{
				// Bring up a dialog giving the user the option to open this existing project,
				//  create a new project or cancel (return to New Project dialog).
				using (DuplicateProjectFoundDlg dlg = new DuplicateProjectFoundDlg())
				{
					dlg.ShowDialog();

					switch (dlg.DialogResult)
					{
						case DialogResult.OK:
							m_fCreateNew = false;
							break;
						case DialogResult.Cancel:
							// Return to New FieldWorks Project dialog
							Enabled = true;
							DialogResult = DialogResult.None;
							break;
					}
				}
			}
			else
			{
				// The project does not exist yet. Bring up the new project dialog box.
				CreateNewLangProjWithProgress();
			}
		}
Exemplo n.º 22
0
        private String WriteEmployerBasicInfo(ProjectInfo projectmodels)
        {
            m_wordApp.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
            m_wordApp.Selection.Font.Size = 14;
            m_wordApp.Selection.Font.Bold = 2;
            m_wordApp.Selection.TypeText("水  质   检   测   报   告 ");
            m_wordApp.Selection.TypeParagraph();

            Word.Table basicInfo = m_doc.Tables.Add(m_wordApp.Selection.Range, 14, 4);
            basicInfo.Borders.Enable           = 1;
            basicInfo.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleNone;
            basicInfo.Borders[WdBorderType.wdBorderTop].LineStyle    = WdLineStyle.wdLineStyleSingle;
            basicInfo.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleSingle;
            basicInfo.Columns[1].Width = 100;

            basicInfo.Rows[1].Height = 10;                    ///单位名称
            basicInfo.Cell(1, 1).Select();
            SetCellHeaderText("委托单位:");
            basicInfo.Cell(1, 2).Merge(basicInfo.Cell(1, 4));
            basicInfo.Cell(1, 2).Select();
            SetCellText(0, 12, projectmodels.CompaneName, WdParagraphAlignment.wdAlignParagraphLeft, WdCellVerticalAlignment.wdCellAlignVerticalCenter);

            basicInfo.Rows[2].Height = 10;                    ///单位名称
            basicInfo.Cell(2, 1).Select();
            SetCellHeaderText("受检单位:");
            basicInfo.Cell(2, 2).Merge(basicInfo.Cell(2, 4));
            basicInfo.Cell(2, 2).Select();
            SetCellText(0, 12, projectmodels.CompaneName, WdParagraphAlignment.wdAlignParagraphLeft, WdCellVerticalAlignment.wdCellAlignVerticalCenter);

            basicInfo.Rows[3].Height = 10;                 ///项目名称
            basicInfo.Cell(3, 1).Select();
            SetCellHeaderText("受检单位地址:");
            basicInfo.Cell(3, 2).Merge(basicInfo.Cell(3, 4));
            basicInfo.Cell(3, 2).Select();
            SetCellText(0, 12, projectmodels.CompanyAddress, WdParagraphAlignment.wdAlignParagraphLeft, WdCellVerticalAlignment.wdCellAlignVerticalCenter);

            basicInfo.Rows[4].Height = 10;                 ///项目名称
            basicInfo.Cell(4, 1).Select();
            SetCellHeaderText("检测类别:");
            basicInfo.Cell(4, 2).Select();
            SetCellHeaderText("   ");
            basicInfo.Cell(4, 3).Select();
            SetCellHeaderText("受理日期:");
            basicInfo.Cell(4, 4).Select();

            basicInfo.Rows[5].Height = 10;                 ///项目名称
            basicInfo.Cell(5, 1).Select();
            SetCellHeaderText("样品来源:");
            basicInfo.Cell(5, 2).Select();
            SetCellHeaderText("采样");
            basicInfo.Cell(5, 3).Select();
            SetCellHeaderText("采样日期:");
            basicInfo.Cell(5, 4).Select();

            basicInfo.Rows[6].Height = 10;                 ///项目名称
            basicInfo.Cell(6, 1).Select();
            SetCellHeaderText("样品数量:");
            basicInfo.Cell(6, 2).Select();
            SetCellHeaderText("   ");
            basicInfo.Cell(6, 3).Select();
            SetCellHeaderText("检测日期:");
            basicInfo.Cell(6, 4).Select();

            basicInfo.Cell(7, 1).Merge(basicInfo.Cell(8, 1));
            basicInfo.Cell(7, 1).Select();
            SetCellHeaderText("主要仪器设备:");
            basicInfo.Cell(7, 2).Merge(basicInfo.Cell(8, 4));
            basicInfo.Cell(7, 2).Select();
            SetCellHeaderText("        ");

            basicInfo.Cell(8, 1).Merge(basicInfo.Cell(14, 1));
            basicInfo.Cell(8, 1).Select();
            SetCellHeaderText("检测依据:");
            basicInfo.Cell(8, 2).Merge(basicInfo.Cell(14, 4));
            basicInfo.Cell(8, 2).Select();
            SetCellHeaderText("        ");

            m_wordApp.Selection.MoveDown();//光标下移,光标移出表格
            m_wordApp.Selection.TypeText("\r\n");
            return("0");
        }
Exemplo n.º 23
0
 public void AddProject(ProjectInfo projectInfo)
 {
     OnProjectAdded(projectInfo);
 }
        public async Task <FileBasedProject> CreateBackTranslationProject(FileBasedProject project, string localProjectFolder,
                                                                          string targetLanguage, string iconPath,
                                                                          List <SourceFile> sourceFiles, string projectNameSuffix)
        {
            if (string.IsNullOrEmpty(projectNameSuffix))
            {
                throw new Exception(PluginResources.Warning_Message_ProjectNameSuffixCannotBeNull);
            }

            var projectInfo = project.GetProjectInfo();

            var newSourceLanguage = projectInfo.TargetLanguages.FirstOrDefault(a =>
                                                                               string.Compare(a.CultureInfo.Name, targetLanguage, StringComparison.CurrentCultureIgnoreCase) == 0);
            var newTargetLanguage = projectInfo.SourceLanguage;

            if (Directory.Exists(localProjectFolder))
            {
                Directory.Delete(localProjectFolder, true);
            }

            var projectReference = new ProjectReference(project.FilePath);
            var newProjectInfo   = new ProjectInfo
            {
                Name               = projectInfo.Name + "-" + projectNameSuffix + "-" + targetLanguage,
                Description        = projectInfo.Description,
                LocalProjectFolder = localProjectFolder,
                SourceLanguage     = newSourceLanguage,
                TargetLanguages    = new Language[] { newTargetLanguage },
                DueDate            = projectInfo.DueDate,
                ProjectOrigin      = Constants.ProjectOrigin_BackTranslationProject,
                IconPath           = iconPath
            };

            var newProject = new FileBasedProject(newProjectInfo, projectReference);

            foreach (var sourceFile in sourceFiles)
            {
                if (!string.IsNullOrEmpty(sourceFile.FilePath) &&
                    File.Exists(sourceFile.FilePath))
                {
                    newProject.AddFiles(new[] { sourceFile.FilePath }, sourceFile.FolderPathInProject);
                }
            }
            newProject.Save();

            UpdateProjectSettingsBundle(newProject, null, null, null);

            // Remove any TMs that don't correspond to the language directions of the project
            UpdateTmConfiguration(newProject);

            var languageFileIds = newProject.GetSourceLanguageFiles().GetIds();

            newProject.RunAutomaticTask(
                languageFileIds,
                AutomaticTaskTemplateIds.Scan);

            var sourceGuids = GetProjectFileGuids(newProject.GetSourceLanguageFiles());

            if (sourceGuids.Count > 0)
            {
                newProject.RunAutomaticTask(
                    sourceGuids.ToArray(),
                    AutomaticTaskTemplateIds.ConvertToTranslatableFormat);

                newProject.RunAutomaticTask(
                    sourceGuids.ToArray(),
                    AutomaticTaskTemplateIds.CopyToTargetLanguages);
            }

            newProject.Save();
            return(await System.Threading.Tasks.Task.FromResult(newProject));
        }
            private Task <ProjectInfo> CreateProjectInfoAsync(ProjectFileInfo projectFileInfo, ProjectId projectId, bool addDiscriminator, CancellationToken cancellationToken)
            {
                var language    = projectFileInfo.Language;
                var projectPath = projectFileInfo.FilePath;

                var projectName = Path.GetFileNameWithoutExtension(projectPath);

                if (addDiscriminator && !string.IsNullOrWhiteSpace(projectFileInfo.TargetFramework))
                {
                    projectName += "(" + projectFileInfo.TargetFramework + ")";
                }

                var version = VersionStamp.Create(
                    FileUtilities.GetFileTimeStamp(projectPath));

                if (projectFileInfo.IsEmpty)
                {
                    var assemblyName = GetAssemblyNameFromProjectPath(projectPath);

                    var parseOptions = GetLanguageService <ISyntaxTreeFactoryService>(language)
                                       .GetDefaultParseOptions();
                    var compilationOptions = GetLanguageService <ICompilationFactoryService>(language)
                                             .GetDefaultCompilationOptions();

                    return(Task.FromResult(
                               ProjectInfo.Create(
                                   projectId,
                                   version,
                                   projectName,
                                   assemblyName: assemblyName,
                                   language: language,
                                   filePath: projectPath,
                                   outputFilePath: string.Empty,
                                   outputRefFilePath: string.Empty,
                                   compilationOptions: compilationOptions,
                                   parseOptions: parseOptions,
                                   documents: SpecializedCollections.EmptyEnumerable <DocumentInfo>(),
                                   projectReferences: SpecializedCollections.EmptyEnumerable <ProjectReference>(),
                                   metadataReferences: SpecializedCollections.EmptyEnumerable <MetadataReference>(),
                                   analyzerReferences: SpecializedCollections.EmptyEnumerable <AnalyzerReference>(),
                                   additionalDocuments: SpecializedCollections.EmptyEnumerable <DocumentInfo>(),
                                   isSubmission: false,
                                   hostObjectType: null)));
                }

                return(DoOperationAndReportProgressAsync(ProjectLoadOperation.Resolve, projectPath, projectFileInfo.TargetFramework, async() =>
                {
                    var projectDirectory = Path.GetDirectoryName(projectPath);

                    // parse command line arguments
                    var commandLineParser = GetLanguageService <ICommandLineParserService>(projectFileInfo.Language);

                    var commandLineArgs = commandLineParser.Parse(
                        arguments: projectFileInfo.CommandLineArgs,
                        baseDirectory: projectDirectory,
                        isInteractive: false,
                        sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory());

                    var assemblyName = commandLineArgs.CompilationName;
                    if (string.IsNullOrWhiteSpace(assemblyName))
                    {
                        // if there isn't an assembly name, make one from the file path.
                        // Note: This may not be necessary any longer if the commmand line args
                        // always produce a valid compilation name.
                        assemblyName = GetAssemblyNameFromProjectPath(projectPath);
                    }

                    // Ensure sure that doc-comments are parsed
                    var parseOptions = commandLineArgs.ParseOptions;
                    if (parseOptions.DocumentationMode == DocumentationMode.None)
                    {
                        parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse);
                    }

                    // add all the extra options that are really behavior overrides
                    var metadataService = GetWorkspaceService <IMetadataService>();
                    var compilationOptions = commandLineArgs.CompilationOptions
                                             .WithXmlReferenceResolver(new XmlFileResolver(projectDirectory))
                                             .WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory))
                                             // TODO: https://github.com/dotnet/roslyn/issues/4967
                                             .WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray <string> .Empty, projectDirectory)))
                                             .WithStrongNameProvider(new DesktopStrongNameProvider(commandLineArgs.KeyFileSearchPaths))
                                             .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

                    var documents = CreateDocumentInfos(projectFileInfo.Documents, projectId, commandLineArgs.Encoding);
                    var additionalDocuments = CreateDocumentInfos(projectFileInfo.AdditionalDocuments, projectId, commandLineArgs.Encoding);
                    CheckForDuplicateDocuments(documents, additionalDocuments, projectPath, projectId);

                    var analyzerReferences = ResolveAnalyzerReferences(commandLineArgs);

                    var resolvedReferences = await ResolveReferencesAsync(projectId, projectFileInfo, commandLineArgs, cancellationToken).ConfigureAwait(false);

                    return ProjectInfo.Create(
                        projectId,
                        version,
                        projectName,
                        assemblyName,
                        language,
                        projectPath,
                        outputFilePath: projectFileInfo.OutputFilePath,
                        outputRefFilePath: projectFileInfo.OutputRefFilePath,
                        compilationOptions: compilationOptions,
                        parseOptions: parseOptions,
                        documents: documents,
                        projectReferences: resolvedReferences.ProjectReferences,
                        metadataReferences: resolvedReferences.MetadataReferences,
                        analyzerReferences: analyzerReferences,
                        additionalDocuments: additionalDocuments,
                        isSubmission: false,
                        hostObjectType: null)
                    .WithDefaultNamespace(projectFileInfo.DefaultNamespace);
                }));
            }
Exemplo n.º 26
0
        Project AddProject(IBuildEngine buildEngine, string projectPath, CancellationToken cancellation)
        {
            // NOTE: we use a different workspace for each project added
            // because we need to set the current configuration/platform
            // as a global property for each, according to the current
            // solution configuration as detected by the current global
            // properties. This is automatically done by the workspace
            // factory, which looks up the project by ID and determines
            // the configuration/platform to load.
            using (var loader = loaderFactory.Create(buildEngine))
            {
                cancellation.ThrowIfCancellationRequested();

                var xml                = loader.LoadXml(projectPath);
                var msbuildProject     = xml.ToDynamic();
                var msbuildProjectFile = (string)msbuildProject["FilePath"];

                // Use the msbuild project to add a new project to the current solution of the workspace
                OnProjectAdded(
                    ProjectInfo.Create(
                        ProjectId.CreateFromSerialized(new Guid((string)msbuildProject["Id"])),
                        VersionStamp.Default,
                        (string)msbuildProject["Name"],
                        (string)msbuildProject["AssemblyName"],
                        (string)msbuildProject["Language"],
                        msbuildProjectFile,
                        outputFilePath: (string)msbuildProject["OutputFilePath"],
                        metadataReferences: ((XElement)msbuildProject.MetadataReferences)
                        .Elements("MetadataReference")
                        .Select(e => MetadataReference.CreateFromFile(e.Attribute("FilePath").Value)),
                        compilationOptions: new CSharpCompilationOptions(
                            (OutputKind)(Enum.Parse(typeof(OutputKind), (string)msbuildProject.CompilationOptions["OutputKind"])),
                            platform: (Platform)(Enum.Parse(typeof(Platform), (string)msbuildProject.CompilationOptions["Platform"])))));

                cancellation.ThrowIfCancellationRequested();

                // Add the documents to the workspace
                foreach (XElement document in ((XElement)msbuildProject.Documents).Elements("Document"))
                {
                    AddDocument(msbuildProjectFile, document, false);
                    cancellation.ThrowIfCancellationRequested();
                }

                foreach (XElement document in ((XElement)msbuildProject.AdditionalDocuments).Elements("Document"))
                {
                    AddDocument(msbuildProjectFile, document, true);
                    cancellation.ThrowIfCancellationRequested();
                }

                // Fix references
                // Iterate the references of the msbuild project
                var referencesToAdd = new List <ProjectReference>();
                foreach (var referencePath in ((XElement)msbuildProject.ProjectReferences).Elements("ProjectReference").Select(e => e.Attribute("FilePath").Value))
                {
                    var referencedProject = GetOrAddProject(buildEngine, referencePath, cancellation);
                    referencesToAdd.Add(new ProjectReference(referencedProject.Id));
                }

                cancellation.ThrowIfCancellationRequested();

                if (referencesToAdd.Count > 0)
                {
                    var addedProject = FindProjectByPath(msbuildProjectFile);

                    TryApplyChanges(CurrentSolution.WithProjectReferences(addedProject.Id, referencesToAdd));
                }

                return(FindProjectByPath(projectPath));
            }
        }
Exemplo n.º 27
0
        public MessageModel CreateProject(PackageModel package)
        {
            var penaltiesTmsList = new List <StarTranslationMemoryMetadata>();
            var target           = GetTargetLanguages(package.LanguagePairs);

            var projectInfo = new ProjectInfo
            {
                Name = package.Name,
                LocalProjectFolder = package.Location,
                SourceLanguage     = new Language(package.LanguagePairs[0].SourceLanguage),
                TargetLanguages    = target,
                DueDate            = package.DueDate
            };

            var newProject = new FileBasedProject(projectInfo,
                                                  new ProjectTemplateReference(package.ProjectTemplate.Uri));

            if (package.Customer != null)
            {
                newProject.SetCustomer(package.Customer);
            }

            //Add StarTransit package source files. The same on all language pairs
            ProjectFile[] sourceProjectFiles = newProject.AddFiles(package.LanguagePairs[0].SourceFile.ToArray());

            //set the file role(user to display project details in Studio view)
            var sourceFilesIds = newProject.GetSourceLanguageFiles().GetIds();

            newProject.SetFileRole(sourceFilesIds, FileRole.Translatable);

            var tmConfig        = newProject.GetTranslationProviderConfiguration();
            var fileTypeManager = DefaultFileTypeManager.CreateInstance(true);

            List <ProjectFile> targetProjectFiles = new List <ProjectFile>();

            foreach (var pair in package.LanguagePairs)
            {
                // Separate all items from package.TMPenalties(files that are having penalties set)
                // which are found in pair.StarTranslationMemoryMetadatas
                foreach (var starTMMetadata in pair.StarTranslationMemoryMetadatas)
                {
                    if (package.TMPenalties != null)
                    {
                        if (package.TMPenalties.Any(t => t.Key.Equals(starTMMetadata.TargetFile)))
                        {
                            starTMMetadata.TMPenalty = package.TMPenalties.FirstOrDefault(t => t.Key.Equals(starTMMetadata.TargetFile)).Value;
                            penaltiesTmsList.Add(starTMMetadata);
                        }
                    }
                }

                // Remove found items from pair.StarTranslationMemoryMetadatas (the remained ones are those which does not have penalties set on them)
                foreach (var item in penaltiesTmsList)
                {
                    pair.StarTranslationMemoryMetadatas.Remove(item);
                }

                // Create one TM (that has the name equals with the project name)
                // with the TM files from pair.StarTranslationMemoryMetadatas (the onew without penalties set by the user)
                targetProjectFiles.Clear();

                // Import language pair TM if any
                if (pair.HasTm)
                {
                    if (pair.StarTranslationMemoryMetadatas.Count > 0)
                    {
                        var importer = new TransitTmImporter(pair.SourceLanguage,
                                                             pair.TargetLanguage,
                                                             pair.CreateNewTm,
                                                             fileTypeManager,
                                                             Path.Combine(Path.GetDirectoryName(newProject.FilePath), Path.GetFileName(pair.TmPath)));
                        foreach (var tm in pair.StarTranslationMemoryMetadatas)
                        {
                            importer.ImportStarTransitTm(tm.TargetFile);
                        }

                        tmConfig.Entries.Add(new TranslationProviderCascadeEntry(importer.GetTranslationProviderReference(),
                                                                                 true,
                                                                                 true,
                                                                                 true));
                    }

                    // Create separate TM for each TM file on which user set penalty
                    // (the name of the new TM will be the same with the one from StarTransit package)
                    foreach (var item in penaltiesTmsList)
                    {
                        var tmWithPenaltyImporter = new TransitTmImporter(
                            Path.GetDirectoryName(newProject.FilePath),
                            pair.SourceLanguage,
                            pair.TargetLanguage,
                            Path.GetFileName(item.TargetFile),
                            fileTypeManager);

                        tmWithPenaltyImporter.ImportStarTransitTm(item.TargetFile);

                        tmConfig.Entries.Add(new TranslationProviderCascadeEntry(
                                                 new TranslationProviderReference(tmWithPenaltyImporter.TMFilePath),
                                                 true,
                                                 true,
                                                 true,
                                                 item.TMPenalty));
                    }
                }
                if (!pair.TargetFile.Any() || pair.TargetFile.Count == 0)
                {
                    var messageModel = new MessageModel()
                    {
                        IsProjectCreated = false,
                        Message          = "Project was not created correctly because no target files were found in the package!",
                        Title            = "Informative message"
                    };
                    return(messageModel);
                }
                else
                {
                    targetProjectFiles.AddRange(newProject.AddFiles(pair.TargetFile.ToArray()));
                    newProject.RunAutomaticTask(targetProjectFiles.GetIds(), AutomaticTaskTemplateIds.Scan);
                    var taskSequence = newProject.RunAutomaticTasks(targetProjectFiles.GetIds(), new string[]
                    {
                        AutomaticTaskTemplateIds.ConvertToTranslatableFormat,
                        AutomaticTaskTemplateIds.CopyToTargetLanguages,
                        AutomaticTaskTemplateIds.PerfectMatch,
                        AutomaticTaskTemplateIds.PreTranslateFiles,
                        AutomaticTaskTemplateIds.AnalyzeFiles,
                    });

                    if (taskSequence.Status.Equals(TaskStatus.Failed))
                    {
                        var messageModel = new MessageModel()
                        {
                            IsProjectCreated = false,
                            Message          = "Project could not be created.Error occured while running automatic tasks!",
                            Title            = "Informative message"
                        };
                        return(messageModel);
                    }
                    else
                    {
                        newProject.UpdateTranslationProviderConfiguration(tmConfig);
                        newProject.Save();
                    }
                }
            }

            if (Directory.Exists(Path.GetDirectoryName(newProject.FilePath)))
            {
                CreateMetadataFolder(package.Location, package.PathToPrjFile);

                Controller.RefreshProjects();
            }
            return(null);
        }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        gridMatrix.OnItemChanged += gridMatrix_OnItemChanged;
        gridMatrix.StopProcessing = true;
        gridMatrix.ColumnsPreferedOrder = string.Join(",", mAllowedPermissions);

        if (ProjectID > 0)
        {
            mProject = ProjectInfoProvider.GetProjectInfo(ProjectID);

            // Check whether the project still exists
            EditedObject = mProject;
        }

        // Handle page chnaged event
        gridMatrix.OnPageChanged += gridMatrix_OnPageChanged;

        // Disable permission matrix if user has no MANAGE rights
        if (!ProjectInfoProvider.IsAuthorizedPerProject(ProjectID, PERMISSION_MANAGE, MembershipContext.AuthenticatedUser))
        {
            Enable = false;
            gridMatrix.Enabled = false;
            lblError.Text = String.Format(GetString("general.accessdeniedonpermissionname"), "Manage");
            lblError.Visible = true;
        }
    }
Exemplo n.º 29
0
        private void AddToRecentProjects(Project project)
        {
            if (project == null)
                return;

            ProjectInfo alreadyThere = RecentProjects.SingleOrDefault(p => p.ProjectUId == project.ProjectUId);

            if (alreadyThere != null) {
                int idx = RecentProjects.IndexOf(alreadyThere);
                RecentProjects.Remove(alreadyThere);

                if(idx >=0 && idx < jumpList.JumpItems.Count)
                    jumpList.JumpItems.RemoveAt(idx);
            }

            ProjectInfo pInfo = new ProjectInfo(project);
            jumpList.JumpItems.Insert(0, CreateProjectJumpItem(pInfo));
            RecentProjects.Insert(0, pInfo);

            if (RecentProjects.Count > 10) {
                int toBeRemoved = RecentProjects.Count - 10;
                RecentProjects.RemoveRange(10, toBeRemoved);
            }

            if (jumpList.JumpItems.Count > 10) {
                int toBeRemoved = jumpList.JumpItems.Count - 10;
                jumpList.JumpItems.RemoveRange(10, toBeRemoved);
            }

            aggregator.Publish<ICollection<ProjectInfo>>(ScrumFactoryEvent.RecentProjectChanged, RecentProjects);

            jumpList.Apply();
        }
Exemplo n.º 30
0
 public CreatWaterTestDoc(ProjectInfo projectinfo)
 {
     // start word and turn off msg boxes
     this.Header = projectinfo.ProjectNumber + "                   DKL/QB-33-03                     ";;
 }
Exemplo n.º 31
0
        static void DumpNetModule(ProjectInfo info, List<ProjectInfo> projectFiles)
        {
            var fileName = info.AssemblyFileName;
            if (string.IsNullOrEmpty(fileName))
                throw new Exception(".NET module filename is empty or null");

            var asmList = new AssemblyList("dnspc.exe", false);
            asmList.UseGAC = !noGac;
            asmList.AddSearchPath(Path.GetDirectoryName(fileName));
            foreach (var path in asmPaths)
                asmList.AddSearchPath(path);
            var lasm = new LoadedAssembly(asmList, fileName);
            var opts = new DecompilationOptions {
                FullDecompilation = true,
                CancellationToken = new CancellationToken(),
            };

            TextWriter writer = null;
            try {
                var lang = GetLanguage();

                if (useStdout)
                    writer = System.Console.Out;
                else {
                    var baseDir = GetProjectDir(lang, fileName);
                    Directory.CreateDirectory(baseDir);
                    writer = new StreamWriter(info.ProjectFileName, false, Encoding.UTF8);
                    opts.SaveAsProjectDirectory = baseDir;
                    opts.DontReferenceStdLib = noCorlibRef;
                    opts.ProjectFiles = projectFiles;
                    opts.ProjectGuid = info.ProjectGuid;
                    opts.DontShowCreateMethodBodyExceptions = dontMaskErr;
                    Console.WriteLine("Saving {0} to {1}", fileName, baseDir);
                }

                lang.DecompileAssembly(lasm, new PlainTextOutput(writer), opts);
            }
            finally {
                if (!useStdout && writer != null)
                    writer.Dispose();
            }
        }
 public abstract bool IsApplicable(ProjectInfo projectInfo);
Exemplo n.º 33
0
        public void Initalize(IConfiguration configuration)
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                                        LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine <NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib          = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
            var systemCore        = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location);
            var scriptcsContracts = MetadataReference.CreateFromFile(typeof(IScriptHost).Assembly.Location);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks   = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List <MetadataReference> {
                        mscorlib, systemCore, scriptcsContracts
                    };
                    var usings = new List <string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project   = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                       compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId         = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                                                                             $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                                                             compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
 public abstract IEnumerable <ITask> Create(ProjectInfo projectInfo);
Exemplo n.º 35
0
        internal async Task <(Compilation compilation, List <MetadataReference> metadata)> CreateCompilationAsync(IEnumerable <string> paths, IEnumerable <string> assemblies, IEnumerable <string> preprocessors = null, Regex[] filters = null)
        {
            Console.WriteLine("Creating workspace...");

            var ws           = new AdhocWorkspace();
            var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Default);

            ws.AddSolution(solutionInfo);
            var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Default, "CSharpExample", "CSharpExample", "C#");

            ws.AddProject(projectInfo);
            if (paths != null)
            {
                foreach (var path in paths)
                {
                    if (path.StartsWith("http://") || path.StartsWith("https://"))
                    {
                        await DownloadDocumentsAsync(path, ws, projectInfo.Id, filters).ConfigureAwait(false);
                    }
                    else if (path.EndsWith(".zip"))
                    {
                        LoadCompressedDocuments(path, ws, projectInfo.Id, filters);
                    }
                    else
                    {
                        LoadFolderDocuments(path, ws, projectInfo.Id, filters);
                    }
                }
            }
            Console.WriteLine("Compiling...");
            var project = ws.CurrentSolution.Projects.Single();
            List <MetadataReference> metadata = new List <MetadataReference>();

            if (assemblies != null)
            {
                foreach (var assm in assemblies)
                {
                    IEnumerable <FileInfo> files = Enumerable.Empty <FileInfo>();
                    if (File.Exists(assm))
                    {
                        files = new FileInfo[] { new FileInfo(assm) };
                    }
                    else
                    {
                        string recursive   = Path.DirectorySeparatorChar + "**" + Path.DirectorySeparatorChar;
                        bool   isRecursive = false;
                        var    d           = assm;
                        var    fn          = Path.GetFileName(assm);
                        if (d.Contains(recursive))
                        {
                            d           = d.Substring(0, d.IndexOf(recursive));
                            isRecursive = true;
                        }
                        else if (Directory.Exists(d))
                        {
                            fn = null;
                        }
                        else
                        {
                            d = Path.GetDirectoryName(d);
                        }
                        var dir = new DirectoryInfo(d);
                        if (!dir.Exists)
                        {
                            throw new DirectoryNotFoundException(d);
                        }
                        if (string.IsNullOrEmpty(fn))
                        {
                            files = dir.GetFiles("*.dll", isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                        }
                        else
                        {
                            var di = new DirectoryInfo(d);
                            files = dir.GetFiles(fn, isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                        }
                    }
                    foreach (var item in files)
                    {
                        var metaref = MetadataReference.CreateFromFile(item.FullName);
                        project = project.AddMetadataReference(metaref);
                        metadata.Add(metaref);
                    }
                }
            }

            //Ensure mscorlib is referenced
            string mscorlib = typeof(System.Enum).Assembly.Location;

            if (File.Exists(mscorlib))
            {
                project = project.WithParseOptions(new Microsoft.CodeAnalysis.CSharp.CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest, DocumentationMode.Parse, SourceCodeKind.Regular, preprocessors));
                var metaref = MetadataReference.CreateFromFile(mscorlib);
                project = project.AddMetadataReference(metaref);
            }

            var comp = await project.GetCompilationAsync().ConfigureAwait(false);

            return(comp, metadata);
        }
Exemplo n.º 36
0
    public static ProjectInfo CreateProjectInfo(string language, string assemblyName, bool includeStuntApi = true, bool includeMockApi = false)
    {
        var suffix  = language == LanguageNames.CSharp ? "CS" : "VB";
        var options = language == LanguageNames.CSharp ?
                      (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default) :
                      (CompilationOptions) new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optionStrict: OptionStrict.On, assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);
        var parse = language == LanguageNames.CSharp ?
                    (ParseOptions) new CSharpParseOptions(Microsoft.CodeAnalysis.CSharp.LanguageVersion.Latest) :
                    (ParseOptions) new VisualBasicParseOptions(Microsoft.CodeAnalysis.VisualBasic.LanguageVersion.Latest);

        //The location of the .NET assemblies
        var frameworkPath   = Path.GetDirectoryName(typeof(object).Assembly.Location);
        var netstandardPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), @".nuget\packages\NETStandard.Library\2.0.0\build\netstandard2.0\ref");

        if (!Directory.Exists(netstandardPath))
        {
            netstandardPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"dotnet\sdk\NuGetFallbackFolder\netstandard.library\2.0.0\build\netstandard2.0\ref");
        }
        if (!Directory.Exists(netstandardPath))
        {
            netstandardPath = @"C:\Program Files\dotnet\sdk\NuGetFallbackFolder\netstandard.library\2.0.0\build\netstandard2.0\ref";
        }

        if (!Directory.Exists(netstandardPath))
        {
            throw new InvalidOperationException("Failed to find location of .NETStandard 2.0 reference assemblies");
        }

        var referencePaths =
            //new[]
            //{
            //    typeof(object).Assembly.Location,
            //    typeof(Enumerable).Assembly.Location,
            //    typeof(CSharpCompilation).Assembly.Location,
            //    typeof(Compilation).Assembly.Location,
            //}
            Directory.EnumerateFiles(netstandardPath, "*.dll")
            .Concat(ReferencePaths.Paths)
            //ReferencePaths.Paths
            //.Concat(Directory.EnumerateFiles(netstandardPath, "*.dll"))
            .Where(path => !string.IsNullOrEmpty(path) && File.Exists(path))
            .Distinct(FileNameEqualityComparer.Default);

        var projectId = ProjectId.CreateNewId();
        var documents = new List <DocumentInfo>();

        if (includeStuntApi)
        {
            var stuntApi = language == LanguageNames.CSharp ?
                           new FileInfo(@"contentFiles\cs\netstandard1.3\Stunt.cs").FullName :
                           new FileInfo(@"contentFiles\vb\netstandard1.3\Stunt.vb").FullName;

            Assert.True(File.Exists(stuntApi));
            documents.Add(DocumentInfo.Create(
                              DocumentId.CreateNewId(projectId, Path.GetFileName(stuntApi)),
                              Path.GetFileName(stuntApi),
                              loader: new FileTextLoader(stuntApi, Encoding.Default),
                              filePath: stuntApi));
        }

        if (includeMockApi)
        {
            var mockApi = language == LanguageNames.CSharp ?
                          new FileInfo(@"contentFiles\cs\netstandard2.0\Mock.cs").FullName :
                          new FileInfo(@"contentFiles\vb\netstandard2.0\Mock.vb").FullName;
            var mockApiOverloads = Path.ChangeExtension(mockApi, ".Overloads") + Path.GetExtension(mockApi);

            Assert.True(File.Exists(mockApi));

            documents.Add(DocumentInfo.Create(
                              DocumentId.CreateNewId(projectId, Path.GetFileName(mockApi)),
                              Path.GetFileName(mockApi),
                              loader: new FileTextLoader(mockApi, Encoding.Default),
                              filePath: mockApi));
            documents.Add(DocumentInfo.Create(
                              DocumentId.CreateNewId(projectId, Path.GetFileName(mockApiOverloads)),
                              Path.GetFileName(mockApiOverloads),
                              loader: new FileTextLoader(mockApiOverloads, Encoding.Default),
                              filePath: mockApiOverloads));
        }

        var projectDir = Path.Combine(Path.GetTempPath(), "Mock", projectId.Id.ToString());

        return(ProjectInfo.Create(
                   projectId,
                   VersionStamp.Create(),
                   assemblyName + "." + suffix,
                   assemblyName + "." + suffix,
                   language,
                   filePath: language == LanguageNames.CSharp
                ? Path.Combine(projectDir, "code.csproj")
                : Path.Combine(projectDir, "code.vbproj"),
                   compilationOptions: options,
                   parseOptions: parse,
                   metadataReferences: referencePaths
                   .Select(path => MetadataReference.CreateFromFile(path)),
                   documents: documents.ToArray()));
    }
 public static void AssertNoAnalysisResultsExist(ProjectInfo projectInfo)
 {
     Assert.IsTrue(projectInfo.AnalysisResults == null || projectInfo.AnalysisResults.Count == 0,
                   "Not expecting analysis results to exist. Count: {0}", projectInfo.AnalysisResults.Count);
 }
Exemplo n.º 38
0
        protected void MoveProjectData(string projectNumber)
        {
            var infomodel = new ProjectInfo();

            infomodel = this.IDKLManagerService.GetProjectInfo(projectNumber);
            if (infomodel != null)
            {
                ProjectInfoHistory history = ProjectInfoHistory.Clone(infomodel);
                history.ProjectRealClosingDate = DateTime.Now;
                this.IDKLManagerService.AddProjectInfoHistory(history);
            }
            this.IDKLManagerService.DeleteProjectInfo(projectNumber);

            var valueInfo = new ValueBasicInfo();

            valueInfo = this.IDKLManagerService.GetVlaueProjectBasicInfo(projectNumber);
            if (valueInfo != null)
            {
                ValueBasicInfoHistory history = ValueBasicInfoHistory.Clone(valueInfo);
                this.IDKLManagerService.AddVlaueProjectBasicInfoHistory(history);
            }
            this.IDKLManagerService.DeleteVlaueProjectBasicInfo(projectNumber);
            var testChemical = new TestChemicalReport();

            testChemical = this.IDKLManagerService.GetTestTestChemicalReport(projectNumber);
            if (testChemical != null)
            {
                TestChemicalReportListHistory chemicalHistory = TestChemicalReportListHistory.Clone(testChemical);
                this.IDKLManagerService.AddTestChemicalReportListHistory(chemicalHistory);
            }
            this.IDKLManagerService.DeleteTestChemicalReport(projectNumber);
            var testInfo = new TestBasicInfo();

            testInfo = this.IDKLManagerService.GetProjectTestBasicInfo(projectNumber);
            if (testInfo != null)
            {
                TestBasicInfoHistory history = TestBasicInfoHistory.Clone(testInfo);
                this.IDKLManagerService.AddProjectTestBasicInfoHistory(history);
            }
            this.IDKLManagerService.DeleteProjectTestBasicInfo(projectNumber);

            var consultInfo = new ConsultBasicInfo();

            consultInfo = this.IDKLManagerService.GetConsultBasicInfo(projectNumber);
            if (consultInfo != null)
            {
                ConsultBasicInfoHistory history = ConsultBasicInfoHistory.Clone(consultInfo);
                this.IDKLManagerService.AddConsultBasicInfoHistory(history);
            }
            this.IDKLManagerService.DeleteConsultBasicInfo(projectNumber);

            var fileInfo = new ProjectFile();

            fileInfo = this.IDKLManagerService.GetProjectFile(projectNumber);
            if (fileInfo != null)
            {
                ProjectFileHistory history = ProjectFileHistory.Clone(fileInfo);
                this.IDKLManagerService.AddProjectFileHistory(history);
            }
            this.IDKLManagerService.DeleteProjectFile(projectNumber);

            var docList = this.IDKLManagerService.GetProjectDocFileList(projectNumber);
            ProjectDocFileHistory docHistory = new ProjectDocFileHistory();

            foreach (var doc in docList)
            {
                docHistory = ProjectDocFileHistory.Clone(doc);
                this.IDKLManagerService.AddProjectDocFileHistory(docHistory);
            }
            this.IDKLManagerService.DeleteProjectDocFile(projectNumber);
        }
Exemplo n.º 39
0
 /// <summary>
 /// Gets cached project wrapper.
 /// </summary>
 /// <param name="projectInfo">The project information. If null then gets active project.</param>
 /// <returns>Returns the project wrapper.</returns>
 /// <exception cref="System.InvalidOperationException"/>
 private BaseProjectWrapper GetProjectWrapper(ProjectInfo projectInfo)
 {
     return(GetProjectWrapperByName(projectInfo != null ? projectInfo.Name : null));
 }
 private static bool HasInvalidGuid(ProjectInfo project)
 {
     return(project.ProjectGuid == Guid.Empty);
 }
        private void AddCppFileTreeViewItem(ProjectInfo projectInfo, TreeViewItem parentTreeViewItem, SolutionHierarchy.Item item)
        {
            const string kExcludeFromUnityBuild = "Exclude from Unity Build";
            const string kIncludeInUnityBuild   = "Include in Unity Build";

            string cppFileName = item.Name;

            var treeViewItem = new TreeViewItem()
            {
                FontWeight = FontWeights.Normal
            };

            treeViewItem.DataContext = item;
            treeViewItem.ContextMenu = new ContextMenu();

            var checkBox = new CheckBox()
            {
                IsChecked         = !_solutionSettings.IsExcludedCppFileNameForProject(projectInfo, cppFileName),
                VerticalAlignment = VerticalAlignment.Center
            };

            var contextMenuItemExclude = new MenuItem()
            {
                Header = checkBox.IsChecked.Value ? kExcludeFromUnityBuild : kIncludeInUnityBuild,
            };

            contextMenuItemExclude.Click += (sender, eventArgs) =>
            {
                checkBox.IsChecked = !checkBox.IsChecked.Value;
            };
            treeViewItem.ContextMenu.Items.Add(contextMenuItemExclude);

            checkBox.Checked += (sender, eventArgs) =>
            {
                _solutionSettings.RemoveExcludedCppFileNameForProject(projectInfo, cppFileName);
                contextMenuItemExclude.Header = kExcludeFromUnityBuild;
            };
            checkBox.Unchecked += (sender, eventArgs) =>
            {
                _solutionSettings.ExcludeCppFileNameForProject(projectInfo, cppFileName);
                contextMenuItemExclude.Header = kIncludeInUnityBuild;
            };

            var image = new Image()
            {
                Source = _solutionHierarchy.GetIcon(SolutionHierarchy.IconType.CppFile)
            };
            var label = new Label()
            {
                Content = System.IO.Path.GetFileName(cppFileName)
            };

            var stack = new StackPanel()
            {
                Orientation = Orientation.Horizontal, Margin = new Thickness(0, -2, 0, -2)
            };

            stack.Children.Add(checkBox);
            stack.Children.Add(image);
            stack.Children.Add(label);
            treeViewItem.Header = stack;

            parentTreeViewItem.Items.Add(treeViewItem);
        }
Exemplo n.º 42
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Keep current user object
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Title element settings
        titleElem.TitleImage = GetImageUrl("Objects/PM_ProjectTask/object.png");
        titleElem.TitleText  = GetString("pm.projecttask.edit");

        #region "Header actions"

        if (CMSContext.CurrentUser.IsAuthenticated())
        {
            // New task link
            string[,] actions = new string[1, 7];
            actions[0, 0]     = HeaderActions.TYPE_LINKBUTTON;
            actions[0, 1]     = GetString("pm.projecttask.newpersonal");
            actions[0, 2]     = null;
            actions[0, 4]     = null;
            actions[0, 5]     = GetImageUrl("Objects/PM_Project/add.png");
            actions[0, 6]     = "new_task";

            HeaderActions.Actions          = actions;
            HeaderActions.ActionPerformed += new CommandEventHandler(actionsElem_ActionPerformed);
            HeaderActions.ReloadData();
        }
        #endregion

        // Switch by display type and set correct list grid name
        switch (this.TasksDisplayType)
        {
        // Project tasks
        case TasksDisplayTypeEnum.ProjectTasks:
            ucTaskList.OrderByType   = ProjectTaskOrderByEnum.NotSpecified;
            ucTaskList.Grid.OrderBy  = "TaskPriorityOrder ASC,ProjectTaskDeadline DESC";
            ucTaskList.Grid.GridName = "~/CMSModules/ProjectManagement/Controls/LiveControls/ProjectTasks.xml";
            pnlListActions.Visible   = false;
            break;

        // Tasks owned by me
        case TasksDisplayTypeEnum.TasksOwnedByMe:
            ucTaskList.OrderByType   = ProjectTaskOrderByEnum.NotSpecified;
            ucTaskList.Grid.OrderBy  = "TaskPriorityOrder ASC,ProjectTaskDeadline DESC";
            ucTaskList.Grid.GridName = "~/CMSModules/ProjectManagement/Controls/LiveControls/TasksOwnedByMe.xml";
            break;

        // Tasks assigned to me
        case TasksDisplayTypeEnum.TasksAssignedToMe:
            // Set not specified order by default
            ucTaskList.OrderByType = ProjectTaskOrderByEnum.NotSpecified;
            // If sitename is not defined => display task from all sites => use user order
            if (String.IsNullOrEmpty(this.SiteName))
            {
                ucTaskList.OrderByType = ProjectTaskOrderByEnum.UserOrder;
            }
            ucTaskList.Grid.OrderBy  = "TaskPriorityOrder ASC,ProjectTaskDeadline DESC";
            ucTaskList.Grid.GridName = "~/CMSModules/ProjectManagement/Controls/LiveControls/TasksAssignedToMe.xml";
            break;
        }

        #region "Force edit by TaskID in querystring"

        // Check whether is not postback
        if (!RequestHelper.IsPostBack())
        {
            // Try get value from request stroage which indicates whether force dialog is displayed
            bool isDisplayed = ValidationHelper.GetBoolean(RequestStockHelper.GetItem("cmspmforceitemdisplayed", true), false);

            // Try get task id from querystring
            int forceTaskId = QueryHelper.GetInteger("taskid", 0);
            if ((forceTaskId > 0) && (!isDisplayed))
            {
                ProjectTaskInfo pti = ProjectTaskInfoProvider.GetProjectTaskInfo(forceTaskId);
                ProjectInfo     pi  = ProjectInfoProvider.GetProjectInfo(pti.ProjectTaskProjectID);

                // Check whether task is defined
                // and if is assigned to some project, this project is assigned to current site
                if ((pti != null) && ((pi == null) || (pi.ProjectSiteID == CMSContext.CurrentSiteID)))
                {
                    bool taskIdValid = false;

                    // Switch by display type
                    switch (this.TasksDisplayType)
                    {
                    // Tasks created by me
                    case TasksDisplayTypeEnum.TasksOwnedByMe:
                        if (pti.ProjectTaskOwnerID == currentUser.UserID)
                        {
                            taskIdValid = true;
                        }
                        break;

                    // Tasks assigned to me
                    case TasksDisplayTypeEnum.TasksAssignedToMe:
                        if (pti.ProjectTaskAssignedToUserID == currentUser.UserID)
                        {
                            taskIdValid = true;
                        }
                        break;

                    // Project task
                    case TasksDisplayTypeEnum.ProjectTasks:
                        if (!String.IsNullOrEmpty(ProjectNames) && (pi != null))
                        {
                            string projectNames = ";" + ProjectNames.ToLower() + ";";
                            if (projectNames.Contains(";" + pi.ProjectName.ToLower() + ";"))
                            {
                                // Check whether user can see private task
                                if (!pti.ProjectTaskIsPrivate ||
                                    ((pti.ProjectTaskOwnerID == currentUser.UserID) || (pti.ProjectTaskAssignedToUserID == currentUser.UserID)) ||
                                    ((pi.ProjectGroupID > 0) && currentUser.IsGroupAdministrator(pi.ProjectGroupID)) ||
                                    ((pi.ProjectGroupID == 0) && (currentUser.IsAuthorizedPerResource("CMS.ProjectManagement", CMSAdminControl.PERMISSION_MANAGE))))
                                {
                                    taskIdValid = true;
                                }
                            }
                        }
                        break;
                    }

                    bool displayValid = true;

                    // Check whether do not display finished tasks is required
                    if (!this.ShowFinishedTasks)
                    {
                        ProjectTaskStatusInfo ptsi = ProjectTaskStatusInfoProvider.GetProjectTaskStatusInfo(pti.ProjectTaskStatusID);
                        if ((ptsi != null) && (ptsi.TaskStatusIsFinished))
                        {
                            displayValid = false;
                        }
                    }

                    // Check whether private task should be edited
                    if (!this.ShowPrivateTasks)
                    {
                        if (pti.ProjectTaskProjectID == 0)
                        {
                            displayValid = false;
                        }
                    }

                    // Check whether ontime task should be edited
                    if (!this.ShowOnTimeTasks)
                    {
                        if ((pti.ProjectTaskDeadline != DateTimeHelper.ZERO_TIME) && (pti.ProjectTaskDeadline < DateTime.Now))
                        {
                            displayValid = false;
                        }
                    }

                    // Check whether overdue task should be edited
                    if (!this.ShowOverdueTasks)
                    {
                        if ((pti.ProjectTaskDeadline != DateTimeHelper.ZERO_TIME) && (pti.ProjectTaskDeadline > DateTime.Now))
                        {
                            displayValid = false;
                        }
                    }

                    // Check whether user is allowed to see project
                    if ((pi != null) && (ProjectInfoProvider.IsAuthorizedPerProject(pi.ProjectID, ProjectManagementPermissionType.READ, CMSContext.CurrentUser)))
                    {
                        displayValid = false;
                    }

                    // If task is valid and user has permissions to see this task display edit task dialog
                    if (displayValid && taskIdValid && ProjectTaskInfoProvider.IsAuthorizedPerTask(forceTaskId, ProjectManagementPermissionType.READ, CMSContext.CurrentUser, CMSContext.CurrentSiteID))
                    {
                        this.ucTaskEdit.ItemID = forceTaskId;
                        this.ucTaskEdit.ReloadData();
                        // Render dialog
                        this.ucPopupDialog.Visible = true;
                        this.ucPopupDialog.Show();
                        // Set "force dialog displayed" flag
                        RequestStockHelper.Add("cmspmforceitemdisplayed", true, true);
                    }
                }
            }
        }

        #endregion


        #region "Event handlers registration"

        // Register list action handler
        ucTaskList.OnAction += new CommandEventHandler(ucTaskList_OnAction);

        #endregion


        #region "Pager settings"

        // Paging
        if (!EnablePaging)
        {
            ucTaskList.Grid.PageSize = "##ALL##";
            ucTaskList.Grid.Pager.DefaultPageSize = -1;
        }
        else
        {
            ucTaskList.Grid.Pager.DefaultPageSize = PageSize;
            ucTaskList.Grid.PageSize    = this.PageSize.ToString();
            ucTaskList.Grid.FilterLimit = PageSize;
        }

        #endregion


        // Use postbacks on list actions
        ucTaskList.UsePostbackOnEdit = true;
        // Check delete permission
        ucTaskList.OnCheckPermissionsExtended += new CheckPermissionsExtendedEventHandler(ucTaskList_OnCheckPermissionsExtended);
        // Dont register JS edit script
        ucTaskList.RegisterEditScript = false;

        // Hide default ok button on edit
        ucTaskEdit.ShowOKButton = false;
        // Disable on site validators
        ucTaskEdit.DisableOnSiteValidators = true;
        // Check modify permission
        ucTaskEdit.OnCheckPermissionsExtended += new CheckPermissionsExtendedEventHandler(ucTaskEdit_OnCheckPermissionsExtended);
        // Build condition event
        ucTaskList.BuildCondition += new CMSModules_ProjectManagement_Controls_UI_ProjectTask_List.BuildConditionEvent(ucTaskList_BuildCondition);
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        gridMatrix.OnItemChanged += new UniMatrix.ItemChangedEventHandler(gridMatrix_OnItemChanged);
        gridMatrix.StopProcessing = true;
        gridMatrix.ColumnsPreferedOrder = string.Join(",", allowedPermissions);

        if (ProjectID > 0)
        {
            project = ProjectInfoProvider.GetProjectInfo(ProjectID);

            // Check whether the project still exists
            EditedObject = project;
        }

        // Handle page chnaged event
        gridMatrix.OnPageChanged += new EventHandler<EventArgs>(gridMatrix_OnPageChanged);

        // Disable permission matrix if user has no MANAGE rights
        if (!ProjectInfoProvider.IsAuthorizedPerProject(ProjectID, PERMISSION_MANAGE, CMSContext.CurrentUser))
        {
            Enable = false;
            gridMatrix.Enabled = false;
            lblError.Text = String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), "Manage");
            lblError.Visible = true;
        }
    }
Exemplo n.º 44
0
 public void Add(ProjectInfo info)
 {
     _projectIdToProjectInfoMap.Add(info.Id, info);
     //Memoized results of ProjectAlreadyReferencesProject may no longer be correct;
     //reset the cache.
     _projectAlreadyReferencesProjectResultCache.Clear();
 }
    /// <summary>
    /// Generates the permission matrix for the cutrrent project.
    /// </summary>
    private void CreateMatrix()
    {
        // Get project resource info
        if (mResProjects == null)
        {
            mResProjects = ResourceInfoProvider.GetResourceInfo("CMS.ProjectManagement");
        }

        // Get project object
        if ((mProject == null) && (ProjectID > 0))
        {
            mProject = ProjectInfoProvider.GetProjectInfo(ProjectID);
        }

        if ((mResProjects != null) && (mProject != null))
        {
            // Get permissions for the current project resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(mResProjects.ResourceId);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                lblInfo.Text = GetString("general.emptymatrix");
                lblInfo.Visible = true;
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.TableSection = TableRowSection.TableHeader;
                headerRow.CssClass = "unigrid-head";

                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.CssClass = "first-column";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in mAllowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if (drArray.Length > 0)
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell = new TableHeaderCell();
                        newHeaderCell.Text = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip = dr["PermissionDescription"].ToString();
                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }

                tblMatrix.Rows.Add(headerRow);

                // Render project access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0] = GetString("security.nobody");
                accessNames[0, 1] = SecurityAccessEnum.Nobody;
                accessNames[1, 0] = GetString("security.allusers");
                accessNames[1, 1] = SecurityAccessEnum.AllUsers;
                accessNames[2, 0] = GetString("security.authenticated");
                accessNames[2, 1] = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0] = GetString("security.groupmembers");
                accessNames[3, 1] = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0] = GetString("security.authorizedroles");
                accessNames[4, 1] = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow;
                int rowIndex = 0;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // If the security isn't displayed as part of group section
                    if ((currentAccess == SecurityAccessEnum.GroupMembers) && (mProject.ProjectGroupID == 0))
                    {
                        // Do not render this access item
                    }
                    else
                    {
                        // Generate cell holding access item name
                        newRow = new TableRow();
                        TableCell newCell = new TableCell();
                        newCell.Text = accessNames[access, 0].ToString();
                        newCell.CssClass = "matrix-header";
                        newRow.Cells.Add(newCell);
                        rowIndex++;

                        // Render the permissions access items
                        int permissionIndex = 0;
                        for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 1); permission++)
                        {
                            newCell = new TableCell();

                            // Check if the currently processed access is applied for permission
                            bool isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                            // Disable column in roles grid if needed
                            if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                            {
                                gridMatrix.DisableColumn(permissionIndex);
                            }

                            // Insert the radio button for the current permission
                            var radio = new CMSRadioButton
                            {
                                Checked = isAllowed,
                                Enabled = Enable,
                            };
                            radio.Attributes.Add("onclick", ControlsHelper.GetPostBackEventReference(this, permission + ";" + Convert.ToInt32(currentAccess)));
                            newCell.Controls.Add(radio);

                            newRow.Cells.Add(newCell);
                            permissionIndex++;
                        }

                        // Add the access row to the table
                        tblMatrix.Rows.Add(newRow);
                    }
                }

                // Check if project has some roles assigned
                headTitle.Visible = gridMatrix.HasData;
            }
        }
    }
Exemplo n.º 46
0
        public VisualStudioProject CreateAndAddToWorkspace(string projectSystemName, string language, VisualStudioProjectCreationInfo creationInfo)
        {
            // HACK: Fetch this service to ensure it's still created on the UI thread; once this is moved off we'll need to fix up it's constructor to be free-threaded.
            _visualStudioWorkspaceImpl.Services.GetRequiredService <VisualStudioMetadataReferenceManager>();

            // HACK: since we're on the UI thread, ensure we initialize our options provider which depends on a UI-affinitized experimentation service
            _visualStudioWorkspaceImpl.EnsureDocumentOptionProvidersInitialized();

            var id = ProjectId.CreateNewId(projectSystemName);
            var directoryNameOpt = creationInfo.FilePath != null?Path.GetDirectoryName(creationInfo.FilePath) : null;

            // We will use the project system name as the default display name of the project
            var project = new VisualStudioProject(_visualStudioWorkspaceImpl, _dynamicFileInfoProviders, _hostDiagnosticUpdateSource, id, displayName: projectSystemName, language, directoryNameOpt);

            var versionStamp = creationInfo.FilePath != null?VersionStamp.Create(File.GetLastWriteTimeUtc(creationInfo.FilePath))
                                   : VersionStamp.Create();

            var assemblyName = creationInfo.AssemblyName ?? projectSystemName;

            _visualStudioWorkspaceImpl.AddProjectToInternalMaps(project, creationInfo.Hierarchy, creationInfo.ProjectGuid, projectSystemName);

            _visualStudioWorkspaceImpl.ApplyChangeToWorkspace(w =>
            {
                var projectInfo = ProjectInfo.Create(
                    id,
                    versionStamp,
                    name: projectSystemName,
                    assemblyName: assemblyName,
                    language: language,
                    filePath: creationInfo.FilePath,
                    compilationOptions: creationInfo.CompilationOptions,
                    parseOptions: creationInfo.ParseOptions);

                // If we don't have any projects and this is our first project being added, then we'll create a new SolutionId
                if (w.CurrentSolution.ProjectIds.Count == 0)
                {
                    // Fetch the current solution path. Since we're on the UI thread right now, we can do that.
                    string solutionFilePath = null;
                    var solution            = (IVsSolution)Shell.ServiceProvider.GlobalProvider.GetService(typeof(SVsSolution));
                    if (solution != null)
                    {
                        if (ErrorHandler.Failed(solution.GetSolutionInfo(out _, out solutionFilePath, out _)))
                        {
                            // Paranoia: if the call failed, we definitely don't want to use any stuff that was set
                            solutionFilePath = null;
                        }
                    }

                    w.OnSolutionAdded(
                        SolutionInfo.Create(
                            SolutionId.CreateNewId(solutionFilePath),
                            VersionStamp.Create(),
                            solutionFilePath,
                            projects: new[] { projectInfo }));
                }
                else
                {
                    w.OnProjectAdded(projectInfo);
                }

                _visualStudioWorkspaceImpl.RefreshProjectExistsUIContextForLanguage(language);
            });

            // We do all these sets after the w.OnProjectAdded, as the setting of these properties is going to try to modify the workspace
            // again. Those modifications will all implicitly do nothing, since the workspace already has the values from above.
            // We could pass these all through the constructor (but that gets verbose), or have some other control to ignore these,
            // but that seems like overkill.
            project.AssemblyName       = assemblyName;
            project.CompilationOptions = creationInfo.CompilationOptions;
            project.FilePath           = creationInfo.FilePath;
            project.ParseOptions       = creationInfo.ParseOptions;

            return(project);
        }
Exemplo n.º 47
0
 private JumpTask CreateProjectJumpItem(ProjectInfo pInfo)
 {
     JumpTask goToProject = new JumpTask();
     goToProject.CustomCategory = ScrumFactory.Windows.Properties.Resources.Recent_projects;
     goToProject.Title = pInfo.ProjectName + " - " + pInfo.ClientName + " [" + pInfo.ProjectNumber + "]";
     goToProject.Description = String.Format(ScrumFactory.Windows.Properties.Resources.Go_to_project_N, pInfo.ProjectNumber);
     goToProject.ApplicationPath = Assembly.GetEntryAssembly().Location;
     goToProject.IconResourcePath = goToProject.ApplicationPath;
     goToProject.Arguments = "projectNumber=" + pInfo.ProjectNumber;
     return goToProject;
 }
Exemplo n.º 48
0
 public MyTfsProject(ProjectInfo projectInfo, IBuildServer buildServer, MyTfsProjectCollection projectCollection)
 {
     _projectInfo       = projectInfo;
     _buildServer       = buildServer;
     _projectCollection = projectCollection;
 }
        /// <summary>
        /// Creates COBIESpaceClassifications.
        /// </summary>
        /// <param name="exporterIFC">The ExporterIFC.</param>
        /// <param name="file">The file.</param>
        /// <param name="spaceHnd">The space handle.</param>
        /// <param name="projectInfo">The project info.</param>
        /// <param name="spatialElement">The spatial element.</param>
        private static void CreateCOBIESpaceClassifications(ExporterIFC exporterIFC, IFCFile file, IFCAnyHandle spaceHnd,
            ProjectInfo projectInfo, SpatialElement spatialElement)
        {
            HashSet<IFCAnyHandle> spaceHnds = new HashSet<IFCAnyHandle>();
            spaceHnds.Add(spaceHnd);

            string bimStandardsLocation = null;
            if (projectInfo != null)
                ParameterUtil.GetStringValueFromElement(projectInfo.Id, "BIM Standards URL", out bimStandardsLocation);

            // OCCS - Space by Function.
            string itemReference = "";
            if (ParameterUtil.GetStringValueFromElement(spatialElement.Id, "OmniClass Number", out itemReference) != null)
            {
                string itemName;
                ParameterUtil.GetStringValueFromElement(spatialElement.Id, "OmniClass Title", out itemName);

                IFCAnyHandle classification;
                if (!ExporterCacheManager.ClassificationCache.ClassificationHandles.TryGetValue("OmniClass", out classification))
                {
                    classification = IFCInstanceExporter.CreateClassification(file, "http://www.omniclass.org", "v 1.0", null, "OmniClass");
                    ExporterCacheManager.ClassificationCache.ClassificationHandles.Add("OmniClass", classification);
                }

                IFCAnyHandle classificationReference = IFCInstanceExporter.CreateClassificationReference(file,
                  "http://www.omniclass.org/tables/OmniClass_13_2006-03-28.pdf", itemReference, itemName, classification);
                IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(),
                   ExporterCacheManager.OwnerHistoryHandle, "OmniClass", null, spaceHnds, classificationReference);
            }

            // Space Type (Owner)
            itemReference = "";
            if (ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Type (Owner) Reference", out itemReference) != null)
            {
                string itemName;
                ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Type (Owner) Name", out itemName);

                IFCAnyHandle classificationReference = IFCInstanceExporter.CreateClassificationReference(file,
                  bimStandardsLocation, itemReference, itemName, null);
                IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(),
                   ExporterCacheManager.OwnerHistoryHandle, "Space Type (Owner)", null, spaceHnds, classificationReference);
            }

            // Space Category (Owner)
            itemReference = "";
            if (ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Category (Owner) Reference", out itemReference) != null)
            {
                string itemName;
                ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Category (Owner) Name", out itemName);

                IFCAnyHandle classificationReference = IFCInstanceExporter.CreateClassificationReference(file,
                  bimStandardsLocation, itemReference, itemName, null);
                IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(),
                   ExporterCacheManager.OwnerHistoryHandle, "Space Category (Owner)", null, spaceHnds, classificationReference);
            }

            // Space Category (BOMA)
            itemReference = "";
            if (ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Category (BOMA) Reference", out itemReference) != null)
            {
                string itemName;
                ParameterUtil.GetStringValueFromElement(spatialElement.Id, "Space Category (BOMA) Name", out itemName);

                IFCAnyHandle classificationReference = IFCInstanceExporter.CreateClassificationReference(file,
                  "http://www.BOMA.org", itemReference, itemName, null);
                IFCAnyHandle relAssociates = IFCInstanceExporter.CreateRelAssociatesClassification(file, GUIDUtil.CreateGUID(),
                   ExporterCacheManager.OwnerHistoryHandle, "Space Category (BOMA)", "", spaceHnds, classificationReference);
            }
        }
Exemplo n.º 50
0
        public override void Start(int delay, int left, int top, int width, int height, double scale, ProjectInfo project)
        {
            base.Start(delay, left, top, width, height, scale, project);

            _infoHeader                = new Native.BitmapInfoHeader();
            _infoHeader.biSize         = (uint)Marshal.SizeOf(_infoHeader);
            _infoHeader.biBitCount     = 24; //Without alpha channel.
            _infoHeader.biClrUsed      = 0;
            _infoHeader.biClrImportant = 0;
            _infoHeader.biCompression  = 0;
            _infoHeader.biHeight       = -StartHeight; //Negative, so the Y-axis will be positioned correctly.
            _infoHeader.biWidth        = StartWidth;
            _infoHeader.biPlanes       = 1;

            //This was working with 32 bits: 3L * Width * Height;
            _byteLength = (StartWidth * _infoHeader.biBitCount + 31) / 32 * 4 * StartHeight;

            //Due to a strange behavior with the GetDiBits method while the cursor is IBeam, it's best to use 24 bits, to ignore the alpha values.
            //This capture mode ignores the alpha value.
            project.BitDepth = 24;

            _fileStream     = new FileStream(project.CachePath, FileMode.Create, FileAccess.Write, FileShare.None);
            _bufferedStream = new BufferedStream(_fileStream, UserSettings.All.MemoryCacheSize * 1048576); //Each 1 MB has 1_048_576 bytes.
            _compressStream = new DeflateStream(_bufferedStream, UserSettings.All.CaptureCompression, true);
        }
Exemplo n.º 51
0
        /// <summary>
        /// Creates the IfcPostalAddress, and assigns it to the file.
        /// </summary>
        /// <param name="file">The IFC file.</param>
        /// <param name="address">The address string.</param>
        /// <param name="town">The town string.</param>
        /// <returns>The handle of IFC file.</returns>
        private IFCAnyHandle CreateIFCAddress(IFCFile file, Document document, ProjectInfo projInfo)
        {
            IFCAnyHandle postalAddress = null;
            postalAddress = CreateIFCAddressFromExtStorage(file, document);
            if (postalAddress != null)
                return postalAddress;

            string projectAddress = projInfo != null ? projInfo.Address : String.Empty;
            SiteLocation siteLoc = document.ActiveProjectLocation.SiteLocation;
            string location = siteLoc != null ? siteLoc.PlaceName : String.Empty;

            if (projectAddress == null)
                projectAddress = String.Empty;
            if (location == null)
                location = String.Empty;

            List<string> parsedAddress = new List<string>();
            string city = String.Empty;
            string state = String.Empty;
            string postCode = String.Empty;
            string country = String.Empty;

            string parsedTown = location;
            int commaLoc = -1;
            do
            {
                commaLoc = parsedTown.IndexOf(',');
                if (commaLoc >= 0)
                {
                    if (commaLoc > 0)
                        parsedAddress.Add(parsedTown.Substring(0, commaLoc));
                    parsedTown = parsedTown.Substring(commaLoc + 1).TrimStart(' ');
                }
                else if (!String.IsNullOrEmpty(parsedTown))
                    parsedAddress.Add(parsedTown);
            } while (commaLoc >= 0);

            int numLines = parsedAddress.Count;
            if (numLines > 0)
            {
                country = parsedAddress[numLines - 1];
                numLines--;
            }

            if (numLines > 0)
            {
                int spaceLoc = parsedAddress[numLines - 1].IndexOf(' ');
                if (spaceLoc > 0)
                {
                    state = parsedAddress[numLines - 1].Substring(0, spaceLoc);
                    postCode = parsedAddress[numLines - 1].Substring(spaceLoc + 1);
                }
                else
                    state = parsedAddress[numLines - 1];
                numLines--;
            }

            if (numLines > 0)
            {
                city = parsedAddress[numLines - 1];
                numLines--;
            }

            List<string> addressLines = new List<string>();
            if (!String.IsNullOrEmpty(projectAddress))
                addressLines.Add(projectAddress);

            for (int ii = 0; ii < numLines; ii++)
            {
                addressLines.Add(parsedAddress[ii]);
            }

            postalAddress = IFCInstanceExporter.CreatePostalAddress(file, null, null, null,
               null, addressLines, null, city, state, postCode, country);

            return postalAddress;
        }
Exemplo n.º 52
0
        public static async Task GenerateAndVerifyMocksUsingEmbeddedResources(
            Type fixtureType,
            string testName,
            Language language,
            IEnumerable <MetadataReference> metadataReferences = default,
            IPlugin[] plugins = default,
            // Should only be enabled temporarily to overwrite expected output with the actual output, making it easy to update
            // expected output files when code changes necessitate.
            bool overwriteExpectedOutput = false)
        {
            var resourceBaseName   = $"{fixtureType.FullName}Resources.";
            var inputResourceName  = $"{resourceBaseName}{testName}Input_{language}.txt";
            var outputResourceName = $"{resourceBaseName}{testName}Output_{language}.txt";
            var platformPath       = Path.GetDirectoryName(typeof(object).Assembly.Location);

            // Manually add some references that are always required.
            var supplementedMetadataReferences = (metadataReferences ?? Enumerable.Empty <MetadataReference>())
                                                 .Concat(
                new[]
            {
                MetadataReference.CreateFromFile(Path.Combine(platformPath, "System.Runtime.dll")),
                MetadataReference.CreateFromFile(typeof(System.Linq.Expressions.Expression).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(MockBase <>).Assembly.Location),
            });

            using (var inputStream = typeof(Helpers).Assembly.GetManifestResourceStream(inputResourceName))
            {
                var projectInfo = ProjectInfo.Create(
                    ProjectId.CreateNewId(),
                    VersionStamp.Create(),
                    "AdhocProject",
                    "AdhocProject",
                    language.ToSyntaxGeneratorLanguageName(),
                    compilationOptions: language == Language.CSharp
                        ? (CompilationOptions) new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                        : new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                    metadataReferences: supplementedMetadataReferences);

                // Create an adhoc workspace and project containing the input source.
                var workspace = new AdhocWorkspace();
                var project   = workspace
                                .AddProject(projectInfo)
                                .AddDocument("Source.cs", SourceText.From(inputStream))
                                .Project;
                var compilation = await project.GetCompilationAsync();

                var diagnostics = compilation.GetDiagnostics();

                // Ensure there are no issues with the input project, otherwise it might be confusing to understand issues with the generated mocks.
                Assert.Empty(diagnostics);

                var logSink = new StringLogSink()
                              .WithMinimumLevel(LogLevel.Warn);
                var generatedMocks = Generator.GenerateMocks(
                    logSink,
                    language,
                    ImmutableList.Create(compilation),
                    (plugins ?? Enumerable.Empty <IPlugin>()).ToImmutableList(),
                    x => true,
                    x => "The.Namespace",
                    x => $"{x.Name}Mock");

                var log = logSink.ToString();
                // There shouldn't be any errors or warnings in the log or something has gone wrong generating mocks.
                Assert.Equal("", log);

                var generatedMocksAggregated = generatedMocks
                                               .Aggregate(
                    new StringBuilder(),
                    (acc, next) =>
                {
                    if (next != null)
                    {
                        acc.AppendLine(next.ToFullString());
                    }

                    return(acc);
                },
                    acc => acc.ToString())
                                               .NormalizeLineEndings();

                using (var outputStream = typeof(Helpers).Assembly.GetManifestResourceStream(outputResourceName))
                    using (var outputStreamReader = new StreamReader(outputStream))
                    {
                        var expectedCode = outputStreamReader.ReadToEnd();

                        // make sure version changes don't break the tests
                        expectedCode = expectedCode
                                       .Replace("$VERSION$", typeof(MockBase <>).Assembly.GetName().Version.ToString())
                                       .NormalizeLineEndings();

                        // useful when converting generated code to something that can be pasted into an expectation file
                        var sanitisedResult = generatedMocksAggregated.Replace(typeof(MockBase <>).Assembly.GetName().Version.ToString(), "$VERSION$");

                        if (overwriteExpectedOutput)
                        {
                            var currentDirectory = Path.GetDirectoryName(typeof(Helpers).Assembly.Location);
                            var outputDirectory  = Path.Combine(currentDirectory, @"..\..\..\", "CodeGeneration", "Plugins", $"{fixtureType.Name}Resources");
                            var outputFileName   = Path.Combine(outputDirectory, $"{testName}Output_{language}.txt");

                            if (!File.Exists(outputFileName))
                            {
                                throw new InvalidOperationException(@"Asked to overwrite output, but cannot determine output path.");
                            }

                            File.WriteAllText(outputFileName, sanitisedResult);

                            Assert.True(false, "Output successfully overwritten - now disable the overwriteExpectedOutput flag.");
                        }

                        Assert.Equal(expectedCode, generatedMocksAggregated);
                    }

                // Now combine the original code with the generated code and make sure there are no problems.
                var workspaceWithGeneratedCode = new AdhocWorkspace();
                var projectWithGeneratedCode   = workspaceWithGeneratedCode
                                                 .AddProject(projectInfo)
                                                 .AddDocument("Source.cs", SourceText.From(inputStream))
                                                 .Project
                                                 .AddDocument("GeneratedSource.cs", SourceText.From(generatedMocksAggregated))
                                                 .Project;
                var compilationWithGeneratedCode = await projectWithGeneratedCode.GetCompilationAsync();

                var diagnosticsToIgnore = new HashSet <string>(
                    new []
                {
                    // Don't require assembly identities to match exactly because PCLMock is built against netstandard whereas we're running
                    // tests against a specific platform. This means, e.g. System.Linq.Expressions won't be the exact same assembly.
                    "CS1701",
                });
                var diagnosticsWithGeneratedCode = compilationWithGeneratedCode
                                                   .GetDiagnostics()
                                                   .Where(diagnostic => !diagnosticsToIgnore.Contains(diagnostic.Id))
                                                   .ToImmutableArray();

                // Ensure there are no issues with the input project, otherwise it might be confusing to understand issues with the generated mocks.
                Assert.Empty(diagnostics);
            }
        }
Exemplo n.º 53
0
            private async Task <bool> TryLoadAndAddReferenceAsync(ProjectId id, string projectReferencePath, ImmutableArray <string> aliases, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
            {
                var projectReferenceInfos = await LoadProjectInfosFromPathAsync(projectReferencePath, _discoveredProjectOptions, cancellationToken).ConfigureAwait(false);

                if (projectReferenceInfos.IsEmpty)
                {
                    return(false);
                }

                // Find the project reference info whose output we have a metadata reference for.
                ProjectInfo projectReferenceInfo = null;

                foreach (var info in projectReferenceInfos)
                {
                    if (builder.Contains(info.OutputFilePath) ||
                        builder.Contains(info.OutputRefFilePath))
                    {
                        projectReferenceInfo = info;
                        break;
                    }
                }

                if (projectReferenceInfo == null)
                {
                    // We didn't find the project reference info that matches any of our metadata references.
                    // In this case, we'll go ahead and use the first project reference info that was found,
                    // but report a warning because this likely means that either a metadata reference path
                    // or a project output path is incorrect.

                    projectReferenceInfo = projectReferenceInfos[0];

                    _diagnosticReporter.Report(new ProjectDiagnostic(
                                                   WorkspaceDiagnosticKind.Warning,
                                                   string.Format(WorkspaceMSBuildResources.Found_project_reference_without_a_matching_metadata_reference_0, projectReferencePath),
                                                   id));
                }

                if (!ProjectReferenceExists(to: id, from: projectReferenceInfo))
                {
                    var newProjectReference = CreateProjectReference(from: id, to: projectReferenceInfo.Id, aliases);
                    builder.SwapMetadataReferenceForProjectReference(newProjectReference, projectReferenceInfo.OutputRefFilePath, projectReferenceInfo.OutputFilePath);
                }
                else
                {
                    // This project already has a reference on us. Don't introduce a circularity by referencing it.
                    // However, if the project's output doesn't exist on disk, we need to remove from our list of
                    // metadata references to avoid failures later. Essentially, the concern here is that the metadata
                    // reference is an UnresolvedMetadataReference, which will throw when we try to create a
                    // Compilation with it.

                    if (!File.Exists(projectReferenceInfo.OutputRefFilePath))
                    {
                        builder.Remove(projectReferenceInfo.OutputRefFilePath);
                    }

                    if (!File.Exists(projectReferenceInfo.OutputFilePath))
                    {
                        builder.Remove(projectReferenceInfo.OutputFilePath);
                    }
                }

                // Note that we return true even if we don't actually add a reference due to a circularity because,
                // in that case, we've still handled everything.
                return(true);
            }
Exemplo n.º 54
0
        /// <summary>
        /// Create a <see cref="Solution"/> for <paramref name="code"/>
        /// Each unique namespace in <paramref name="code"/> is added as a project.
        /// </summary>
        /// <param name="code">The code to create the solution from.</param>
        /// <param name="compilationOptions">The <see cref="CSharpCompilationOptions"/>.</param>
        /// <param name="metadataReferences">The metadata references.</param>
        /// <param name="languageVersion">The <see cref="LanguageVersion"/>.</param>
        /// <returns>A <see cref="Solution"/>.</returns>
        public static Solution CreateSolution(IEnumerable <string> code, CSharpCompilationOptions compilationOptions, IEnumerable <MetadataReference>?metadataReferences = null, LanguageVersion languageVersion = LanguageVersion.Latest)
        {
            var solutionInfo = SolutionInfo.Create(
                SolutionId.CreateNewId("Test.sln"),
                VersionStamp.Default,
                projects: GetProjectInfos());
            var solution = EmptySolution;

            foreach (var projectInfo in solutionInfo.Projects)
            {
                solution = solution.AddProject(projectInfo.WithProjectReferences(FindReferences(projectInfo)));
            }

            return(solution);

            IEnumerable <ProjectInfo> GetProjectInfos()
            {
                var byNamespace = new SortedDictionary <string, List <string> >();

                foreach (var document in code)
                {
                    var ns = CodeReader.Namespace(document);
                    if (byNamespace.TryGetValue(ns, out var doc))
                    {
                        doc.Add(document);
                    }
                    else
                    {
                        byNamespace[ns] = new List <string> {
                            document
                        };
                    }
                }

                var byProject = new SortedDictionary <string, List <KeyValuePair <string, List <string> > > >();

                foreach (var kvp in byNamespace)
                {
                    var last = byProject.Keys.LastOrDefault();
                    var ns   = kvp.Key;
                    if (last != null &&
                        ns.Contains(last))
                    {
                        byProject[last].Add(kvp);
                    }
                    else
                    {
                        byProject.Add(ns, new List <KeyValuePair <string, List <string> > > {
                            kvp
                        });
                    }
                }

                foreach (var kvp in byProject)
                {
                    var assemblyName = kvp.Key;
                    var projectId    = ProjectId.CreateNewId(assemblyName);
                    yield return(ProjectInfo.Create(
                                     projectId,
                                     VersionStamp.Default,
                                     assemblyName,
                                     assemblyName,
                                     LanguageNames.CSharp,
                                     compilationOptions: compilationOptions,
                                     metadataReferences: metadataReferences,
                                     documents: kvp.Value.SelectMany(x => x.Value)
                                     .Select(
                                         x =>
                    {
                        var documentName = CodeReader.FileName(x);
                        return DocumentInfo.Create(
                            DocumentId.CreateNewId(projectId, documentName),
                            documentName,
                            sourceCodeKind: SourceCodeKind.Regular,
                            loader: new StringLoader(x));
                    }))
                                 .WithParseOptions(CSharpParseOptions.Default.WithLanguageVersion(languageVersion)));
                }
            }

            IEnumerable <ProjectReference> FindReferences(ProjectInfo projectInfo)
            {
                var references = new List <ProjectReference>();

                foreach (var other in solutionInfo.Projects.Where(x => x.Id != projectInfo.Id))
                {
                    if (projectInfo.Documents.Any(x => x.TextLoader is StringLoader stringLoader &&
                                                  (stringLoader.Code.Contains($"using {other.Name};") ||
                                                   stringLoader.Code.Contains($"{other.Name}."))))
                    {
                        references.Add(new ProjectReference(other.Id));
                    }
                }

                return(references);
            }
        }
    /// <summary>
    /// Load data.
    /// </summary>
    public void LoadData()
    {
        process = true;
        if (!Visible || StopProcessing)
        {
            EnableViewState = false;
            process = false;
        }

        IsLiveSite = false;

        if (ProjectID > 0)
        {
            // Get information on current project
            project = ProjectInfoProvider.GetProjectInfo(ProjectID);
        }

        // Get project resource
        resProjects = ResourceInfoProvider.GetResourceInfo("CMS.ProjectManagement");

        if ((resProjects != null) && (project != null))
        {
            QueryDataParameters parameters = new QueryDataParameters();
            parameters.Add("@ID", resProjects.ResourceId);
            parameters.Add("@ProjectID", project.ProjectID);
            parameters.Add("@SiteID", CMSContext.CurrentSiteID);

            string where = "";
            int groupId = project.ProjectGroupID;

            // Build where condition
            if (groupId > 0)
            {
                where = "RoleGroupID=" + groupId.ToString() + " AND PermissionDisplayInMatrix = 0";
            }
            else
            {
                where = "RoleGroupID IS NULL AND PermissionDisplayInMatrix = 0";
            }

            // Setup matrix control
            gridMatrix.IsLiveSite = IsLiveSite;
            gridMatrix.QueryParameters = parameters;
            gridMatrix.WhereCondition = where;
            gridMatrix.ContentBefore = "<table class=\"PermissionMatrix\" cellspacing=\"0\" cellpadding=\"0\" rules=\"rows\" border=\"1\" style=\"border-collapse:collapse;\">";
            gridMatrix.ContentAfter = "</table>";
        }
    }
Exemplo n.º 56
0
 private bool ProjectReferenceExists(ProjectId to, ProjectInfo from)
 => from.ProjectReferences.Any(pr => pr.ProjectId == to);
    /// <summary>
    /// Generates the permission matrix for the cutrrent project.
    /// </summary>
    private void CreateMatrix()
    {
        // Get project resource info
        if (resProjects == null)
        {
            resProjects = ResourceInfoProvider.GetResourceInfo("CMS.ProjectManagement");
        }

        // Get project object
        if ((project == null) && (ProjectID > 0))
        {
            project = ProjectInfoProvider.GetProjectInfo(ProjectID);
        }

        if ((resProjects != null) && (project != null))
        {
            // Get permissions for the current project resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resProjects.ResourceId);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                lblInfo.Text = GetString("general.emptymatrix");
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.CssClass = "UniGridHead";
                TableCell newCell = new TableCell();
                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                newHeaderCell.Attributes["style"] = "width:200px;";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if ((drArray != null) && (drArray.Length > 0))
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell = new TableHeaderCell();
                        newHeaderCell.Attributes["style"] = "text-align:center;white-space:nowrap;";
                        newHeaderCell.Text = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip = dr["PermissionDescription"].ToString();
                        newHeaderCell.HorizontalAlign = HorizontalAlign.Center;
                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                newHeaderCell = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                headerRow.Cells.Add(newHeaderCell);

                tblMatrix.Rows.Add(headerRow);

                // Render project access permissions
                object[,] accessNames = new object[5,2];
                accessNames[0, 0] = GetString("security.nobody");
                accessNames[0, 1] = SecurityAccessEnum.Nobody;
                accessNames[1, 0] = GetString("security.allusers");
                accessNames[1, 1] = SecurityAccessEnum.AllUsers;
                accessNames[2, 0] = GetString("security.authenticated");
                accessNames[2, 1] = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0] = GetString("security.groupmembers");
                accessNames[3, 1] = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0] = GetString("security.authorizedroles");
                accessNames[4, 1] = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow = null;
                int rowIndex = 0;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // If the security isn't displayed as part of group section
                    if ((currentAccess == SecurityAccessEnum.GroupMembers) && (project.ProjectGroupID == 0))
                    {
                        // Do not render this access item
                    }
                    else
                    {
                        // Generate cell holding access item name
                        newRow = new TableRow();
                        newRow.CssClass = ((rowIndex % 2 == 0) ? "EvenRow" : "OddRow");
                        newCell = new TableCell();
                        newCell.Text = accessNames[access, 0].ToString();
                        newCell.Wrap = false;
                        newCell.CssClass = "MatrixHeader";
                        newCell.Width = new Unit(28, UnitType.Percentage);
                        newRow.Cells.Add(newCell);
                        rowIndex++;

                        // Render the permissions access items
                        bool isAllowed = false;
                        bool isDisabled = (!Enable);
                        int permissionIndex = 0;
                        for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 2); permission++)
                        {
                            newCell = new TableCell();

                            // Check if the currently processed access is applied for permission
                            isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                            // Disable column in roles grid if needed
                            if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                            {
                                gridMatrix.DisableColumn(permissionIndex);
                            }

                            // Insert the radio button for the current permission
                            string permissionText = tblMatrix.Rows[0].Cells[permission + 1].Text;
                            string elemId = ClientID + "_" + permission + "_" + access;
                            newCell.Text = "<label style=\"display:none;\" for=\"" + elemId + "\">" + permissionText + "</label><input type=\"radio\" id=\"" + elemId + "\" name=\"" + permissionText + "\" onclick=\"" +
                                           ControlsHelper.GetPostBackEventReference(this, permission.ToString() + ";" + Convert.ToInt32(currentAccess).ToString()) + "\" " +
                                           ((isAllowed) ? "checked = \"checked\"" : "") + ((isDisabled) ? " disabled=\"disabled\"" : "") + "/>";

                            newCell.Wrap = false;
                            newCell.Width = new Unit(12, UnitType.Percentage);
                            newCell.HorizontalAlign = HorizontalAlign.Center;
                            newRow.Cells.Add(newCell);
                            permissionIndex++;
                        }

                        newCell = new TableCell();
                        newCell.Text = "&nbsp;";
                        newRow.Cells.Add(newCell);

                        // Add the access row to the table
                        tblMatrix.Rows.Add(newRow);
                    }
                }

                // Check if project has some roles assigned
                mNoRolesAvailable = !gridMatrix.HasData;

                // Get permission matrix for current project resource
                if (!mNoRolesAvailable)
                {
                    // Security - Role separator
                    newRow = new TableRow();
                    newCell = new TableCell();
                    newCell.Text = "&nbsp;";
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);

                    // Security - Role separator text
                    newRow = new TableRow();
                    newCell = new TableCell();
                    newCell.CssClass = "MatrixLabel";
                    newCell.Text = GetString("SecurityMatrix.RolesAvailability");
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);
                }
            }
        }
    }
        public void Initalize()
        {
            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.LogInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }
            _logger.LogInformation($"Detecting projects in '{solutionFilePath}'.");

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.LogWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.LogInformation($"Loading project from '{projectFilePath}'.");

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }
            private async Task UpdateSymbolTreeInfoAsync(Project project, CancellationToken cancellationToken)
            {
                if (!project.SupportsCompilation)
                {
                    return;
                }

                // Check the semantic version of this project.  The semantic version will change
                // if any of the source files changed, or if the project version itself changed.
                // (The latter happens when something happens to the project like metadata 
                // changing on disk).
                var version = await project.GetSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

                ProjectInfo projectInfo;
                if (!_projectToInfo.TryGetValue(project.Id, out projectInfo) || projectInfo.VersionStamp != version)
                {
                    var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

                    // Update the symbol tree infos for metadata and source in parallel.
                    var referencesTask = UpdateReferencesAync(project, compilation, cancellationToken);
                    var projectTask = SymbolTreeInfo.GetInfoForSourceAssemblyAsync(project, cancellationToken);

                    await Task.WhenAll(referencesTask, projectTask).ConfigureAwait(false);

                    // Mark that we're up to date with this project.  Future calls with the same 
                    // semantic version can bail out immediately.
                    projectInfo = new ProjectInfo(version, await projectTask.ConfigureAwait(false));
                    _projectToInfo.AddOrUpdate(project.Id, projectInfo, (_1, _2) => projectInfo);
                }
            }
Exemplo n.º 60
0
        /// <summary>
        /// Event when OK button is pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void buttonOK_Click(object sender, RoutedEventArgs args)
        {
            // Saved changes to both Address Tab items and File Header Tab items if they have changed

            if (m_newAddressItem.isUnchanged(m_savedAddressItem) == false)
            {
                m_newAddress.UpdateAddress(IFCCommandOverrideApplication.TheDocument, m_newAddressItem);
            }

            if (m_newFileHeaderItem.isUnchanged(m_savedFileHeaderItem) == false)
            {
                m_newFileHeader.UpdateFileHeader(IFCCommandOverrideApplication.TheDocument, m_newFileHeaderItem);
            }

            if (m_newAddressItem.UpdateProjectInformation == true)
            {
                // Format IFC address and update it into Project Information: Project Address
                String address = null;
                String geographicMapLocation = null;
                bool   addNewLine            = false;

                if (String.IsNullOrEmpty(m_newAddressItem.AddressLine1) == false)
                {
                    address += string.Format("{0}\r\n", m_newAddressItem.AddressLine1);
                }
                if (String.IsNullOrEmpty(m_newAddressItem.AddressLine2) == false)
                {
                    address += string.Format("{0}\r\n", m_newAddressItem.AddressLine2);
                }
                if (String.IsNullOrEmpty(m_newAddressItem.POBox) == false)
                {
                    address += string.Format("{0}\r\n", m_newAddressItem.POBox);
                }
                if (String.IsNullOrEmpty(m_newAddressItem.TownOrCity) == false)
                {
                    address   += string.Format("{0}", m_newAddressItem.TownOrCity);
                    addNewLine = true;
                }
                if (String.IsNullOrEmpty(m_newAddressItem.RegionOrState) == false)
                {
                    address   += string.Format(", {0}", m_newAddressItem.RegionOrState);
                    addNewLine = true;
                }
                if (String.IsNullOrEmpty(m_newAddressItem.PostalCode) == false)
                {
                    address   += string.Format(" {0}", m_newAddressItem.PostalCode);
                    addNewLine = true;
                }
                if (addNewLine == true)
                {
                    address   += string.Format("\r\n");
                    addNewLine = false;
                }

                if (String.IsNullOrEmpty(m_newAddressItem.Country) == false)
                {
                    address += string.Format("{0}\r\n", m_newAddressItem.Country);
                }

                if (String.IsNullOrEmpty(m_newAddressItem.InternalLocation) == false)
                {
                    address += string.Format("\r\n{0}: {1}\r\n",
                                             Properties.Resources.InternalAddress, m_newAddressItem.InternalLocation);
                }

                if (String.IsNullOrEmpty(m_newAddressItem.TownOrCity) == false)
                {
                    geographicMapLocation = m_newAddressItem.TownOrCity;
                }

                if (String.IsNullOrEmpty(m_newAddressItem.RegionOrState) == false)
                {
                    if (String.IsNullOrEmpty(geographicMapLocation) == false)
                    {
                        geographicMapLocation = geographicMapLocation + ", " + m_newAddressItem.RegionOrState;
                    }
                    else
                    {
                        geographicMapLocation = m_newAddressItem.RegionOrState;
                    }
                }

                if (String.IsNullOrEmpty(m_newAddressItem.Country) == false)
                {
                    if (String.IsNullOrEmpty(geographicMapLocation) == false)
                    {
                        geographicMapLocation = geographicMapLocation + ", " + m_newAddressItem.Country;
                    }
                    else
                    {
                        geographicMapLocation = m_newAddressItem.Country;
                    }
                }
                ;

                Transaction transaction = new Transaction(IFCCommandOverrideApplication.TheDocument, Properties.Resources.UpdateProjectAddress);
                transaction.Start();

                ProjectInfo projectInfo = IFCCommandOverrideApplication.TheDocument.ProjectInformation;
                projectInfo.Address = address;    // set project address information using the IFC Address Information when requested

                if (String.IsNullOrEmpty(geographicMapLocation) == false)
                {
                    IFCCommandOverrideApplication.TheDocument.ActiveProjectLocation.SiteLocation.PlaceName = geographicMapLocation;    // Update also Revit Site location on the Map using City, State and Country when they are not null
                }
                transaction.Commit();
            }

            // Update Classification if it has changed or the mandatory fields are filled. If mandatory fields are not filled we will ignore the classification.
            if (!m_newClassification.IsUnchanged(m_savedClassification))
            {
                if (m_newClassification.AreMandatoryFieldsFilled())
                {
                    IFCClassificationMgr.UpdateClassification(IFCCommandOverrideApplication.TheDocument, m_newClassification);
                }
                else if (!m_newClassification.IsClassificationEmpty())
                {
                    m_newClassification.ClassificationTabMsg = Properties.Resources.ManditoryFieldsNotEmpty;
                    return;
                }
            }

            m_newClassification.ClassificationTabMsg = null;
            Close();
        }