private void Parse(FileCodeModel2 model)
 {
     Dispatcher.VerifyAccess();
     foreach (CodeElement codeElement in model.CodeElements)
     {
         if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
         {
             CodeNamespace namespaceElement = codeElement as CodeNamespace;
             foreach (CodeElement elem in namespaceElement.Children)
             {
                 if (elem.Kind == vsCMElement.vsCMElementFunction)
                 {
                     CodeFunction funcElement = elem as CodeFunction;
                     funcInfo("", (CodeElement)funcElement);
                 }
             }
         }
         if (codeElement.Kind == vsCMElement.vsCMElementClass)
         {
             CodeClass classElement = codeElement as CodeClass;
             foreach (CodeElement elem in classElement.Children)
             {
                 if (elem.Kind == vsCMElement.vsCMElementFunction)
                 {
                     CodeFunction funcElement = elem as CodeFunction;
                     funcInfo(classElement.FullName, elem);
                 }
             }
         }
         if (codeElement.Kind == vsCMElement.vsCMElementFunction)
         {
             funcInfo("", codeElement);
         }
     }
 }
        public static CodeItem Create(FileCodeModel2 codeModel)
        {
            var list = new List <CodeElement2>();

            CollectElements(list, codeModel.CodeElements, new [] { vsCMElement.vsCMElementClass });
            if (list.Count == 0)
            {
                return(new OtherItem("Unknow"));
            }

            var item = list.Cast <CodeClass>().First();

            if (item.IsDerivedFrom["MavenThought.Commons.Testing.BaseTest"])
            {
                if (item.Name.Contains("Specification"))
                {
                    return(new SpecificationItem(item.Name, item.Namespace.Name, item.FullName));
                }

                var spec   = (CodeClass)item.Bases.Cast <CodeElement>().First(ce => ce is CodeClass);
                var spItem = new SpecificationItem(spec.Name, spec.Namespace.Name, spec.FullName);

                return(new SenarioItem(item.Name, item.Namespace.Name, item.FullName, spItem));
            }

            return(new ClassItem(item.Name, item.Namespace.Name, item.FullName));
        }
        public MemberSorter(DTE dte, bool findMembers)
        {
            this.textHandler = new TextDocumentHandler(dte);
            this.language    = this.textHandler.Language;

            if (this.textHandler.HasNonEmptySelection &&
                this.textHandler.Document != null &&
                (this.language == Language.CSharp || this.language == Language.VB))
            {
                this.selectionStart = this.textHandler.Selection.TopPoint;
                this.selectionEnd   = this.textHandler.Selection.BottomPoint;

                ProjectItem item = this.textHandler.Document.ProjectItem;
                if (item != null)
                {
                    FileCodeModel2 codeModel = item.FileCodeModel as FileCodeModel2;
                    if (codeModel != null && codeModel.ParseStatus == vsCMParseStatus.vsCMParseStatusComplete)
                    {
                        // For CommandProcessor.CanExecute, we don't actually want to find the members (since
                        // CanExecute is called A LOT).  We just want to know if we got far enough to try.
                        this.CanFindMembers = true;
                        if (findMembers)
                        {
                            this.memberLists = FindMembers(codeModel.CodeElements, this.IsMemberSelected);
                        }
                    }
                }
            }
        }
        private void ModuleRenamed(object source, ElementPropertyChangedEventArgs e)
        {
            //If an element with the old name exists it means the designer is auto-assigning a new name
            //to a newly dropped element and there's no need to rename the corresponding code element. In
            //fact that would be wrong because we would end up renaming the code element corresponding to the
            //model element with the old name, whose name hasn't changed.
            if (((Module)e.ModelElement).CountModulesWithName((string)e.OldValue) > 0)
            {
                return;
            }

            FileCodeModel2 fcm = GetGeneratedFileCodeModel();

            if (fcm == null)
            {
                return;
            }
            CodeElement2 field = FindElement(fcm.CodeElements, (string)e.OldValue, vsCMElement.vsCMElementVariable);

            if (field != null)
            {
                field.RenameSymbol((string)e.NewValue);
            }

            UpdateView();
        }
        public static CodeItem Create(FileCodeModel2 codeModel)
        {
            var list = new List<CodeElement2>();
            CollectElements(list, codeModel.CodeElements, new [] { vsCMElement.vsCMElementClass });
            if (list.Count == 0)
            {
                return new OtherItem("Unknow", null);
            }

            var item = list.Cast<CodeClass>().First();

            if (item.IsDerivedFrom["MavenThought.Commons.Testing.BaseTest"])
            {
                if (item.Name.Contains("Specification"))
                {
                    return new SpecificationItem(item.Name, item.Namespace.Name, item.FullName, item.ProjectItem);  
                }

                var spec = (CodeClass)item.Bases.Cast<CodeElement>().First(ce => ce is CodeClass);
                var spItem = new SpecificationItem(spec.Name, spec.Namespace.Name, spec.FullName, item.ProjectItem);

                return new SenarioItem(item.Name, item.Namespace.Name, item.FullName, spItem, item.ProjectItem);
            }

            return new ClassItem(item.Name, item.Namespace.Name, item.FullName, item.ProjectItem);
        }
        /// <summary>
        /// Initializes objects used to access opened document's buffer
        /// </summary>
        protected void InitializeVariables()
        {
            currentDocument = VisualLocalizerPackage.Instance.DTE.ActiveDocument;
            if (currentDocument == null)
            {
                throw new Exception("No selected document");
            }
            if (currentDocument.ReadOnly)
            {
                throw new Exception("Cannot perform this operation - active document is readonly");
            }

            bool fileOpened;

            currentCodeModel = currentDocument.ProjectItem.GetCodeModel(false, false, out fileOpened);

            textManager = (IVsTextManager)Package.GetGlobalService(typeof(SVsTextManager));
            if (textManager == null)
            {
                throw new Exception("Cannot consume IVsTextManager service");
            }

            int hr = textManager.GetActiveView(1, null, out textView);

            Marshal.ThrowExceptionForHR(hr);

            hr = textView.GetBuffer(out textLines);
            Marshal.ThrowExceptionForHR(hr);

            hr = textLines.GetUndoManager(out undoManager);
            Marshal.ThrowExceptionForHR(hr);
        }
        private void ReorderMembers(CodeElement2 type, IEnumerable <CodeMember> members, string orderedCode, TextPoint startPoint)
        {
            // Removing members will shift the startPoint back one line.
            // So we'll use the absolute offset to jump back to that insert point.
            int startPointOffset = 0;

            if (startPoint != null)
            {
                startPointOffset = startPoint.AbsoluteCharOffset;
            }

            FileCodeModel2 codeModel = this.textHandler.Document.ProjectItem.FileCodeModel as FileCodeModel2;

            codeModel.BeginBatch();
            try
            {
                foreach (CodeMember member in members)
                {
                    member.Remove();
                }
            }
            finally
            {
                codeModel.EndBatch();
            }

            if (startPoint != null)
            {
                EditPoint startEdit = startPoint.CreateEditPoint();
                startEdit.MoveToAbsoluteOffset(startPointOffset);
                startEdit.StartOfLine();

                // If the line above startEdit isn't empty and isn't the start of the class/struct/interface/enum,
                // then insert a blank line so the sortedCode will be separated from the code above it.
                EditPoint lineAboveEdit = startEdit.CreateEditPoint();
                lineAboveEdit.LineUp();
                lineAboveEdit.StartOfLine();
                string lineText = lineAboveEdit.GetText(lineAboveEdit.LineLength).Trim();
                if (lineText.Length != 0 &&
                    lineAboveEdit.Line > type.StartPoint.Line &&
                    (this.language != Language.CSharp || lineText != "{"))
                {
                    startEdit.Insert(Environment.NewLine);
                }

                startEdit.Insert(orderedCode);

                // If the line after startEdit isn't empty and isn't the end of the class/struct/interface/enum,
                // then insert a blank line so the sortedCode will be separated from the code below it.
                startEdit.StartOfLine();
                lineText = startEdit.GetText(startEdit.LineLength).Trim();
                if (lineText.Length != 0 &&
                    startEdit.Line < type.EndPoint.Line &&
                    (this.language != Language.CSharp || lineText != "}"))
                {
                    startEdit.Insert(Environment.NewLine);
                }
            }
        }
        // examine an item
        private void ExamineItem(ProjectItem item)
        {
            FileCodeModel2 model = (FileCodeModel2)item.FileCodeModel;

            foreach (CodeElement codeElement in model.CodeElements)
            {
                ExamineCodeElement(codeElement, 3);
            }
        }
Example #9
0
 private static CodeFunction GetCodeFunction(FileCodeModel2 fcm, TextPoint point)
 {
     try {
         var element = fcm.CodeElementFromPoint(point, vsCMElement.vsCMElementFunction);
         return((CodeFunction)element);
     } catch {
         return(null);
     }
 }
Example #10
0
        /// <summary>
        /// Creates a test file named 'SecuredTests.cs' that contains all the test methods.
        /// </summary>
        /// <param name="p_methods"></param>
        public static void CreateTestFile(Dictionary <TestingMethodVM, List <TestConfiguration> > p_methods)
        {
            DTE2           dte         = (DTE2)Secure_TDDPackage.GetGlobalService(typeof(DTE));
            Solution2      soln        = (Solution2)dte.Solution;
            Project        currentProj = dte.ActiveDocument.ProjectItem.ContainingProject;
            Project        proj        = GetTestingProject(currentProj);
            ProjectItem    pi          = GetCSTestFile(proj, soln);
            FileCodeModel2 fcm         = (FileCodeModel2)pi.FileCodeModel;

            if (!IsContainImports(fcm))
            {
                fcm.AddImport("System");
                fcm.AddImport("System.Linq");
                fcm.AddImport("System.Text");
                fcm.AddImport("System.Collections.Generic");
                fcm.AddImport("Microsoft.VisualStudio.TestTools.UnitTesting");
            }

            string        namespaceName    = "Testing";
            CodeNamespace testingNameSpace = GetNamespace(fcm, namespaceName);

            if (testingNameSpace != null)
            {
                string     className    = "SecuredTestClass";
                CodeClass2 securedClass = GetClass(fcm, testingNameSpace, className);

                foreach (var methodKeyValue in p_methods)
                {
                    var startIndexOfMethodName = methodKeyValue.Key.FullName.LastIndexOf('.');
                    var methodBaseName         = methodKeyValue.Key.FullName.Substring(startIndexOfMethodName + 1) + "_{0}Test";

                    foreach (var testConfiguration in methodKeyValue.Value)
                    {
                        // Remove all white-spaces in the test name.
                        var fixedName    = testConfiguration.Name.Replace(" ", string.Empty);
                        var methodName   = string.Format(methodBaseName, fixedName);
                        var functionBody = GetMethodBody(methodKeyValue.Key, testConfiguration);
                        AddFunction(securedClass, methodName, functionBody);
                    }
                }
            }

            // if the file is not opened in the text editor, open and activate it.
            Window window = pi.Open(Constants.vsViewKindCode);

            if (window != null)
            {
                window.Activate();
                dte.ExecuteCommand("Edit.FormatDocument");
            }

            // Save the file.
            pi.Save();
        }
Example #11
0
        public void FileCodeModel_ProjectDirectory_ReturnsNull()
        {
            CreateProjectItems();
            msbuildProject.AddFile(@"src\program.cs");

            ProjectItem directoryItem = projectItems.Item("src");

            FileCodeModel2 fileCodeModel = directoryItem.FileCodeModel;

            Assert.IsNull(fileCodeModel);
        }
Example #12
0
        /// <summary>
        /// Finds the or create import.
        /// </summary>
        /// <param name="fileCodeModel">The file code model.</param>
        /// <param name="importName">Name of the import.</param>
        /// <returns></returns>
        public static CodeImport FindOrCreateImport(FileCodeModel2 fileCodeModel, string importName)
        {
            foreach (CodeElement ce in (fileCodeModel).CodeElements)
            {
                if (ce is CodeImport && ((CodeImport)ce).Namespace == importName)
                {
                    return((CodeImport)ce);
                }
            }

            return((fileCodeModel).AddImport(importName, 0, null));
        }
Example #13
0
        private List <TableRecord> getTableList(FileCodeModel2 activeCodeModel)
        {
            if (activeCodeModel == null)
            {
                System.Windows.Forms.MessageBox.Show("No active code is open");
                return(new List <TableRecord>());
            }

            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            Collector collector = new Collector(activeCodeModel, debugPane);

            return(collector.ParseFileCodeModel());
        }
Example #14
0
        public List <ProjectObj> DiscoverProjectClasses()
        {
            var projects = new List <ProjectObj>();

            // get the DTE reference
            var dte = (DTE2)Microsoft.VisualStudio.Shell.ServiceProvider
                      .GlobalProvider.GetService(typeof(EnvDTE.DTE));

            // get the solution
            Solution solution = dte.Solution;

            Console.WriteLine(solution.FullName);

            // get all the projects
            foreach (Project project in solution.Projects)
            {
                var proj = new ProjectObj()
                {
                    Name = project.Name
                };

                // get all the items in each project
                foreach (ProjectItem item in project.ProjectItems)
                {
                    FileCodeModel2 model = (FileCodeModel2)item.FileCodeModel;
                    if (model != null)
                    {
                        foreach (CodeElement codeElement in model.CodeElements)
                        {
                            if (codeElement.Kind == vsCMElement.vsCMElementNamespace)
                            {
                                foreach (CodeElement ce in codeElement.Children)
                                {
                                    if (ce.Kind == vsCMElement.vsCMElementClass)
                                    {
                                        proj.Classes.Add(new ProjectClass()
                                        {
                                            Name = item.Name.Replace(".cs", "")
                                        });
                                    }
                                }
                            }
                        }
                    }
                }
                projects.Add(proj);
            }

            return(projects);
        }
        private object NewImport(NewCodeElementItemParams newItemParams, string path, object newItemValue)
        {
            FileCodeModel2 fileCodeModel2 = _codeModel as FileCodeModel2;

            if (null == fileCodeModel2)
            {
                return(null);
            }

            // apparantly required to prevent an exception in VS
            newItemParams.Position = Math.Max(newItemParams.Position, 0);

            return(fileCodeModel2.AddImport(path, newItemParams.Position, String.Empty));
        }
Example #16
0
        /// <summary>
        /// Treats given ProjectItem as a VB code file, using VBCodeExplorer to examine the file. LookInVB method is called as a callback,
        /// given plain methods text.
        /// </summary>
        protected override void ProcessVB(ProjectItem projectItem, Predicate <CodeElement> exploreable, bool verbose)
        {
            if (isInitial || editorInstance.UIControl.sourceFilesThatNeedUpdate.Contains(projectItem.GetFullPath().ToLower()))
            {
                base.ProcessVB(projectItem, exploreable, verbose);
            }
            else
            {
                bool           fileOpened;
                FileCodeModel2 codeModel = projectItem.GetCodeModel(false, false, out fileOpened);

                if (codeModel == null && !RDTManager.IsFileOpen(projectItem.GetFullPath()))
                {
                    editorInstance.UIControl.RegisterAsStaticReferenceSource(projectItem);
                    return;
                }

                if (codeModel == null)
                {
                    if (verbose)
                    {
                        VLOutputWindow.VisualLocalizerPane.WriteLine("\tCannot process {0}, file code model does not exist.", projectItem.Name);
                    }
                    return;
                }
                if (verbose)
                {
                    VLOutputWindow.VisualLocalizerPane.WriteLine("\tProcessing {0}", projectItem.Name);
                }

                currentlyProcessedItem = projectItem;

                try {
                    VBCodeExplorer.Instance.Explore(this, exploreable, codeModel);
                } catch (COMException ex) {
                    if (ex.ErrorCode == -2147483638)
                    {
                        VLOutputWindow.VisualLocalizerPane.WriteLine("\tError occured during processing {0} - the file is not yet compiled.", projectItem.Name);
                    }
                    else
                    {
                        throw;
                    }
                }

                currentlyProcessedItem = null;
            }
            editorInstance.UIControl.sourceFilesThatNeedUpdate.Remove(projectItem.GetFullPath().ToLower());
        }
Example #17
0
        void LoadProjectModules()
        {
            try
            {
                var projects = GetProjects();

                List <ProjectModuleInfo> projectModules = new List <ProjectModuleInfo>();

                foreach (var project in projects)
                {
                    foreach (ProjectItem item in project.ProjectItems)
                    {
                        FileCodeModel2 codeModel = (FileCodeModel2)item.FileCodeModel;
                        if (codeModel != null)
                        {
                            CodeClass2 codeClass = GetCodeClass(codeModel.CodeElements);
                            if (codeClass != null)
                            {
                                if (IsIModule(codeClass.ImplementedInterfaces))
                                {
                                    var moduleInfo = new ProjectModuleInfo();
                                    moduleInfo.ModuleName   = codeClass.Name;
                                    moduleInfo.AssemblyFile = String.Format("{0}.dll", project.Properties.Item("AssemblyName").Value);
                                    moduleInfo.ModuleType   = GetModuleType(project, codeClass);
                                    projectModules.Add(moduleInfo);
                                    break;
                                }
                            }
                        }
                    }
                }

                _designer.ProjectModules = new System.Collections.ObjectModel.ObservableCollection <ProjectModuleInfo>(projectModules);
            }
            catch (Exception ex)
            {
                string message = "The was a problem reading the projects in this solution. Build the solution and try again.";
                string title   = "Error Loading Projects";

                // Show a message box to prove we were here
                VsShellUtilities.ShowMessageBox(
                    this,
                    message,
                    title,
                    OLEMSGICON.OLEMSGICON_INFO,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }
        }
Example #18
0
        private static bool IsContainImports(FileCodeModel2 p_fcm)
        {
            bool isContains = false;

            foreach (CodeElement2 codeElement in p_fcm.CodeElements)
            {
                if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                {
                    isContains = true;
                    break;
                }
            }

            return(isContains);
        }
Example #19
0
        /// <summary>
        /// Adds new namespace import into the given document.
        /// </summary>
        public static CodeImport AddUsingBlock(this Document document, string newNamespace)
        {
            if (document == null || document.ProjectItem == null)
            {
                throw new Exception("No document or project item.");
            }
            if (string.IsNullOrEmpty(newNamespace))
            {
                throw new ArgumentNullException("newNamespace");
            }

            bool           fileOpened;
            FileCodeModel2 model = document.ProjectItem.GetCodeModel(true, false, out fileOpened);

            return(model.AddImport(newNamespace, 0, string.Empty));
        }
Example #20
0
        /// <summary>
        /// Get the specified namespace from the given file code model. Creates new namespace if no exists.
        /// </summary>
        /// <param name="p_fcm"></param>
        /// <param name="p_namespaceName"></param>
        /// <returns></returns>
        private static CodeNamespace GetNamespace(FileCodeModel2 p_fcm, string p_namespaceName)
        {
            CodeNamespace testingNameSpace = null;

            foreach (CodeElement2 codeElement in p_fcm.CodeElements)
            {
                testingNameSpace = FindNamespaceRecursive(codeElement, p_namespaceName);
                if (testingNameSpace != null)
                {
                    break;
                }
            }

            if (testingNameSpace == null)
            {
                testingNameSpace = p_fcm.AddNamespace(p_namespaceName, -1);
            }
            return(testingNameSpace);
        }
Example #21
0
        public static AssemblyMethodSignature GetSignature(VirtualPoint point, FileCodeModel2 fcm)
        {
            var codeFunction = GetCodeFunction(fcm, point);

            if (codeFunction == null)
            {
                return(null);
            }
            // init and remove generic part
            string funcName = GenericPartRegex.Replace(codeFunction.FullName, String.Empty);
            IEnumerable <CodeTypeRef> paramsList;

            switch (codeFunction.FunctionKind)
            {
            case vsCMFunction.vsCMFunctionPropertyGet:
            case vsCMFunction.vsCMFunctionPropertySet:

                var prefix = codeFunction.FunctionKind == vsCMFunction.vsCMFunctionPropertyGet
                        ? "get_"
                        : "set_";

                var lastDot = funcName.LastIndexOf(".", StringComparison.Ordinal);
                funcName = funcName.Substring(0, lastDot + 1) + prefix + funcName.Substring(lastDot + 1);

                paramsList = codeFunction.FunctionKind == vsCMFunction.vsCMFunctionPropertyGet
                        ? new List <CodeTypeRef>()
                        : new List <CodeTypeRef> {
                    codeFunction.Type
                };
                break;

            default:
                if (codeFunction.FunctionKind == vsCMFunction.vsCMFunctionConstructor)
                {
                    var lastIndex = funcName.LastIndexOf(codeFunction.Name, StringComparison.Ordinal);
                    funcName = funcName.Substring(0, lastIndex) + ".ctor";
                }
                paramsList = codeFunction.Parameters.OfType <CodeParameter>().Select(p => p.Type);
                break;
            }
            return(new AssemblyMethodSignature(funcName, paramsList.Select(ProcessTypeRef).ToList()));
        }
Example #22
0
            private static CodeClass2 FindClass(FileCodeModel2 model, string name)
            {
                // Create a queue to "recurse" through all the child elements of the file
                Queue <CodeElement2> remaining = new Queue <CodeElement2>();

                // Start with the top level elements
                foreach (object element in model.CodeElements)
                {
                    remaining.Enqueue(new CodeElement2(element));
                }

                // "Recurse" through their children
                while (remaining.Count > 0)
                {
                    CodeElement2 element = remaining.Dequeue();

                    // Ignore anything that isn't a type or a namespace
                    if (element == null || element.Reference == null || (!element.IsCodeType && element.Kind != vsCMElement.vsCMElementNamespace))
                    {
                        continue;
                    }

                    // If it's a class with a matching name, return it
                    if ((element.Kind == vsCMElement.vsCMElementClass) && (string.CompareOrdinal(element.FullName, name) == 0))
                    {
                        return(new CodeClass2(element.Reference));
                    }

                    // Add any children of the type
                    if (element.Children != null)
                    {
                        foreach (object child in element.Children)
                        {
                            remaining.Enqueue(new CodeElement2(child));
                        }
                    }
                }

                // Return null if we couldn't find a node corresponding to the class name
                return(null);
            }
Example #23
0
        /// <summary>
        /// Treats given ProjectItem as a VB code file, using VBCodeExplorer to examine the file. LookInVB method is called as a callback,
        /// given plain methods text.
        /// </summary>
        protected virtual void ProcessVB(ProjectItem projectItem, Predicate <CodeElement> exploreable, bool verbose)
        {
            bool           fileOpened;
            FileCodeModel2 codeModel = projectItem.GetCodeModel(false, true, out fileOpened);

            if (fileOpened)
            {
                VLDocumentViewsManager.AddInvisibleWindow(projectItem.GetFullPath(), invisibleWindowsAuthor);
                VLOutputWindow.VisualLocalizerPane.WriteLine("\tForce opening {0} in background in order to obtain code model", projectItem.Name);
            }

            if (codeModel == null)
            {
                if (verbose)
                {
                    VLOutputWindow.VisualLocalizerPane.WriteLine("\tCannot process {0}, file code model does not exist.", projectItem.Name);
                }
                return;
            }
            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("\tProcessing {0}", projectItem.Name);
            }

            currentlyProcessedItem = projectItem;

            try {
                VBCodeExplorer.Instance.Explore(this, exploreable, codeModel);
            } catch (COMException ex) {
                if (ex.ErrorCode == -2147483638)
                {
                    VLOutputWindow.VisualLocalizerPane.WriteLine("\tError occured during processing {0} - the file is not yet compiled.", projectItem.Name);
                }
                else
                {
                    throw;
                }
            }

            currentlyProcessedItem = null;
        }
        private void MenuItemCallback()
        {
            Dispatcher.VerifyAccess();
            table.Clear();
            DTE2 dte;

            try
            {
                dte = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));
                ProjectItem    item  = dte.ActiveDocument.ProjectItem;
                FileCodeModel2 model = (FileCodeModel2)item.FileCodeModel;
                if (model != null)
                {
                    Parse(model);
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.ToString());
            }
        }
Example #25
0
        /// <summary>
        /// Get the specified class from the given namespace. Creates new class if no exists.
        /// </summary>
        /// <param name="p_fcm"></param>
        /// <param name="p_testingNameSpace"></param>
        /// <param name="p_className"></param>
        /// <returns></returns>
        private static CodeClass2 GetClass(FileCodeModel2 p_fcm, CodeNamespace p_testingNameSpace, string p_className)
        {
            CodeClass2 securedClass = null;

            foreach (CodeElement2 codeElement in p_fcm.CodeElements)
            {
                securedClass = FindClassRecursive(codeElement, p_className);
                if (securedClass != null)
                {
                    break;
                }
            }

            if (securedClass == null)
            {
                // Add a class to the namespace.
                securedClass = (CodeClass2)p_testingNameSpace.AddClass(p_className, -1, null, null, vsCMAccess.vsCMAccessPublic);
                securedClass.DataTypeKind = vsCMDataTypeKind.vsCMDataTypeKindPartial;
                securedClass.AddAttribute("TestClass", string.Empty);
            }
            return(securedClass);
        }
Example #26
0
        public static FileCodeModel2 AddNotExistingImports(this FileCodeModel2 fileCodeModel, IEnumerable <string> importsToAdd)
        {
            if (null == fileCodeModel)
            {
                throw new ArgumentNullException(nameof(fileCodeModel));
            }

            var currentImports = fileCodeModel.CodeElements
                                 .OfType <CodeImport>()
                                 .Select(x => x.Namespace)
                                 .ToList();

            foreach (var import in importsToAdd)
            {
                if (!currentImports.Any(x => x == import))
                {
                    fileCodeModel.AddImport(import, 0);
                }
            }

            return(fileCodeModel);
        }
        /// <summary>
        /// Adds the using statement.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="usingStatement">The using statement.</param>
        public static void AddUsingStatement(
            this ProjectItem instance,
            string usingStatement)
        {
            TraceService.WriteLine("ProjectItemExtensions::AddUsingStatement in file " + instance.Name + " statement " + usingStatement);

            CodeNamespace codeNamespace = instance.GetFirstNameSpace();

            if (codeNamespace != null)
            {
                FileCodeModel2 fileCodeModel2 = codeNamespace.ProjectItem.FileCodeModel as FileCodeModel2;

                if (fileCodeModel2 != null)
                {
                    fileCodeModel2.AddImport(usingStatement);
                }
            }
            else
            {
                TraceService.WriteError("ProjectItemExtensions::AddUsingStatement cannot find namespace");
            }
        }
Example #28
0
        public void BeginTraverse(FileCodeModel fcm)
        {
            FileCodeModel2 fcm2 = fcm as FileCodeModel2;

            if (fcm2 == null)
            {
                return;
            }
            String[] imports = _injector.OnGenerateUsing(_context);
            if (imports != null)
            {
                foreach (string import in imports)
                {
                    try
                    {
                        fcm2.AddImport(import, null, String.Empty);
                    }
                    catch
                    {
                    }
                }
            }
        }
Example #29
0
        /// <summary>
        /// Adds the allow partially trusted callers attribute to the AssemblyInfo.
        /// </summary>
        /// <param name="dteProject">The DTE project.</param>
        public static void AddAllowPartiallyTrustedCallersAttribute(EnvDTE.Project dteProject)
        {
            EnvDTE.ProjectItem item = DTEManager.FindItemByName(dteProject.ProjectItems, "assemblyinfo.cs", true);

            bool contains = false;

            FileCodeModel2 model = (FileCodeModel2)item.FileCodeModel;

            foreach (CodeElement codeElement in model.CodeElements)
            {
                if (ExamineCodeElement(codeElement, "allowpartiallytrustedcallers", 3))
                {
                    contains = true;
                    break;
                }
            }

            //The attribute was not found so make sure it gets added.
            if (!contains)
            {
                model.AddAttribute("AllowPartiallyTrustedCallers", null);
            }
        }
Example #30
0
        /// <summary>
        /// Shows the tool window when the menu item is clicked.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread("Exception in Execute()");

            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = this.package.FindToolWindow(typeof(ExtToolWindow), 0, true);

            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException("Cannot create tool window");
            }

            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());

            FileCodeModel2 codeModel = getCurrentCodeModel();

            ExtToolWindowControl toolWindow = window.Content as ExtToolWindowControl;

            toolWindow.InfoTable.ItemsSource = getTableList(codeModel);
        }
Example #31
0
        /// <summary>
        /// Adds the using statement.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="usingStatement">The using statement.</param>
        public static void AddUsingStatement(
            this ProjectItem instance,
            string usingStatement)
        {
            FileCodeModel2 fileCodeModel2 = instance.GetFirstNameSpace().ProjectItem.FileCodeModel as FileCodeModel2;

            if (fileCodeModel2 != null)
            {
                foreach (CodeElement codeElement in fileCodeModel2.CodeElements)
                {
                    if (codeElement.Kind == vsCMElement.vsCMElementImportStmt)
                    {
                        CodeImport codeImport = codeElement as CodeImport;

                        if (codeImport.Namespace == usingStatement)
                        {
                            return;
                        }
                    }
                }

                fileCodeModel2.AddImport(usingStatement);
            }
        }
Example #32
0
        private static void EnsureUsingDirective(FileCodeModel2 fileCodeModel, string importName)
        {
            bool importNotFound = true;
            foreach (CodeElement ce in (fileCodeModel).CodeElements)
            {
                if (ce is CodeImport && ((CodeImport)ce).Namespace == importName)
                {
                    importNotFound = false;
                    break;
                }
            }

            if (importNotFound)
                fileCodeModel.AddImport(importName);
        }