Ejemplo n.º 1
0
        ArrayList SearchClasses(string text)
        {
            int    dotPos = text.IndexOf('.');
            string needle = text;
            string member = "";

            if (dotPos > 0)
            {
                needle = text.Substring(0, dotPos).Trim();
                member = text.Substring(dotPos + 1).Trim();
            }
            ArrayList list = new ArrayList();

            if (ProjectService.OpenSolution != null)
            {
                foreach (IProject project in ProjectService.OpenSolution.Projects)
                {
                    IProjectContent projectContent = ParserService.GetProjectContent(project);
                    if (projectContent != null)
                    {
                        AddClasses(needle, member, list, projectContent.Classes);
                    }
                }
            }
            return(list);
        }
Ejemplo n.º 2
0
 static void GetPossibleFilesInternal(List <ProjectItem> resultList, IProjectContent ownerProjectContent, bool internalOnly)
 {
     if (ProjectService.OpenSolution == null)
     {
         return;
     }
     foreach (IProject p in ProjectService.OpenSolution.Projects)
     {
         IProjectContent pc = ParserService.GetProjectContent(p);
         if (pc == null)
         {
             continue;
         }
         if (pc != ownerProjectContent)
         {
             if (internalOnly)
             {
                 // internal = can be only referenced from same project content
                 continue;
             }
             if (!pc.ReferencedContents.Contains(ownerProjectContent))
             {
                 // project contents that do not reference the owner's content cannot reference the member
                 continue;
             }
         }
         foreach (ProjectItem item in p.Items)
         {
             if (item is FileProjectItem)
             {
                 resultList.Add(item);
             }
         }
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Looks for the specified type in all the projects in the open solution
        /// excluding the current project.
        /// </summary>
        static IProject FindProjectContainingType(string type)
        {
            IProject currentProject = ProjectService.CurrentProject;

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

            foreach (IProject project in ProjectService.OpenSolution.Projects)
            {
                if (project != currentProject)
                {
                    IProjectContent projectContent = ParserService.GetProjectContent(project);
                    if (projectContent != null)
                    {
                        if (projectContent.GetClass(type, 0) != null)
                        {
                            LoggingService.Debug("Found project containing type: " + project.FileName);
                            return(project);
                        }
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 4
0
        protected IClass GetClassFromName(string name)
        {
            if (name == null)
            {
                return(null);
            }
            if (ProjectService.OpenSolution == null)
            {
                return(null);
            }

            foreach (IProject project in ProjectService.OpenSolution.Projects)
            {
                IProjectContent content = ParserService.GetProjectContent(project);
                if (content != null)
                {
                    IClass c = content.GetClassByReflectionName(name, true);
                    if (c != null)
                    {
                        return(c);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 5
0
        protected override void Initialize()
        {
            base.Initialize();
            Nodes.Clear();

            List <IProjectContent> contentList = new List <IProjectContent>();

            if (ProjectService.OpenSolution != null)
            {
                foreach (IProject project in ProjectService.OpenSolution.Projects)
                {
                    IProjectContent projectContent = ParserService.GetProjectContent(project);
                    if (projectContent != null)
                    {
                        contentList.Add(projectContent);
                    }
                }
            }
            foreach (IClass derivedClass in RefactoringService.FindDerivedClasses(c, contentList, true))
            {
                new ClassNode(project, derivedClass).AddTo(this);
            }

            if (Nodes.Count == 0)
            {
                SetIcon(ClosedIcon);
                OpenedIcon = ClosedIcon = null;
            }
        }
Ejemplo n.º 6
0
        public override void LoadPanelContents()
        {
            SetupFromXmlResource("ProjectImports.xfrm");
            InitializeHelper();

            Get <Button>("addImport").Click               += new EventHandler(addImportButton_Click);
            Get <Button>("removeImport").Click            += new EventHandler(removeImportButton_Click);
            Get <ComboBox>("namespaces").TextChanged      += new EventHandler(namespacesComboBox_TextCanged);
            Get <ListBox>("imports").SelectedIndexChanged += new EventHandler(importsListBox_SelectedIndexChanged);

            Get <ComboBox>("namespaces").Items.Clear();
            Get <ComboBox>("namespaces").AutoCompleteSource = AutoCompleteSource.ListItems;
            Get <ComboBox>("namespaces").AutoCompleteMode   = AutoCompleteMode.Suggest;
            foreach (ProjectItem item in project.Items)
            {
                if (item.ItemType == ItemType.Import)
                {
                    Get <ListBox>("imports").Items.Add(item.Include);
                }
            }

            IProjectContent projectContent = ParserService.GetProjectContent(project);

            foreach (IProjectContent refProjectContent in projectContent.ReferencedContents)
            {
                AddNamespaces(refProjectContent);
            }
            AddNamespaces(projectContent);

            namespacesComboBox_TextCanged(null, EventArgs.Empty);
            importsListBox_SelectedIndexChanged(null, EventArgs.Empty);
        }
Ejemplo n.º 7
0
        public override void Load(OpenedFile file, Stream stream)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(stream);
            projectContent = ParserService.GetProjectContent(ProjectService.CurrentProject);
            canvas.LoadFromXml(doc, projectContent);
        }
 public static IProjectContent GetProjectContent(IProject project)
 {
     if (projectContents == null)
     {
         return(ParserService.GetProjectContent(project));
     }
     else
     {
         return(projectContents[project]);
     }
 }
        protected override void ConvertAst(CompilationUnit compilationUnit, List <ISpecial> specials, FileProjectItem sourceItem)
        {
            PreprocessingDirective.CSharpToVB(specials);
            IProjectContent             pc      = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
            CSharpToVBNetConvertVisitor visitor = new CSharpToVBNetConvertVisitor(pc, ParserService.GetParseInformation(sourceItem.FileName));

            visitor.RootNamespaceToRemove     = sourceItem.Project.RootNamespace;
            visitor.DefaultImportsToRemove    = defaultImports;
            visitor.StartupObjectToMakePublic = startupObject;
            compilationUnit.AcceptVisitor(visitor, null);
        }
Ejemplo n.º 10
0
 internal static IProjectContent GetProjectContent(OpenedFile file)
 {
     if (ProjectService.OpenSolution != null && file != null)
     {
         IProject p = ProjectService.OpenSolution.FindProjectContainingFile(file.FileName);
         if (p != null)
         {
             return(ParserService.GetProjectContent(p));
         }
     }
     return(ParserService.DefaultProjectContent);
 }
Ejemplo n.º 11
0
        protected override void ConvertAst(CompilationUnit compilationUnit, List <ISpecial> specials, FileProjectItem sourceItem)
        {
            PreprocessingDirective.VBToCSharp(specials);
            CompilableProject project = (CompilableProject)sourceItem.Project;

            RemoveWindowsFormsSpecificCode(compilationUnit, specials, project.OutputType == OutputType.WinExe);

            IProjectContent             pc      = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
            VBNetToCSharpConvertVisitor visitor = new VBNetToCSharpConvertVisitorWithMyFormsSupport(pc, ParserService.GetParseInformation(sourceItem.FileName), sourceItem.Project.RootNamespace);

            compilationUnit.AcceptVisitor(visitor, null);
        }
Ejemplo n.º 12
0
        protected IProjectContent GetProjectContent()
        {
            IProject p = FindProjectContainingFile();

            if (p != null)
            {
                return(ParserService.GetProjectContent(p) ?? ParserService.DefaultProjectContent);
            }
            else
            {
                return(ParserService.DefaultProjectContent);
            }
        }
        IEnumerable <IClass> GetAllStaticClasses(IProject project)
        {
            IProjectContent projectContent = ParserService.GetProjectContent(project);

            if (projectContent != null)
            {
                foreach (IClass c in projectContent.Classes)
                {
                    if (c.IsStatic)
                    {
                        yield return(c);
                    }
                }
            }
        }
        public SelectSourceClassDialog()
        {
            InitializeComponent();

            this.cache = ProjectService.OpenSolution.Projects
                         .Select(p => ParserService.GetProjectContent(p))
                         .SelectMany(content => (content == null) ? Enumerable.Empty <IClass>() : content.Classes.Where(aClass => aClass.ClassType == ClassType.Class))
                         .Where(myClass => !(myClass.IsAbstract || myClass.IsStatic))
                         .Select(c => new ClassWrapper()
            {
                Class = c, Name = c.Namespace + "." + c.Name
            });

            this.lvClasses.ItemsSource = this.cache;
        }
Ejemplo n.º 15
0
 public void StartSearch()
 {
     if (searchTerm.Length == 0)
     {
         CancelSearch();
         return;
     }
     if (!inSearchMode)
     {
         foreach (TreeNode node in classBrowserTreeView.Nodes)
         {
             oldNodes.Add(node);
         }
         inSearchMode = true;
         previousNodes.Clear();
         nextNodes.Clear();
         UpdateToolbars();
     }
     classBrowserTreeView.BeginUpdate();
     classBrowserTreeView.Nodes.Clear();
     if (ProjectService.OpenSolution != null)
     {
         foreach (IProject project in ProjectService.OpenSolution.Projects)
         {
             IProjectContent projectContent = ParserService.GetProjectContent(project);
             if (projectContent != null)
             {
                 foreach (IClass c in projectContent.Classes)
                 {
                     if (c.Name.ToUpper().StartsWith(searchTerm))
                     {
                         ClassNodeBuilders.AddClassNode(classBrowserTreeView, project, c);
                     }
                 }
             }
         }
     }
     if (classBrowserTreeView.Nodes.Count == 0)
     {
         ExtTreeNode notFoundMsg = new ExtTreeNode();
         notFoundMsg.Text = ResourceService.GetString("MainWindow.Windows.ClassBrowser.NoResultsFound");
         notFoundMsg.AddTo(classBrowserTreeView);
     }
     classBrowserTreeView.Sort();
     classBrowserTreeView.EndUpdate();
 }
Ejemplo n.º 16
0
        ArrayList SearchClasses(string text)
        {
            ArrayList list = new ArrayList();

            if (ProjectService.OpenSolution != null)
            {
                foreach (IProject project in ProjectService.OpenSolution.Projects)
                {
                    IProjectContent projectContent = ParserService.GetProjectContent(project);
                    if (projectContent != null)
                    {
                        AddClasses(text, list, projectContent.Classes);
                    }
                }
            }
            return(list);
        }
        protected override void ConvertAst(CompilationUnit compilationUnit, List <ISpecial> specials, FileProjectItem sourceItem)
        {
            PreprocessingDirective.VBToCSharp(specials);
            CompilableProject project = (CompilableProject)sourceItem.Project;

            RemoveWindowsFormsSpecificCode(compilationUnit, specials, project.OutputType == OutputType.WinExe);

            IProjectContent             pc      = ParserService.GetProjectContent(sourceItem.Project) ?? ParserService.CurrentProjectContent;
            VBNetToCSharpConvertVisitor visitor = new VBNetToCSharpConvertVisitorWithMyFormsSupport(pc, ParserService.GetParseInformation(sourceItem.FileName), sourceItem.Project.RootNamespace);

            // set project options
            visitor.OptionInfer = (project.GetEvaluatedProperty("OptionInfer") ?? "Off")
                                  .Equals("On", StringComparison.OrdinalIgnoreCase);
            visitor.OptionStrict = (project.GetEvaluatedProperty("OptionStrict") ?? "Off")
                                   .Equals("On", StringComparison.OrdinalIgnoreCase);

            compilationUnit.AcceptVisitor(visitor, null);
        }
Ejemplo n.º 18
0
        public static IList <IClass> GetPossibleStartupObjects(IProject project)
        {
            List <IClass>   results = new List <IClass>();
            IProjectContent pc      = ParserService.GetProjectContent(project);

            if (pc != null)
            {
                foreach (IClass c in pc.Classes)
                {
                    foreach (IMethod m in c.Methods)
                    {
                        if (m.IsStatic && m.Name == "Main")
                        {
                            results.Add(c);
                        }
                    }
                }
            }
            return(results);
        }
Ejemplo n.º 19
0
        string CreateFilterFile()
        {
            var classFilterBuilder = new ClassFilterBuilder();
            var projectContent     = ParserService.GetProjectContent(project);
            var filter             = classFilterBuilder.BuildFilterFor(tests, @using: projectContent);

            string path = null;

            if (filter.Count > 0)
            {
                path = Path.GetTempFileName();
                using (var stream = new FileStream(path, FileMode.Create, FileAccess.Write))
                    using (var writer = new StreamWriter(stream))
                        foreach (var testClassName in filter)
                        {
                            writer.WriteLine(testClassName);
                        }
            }
            return(path);
        }
Ejemplo n.º 20
0
        protected override void Initialize()
        {
            base.Initialize();
            IProjectContent projectContent = ParserService.GetProjectContent(Project);

            if (projectContent != null)
            {
                Nodes.Clear();
                ReferenceFolderNode referencesNode = new ReferenceFolderNode(Project);
                referencesNode.AddTo(this);
                projectContent.ReferencedContentsChanged += delegate { WorkbenchSingleton.SafeThreadAsyncCall(referencesNode.UpdateReferenceNodes); };
                foreach (ProjectItem item in Project.GetItemsOfType(ItemType.Compile))
                {
                    ParseInformation parseInformation = ParserService.GetParseInformation(item.FileName);
                    if (parseInformation != null)
                    {
                        InsertParseInformation(parseInformation.BestCompilationUnit as ICompilationUnit);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        public override void Run()
        {
            IProject p        = ProjectService.CurrentProject;
            string   filename = Path.Combine(p.Directory, p.Name + ".cd");

            if (p == null)
            {
                return;
            }

            /*if (p.IsFileInProject(filename))
             * {
             *      ProjectItem pi = p.Items.Find(
             *              delegate(ProjectItem pItem)
             *              { return pItem.FileName == filename; }
             *      );
             * }
             * else*/
            {
                //MessageBox.Show("Creating a new class diagram file named "+"\"+p.Directory+filename);
                ClassCanvas classcanvas = new ClassCanvas();

                IProjectContent pc = ParserService.GetProjectContent(p);
                //float x = 20, y = 20;
                //float max_h = 0;

                foreach (IClass ct in pc.Classes)
                {
                    ClassCanvasItem classitem = ClassCanvas.CreateItemFromType(ct);
                    classcanvas.AddCanvasItem(classitem);
                }

                classcanvas.AutoArrange();
                XmlDocument xmlDocument = classcanvas.WriteToXml();
                FileUtility.ObservedSave(
                    newFileName => SaveAndOpenNewClassDiagram(p, newFileName, xmlDocument),
                    filename, FileErrorPolicy.ProvideAlternative
                    );
            }
        }
        protected override void Initialize()
        {
            ProjectItems   = new ObservableCollection <string>();
            NameSpaceItems = new ObservableCollection <string> ();

            foreach (ProjectItem item in base.Project.Items)
            {
                if (item.ItemType == ItemType.Import)
                {
                    ProjectItems.Add(item.Include);
                }
            }


            IProjectContent projectContent = ParserService.GetProjectContent(base.Project);

            foreach (IProjectContent refProjectContent in projectContent.ThreadSafeGetReferencedContents())
            {
                AddNamespaces(refProjectContent);
            }
            AddNamespaces(projectContent);
        }
Ejemplo n.º 23
0
        IEnumerable <string> GetUnitTestNames(SelectedTests selectedTests)
        {
            IProjectContent content = ParserService.GetProjectContent(selectedTests.Project);

            if (selectedTests.Class == null)
            {
                var testClasses = content.Classes
                                  .Where(c => c.Attributes.Any(a => a.AttributeType.FullyQualifiedName == "NUnit.Framework.TestFixtureAttribute"));
                return(testClasses
                       .SelectMany(c2 => c2.Methods)
                       .Where(m => m.Attributes.Any(a2 => a2.AttributeType.FullyQualifiedName == "NUnit.Framework.TestAttribute"))
                       .Select(m2 => m2.FullyQualifiedName));
            }

            if (selectedTests.Member == null)
            {
                return(content.Classes.First(c => c.FullyQualifiedName == selectedTests.Class.DotNetName).Methods
                       .Where(m => m.Attributes.Any(a2 => a2.AttributeType.FullyQualifiedName == "NUnit.Framework.TestAttribute"))
                       .Select(m2 => m2.FullyQualifiedName));
            }

            return(new[] { selectedTests.Class.DotNetName + "." + selectedTests.Member.Name });
        }
        IEnumerable <string> GetUnitTestNames(UnitTestApplicationStartHelper helper)
        {
            IProjectContent content = ParserService.GetProjectContent(helper.Project);

            if (helper.Fixture == null)
            {
                var testClasses = content.Classes
                                  .Where(c => c.Attributes.Any(a => a.AttributeType.FullyQualifiedName == "NUnit.Framework.TestFixtureAttribute"));
                return(testClasses
                       .SelectMany(c2 => c2.Methods)
                       .Where(m => m.Attributes.Any(a2 => a2.AttributeType.FullyQualifiedName == "NUnit.Framework.TestAttribute"))
                       .Select(m2 => m2.FullyQualifiedName));
            }

            if (helper.Test == null)
            {
                return(content.Classes
                       .Where(c => c.FullyQualifiedName == helper.Fixture).First().Methods
                       .Where(m => m.Attributes.Any(a2 => a2.AttributeType.FullyQualifiedName == "NUnit.Framework.TestAttribute"))
                       .Select(m2 => m2.FullyQualifiedName));
            }

            return(new[] { helper.Fixture + "." + helper.Test });
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Returns the project content for the specified project.
 /// </summary>
 public virtual IProjectContent GetProjectContent(IProject project)
 {
     return(ParserService.GetProjectContent(project));
 }
        public override bool Extract()
        {
            using (var parser = ParserFactory.CreateParser(SupportedLanguage.CSharp, new StringReader("class Tmp { void Test() {\n " + this.textEditor.SelectedText + "\n}}"))) {
                parser.Parse();

                if (parser.Errors.Count > 0)
                {
                    MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ParseErrors}");

                    return(false);
                }

                this.specialsList = parser.Lexer.SpecialTracker.RetrieveSpecials();
            }

            this.currentProjectContent = ParserService.GetProjectContent(ProjectService.CurrentProject);

            MethodDeclaration          newMethod            = new MethodDeclaration();
            List <VariableDeclaration> possibleReturnValues = new List <VariableDeclaration>();
            List <VariableDeclaration> otherReturnValues    = new List <VariableDeclaration>();

            // Initialise new method
            newMethod.Body = GetBlock(this.textEditor.SelectedText);
            newMethod.Body.StartLocation = new Location(0, 0);

            this.parentNode = GetParentMember(start, end);

            Dom.IMember member = GetParentMember(textEditor, textEditor.Caret.Line, textEditor.Caret.Column);

            if (parentNode == null || member == null)
            {
                MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.InvalidSelection}");
                return(false);
            }

            this.currentClass = member.DeclaringType;

            ErrorKind kind = CheckForJumpInstructions(newMethod);

            if (kind != ErrorKind.None)
            {
                switch (kind)
                {
                case ErrorKind.ContainsBreak:
                    MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsBreakError}");
                    break;

                case ErrorKind.ContainsContinue:
                    MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsContinueError}");
                    break;

                case ErrorKind.ContainsGoto:
                    MessageService.ShowError("${res:AddIns.SharpRefactoring.ExtractMethod.ContainsGotoError}");
                    break;
                }
                return(false);
            }

            newMethod.Modifier = parentNode.Modifier;

            newMethod.Modifier &= ~(Modifiers.Internal | Modifiers.Protected | Modifiers.Private | Modifiers.Public | Modifiers.Override);

            LookupTableVisitor ltv = new LookupTableVisitor(SupportedLanguage.CSharp);

            parentNode.AcceptVisitor(ltv, null);

            var variablesList = (from list in ltv.Variables.Values from item in list select new Variable(item))
                                .Where(v => !(v.StartPos > end || v.EndPos < start) &&
                                       (HasReferencesInSelection(newMethod, v) ||
                                        HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, v.Name, v.StartPos, v.EndPos)))
                                .Union(FromParameters(newMethod))
                                .Select(va => ResolveVariable(va));

            foreach (var variable in variablesList)
            {
                LoggingService.Debug(variable);

                bool hasOccurrencesAfter = HasOccurrencesAfter(CSharpNameComparer, this.parentNode, end, variable.Name, variable.StartPos, variable.EndPos);
                bool isInitialized       = (variable.Initializer != null) ? !variable.Initializer.IsNull : false;
                bool hasAssignment       = HasAssignment(newMethod, variable);

                if (IsInCurrentSelection(variable.StartPos) && hasOccurrencesAfter)
                {
                    possibleReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
                    otherReturnValues.Add(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type));
                }

                if (!(IsInCurrentSelection(variable.StartPos) || IsInCurrentSelection(variable.EndPos)))
                {
                    ParameterDeclarationExpression newParam = null;

                    if ((hasOccurrencesAfter && isInitialized) || variable.WasRefParam)
                    {
                        newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Ref);
                    }
                    else
                    {
                        if ((hasOccurrencesAfter && hasAssignment) || variable.WasOutParam)
                        {
                            newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.Out);
                        }
                        else
                        {
                            if (!hasOccurrencesAfter)
                            {
                                newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.None);
                            }
                            else
                            {
                                if (!hasOccurrencesAfter && !isInitialized)
                                {
                                    newMethod.Body.Children.Insert(0, new LocalVariableDeclaration(new VariableDeclaration(variable.Name, variable.Initializer, variable.Type)));
                                }
                                else
                                {
                                    newParam = new ParameterDeclarationExpression(variable.Type, variable.Name, ParameterModifiers.In);
                                }
                            }
                        }
                    }
                    if (newParam != null)
                    {
                        newMethod.Parameters.Add(newParam);
                    }
                }
            }

            List <VariableDeclaration> paramsAsVarDecls = new List <VariableDeclaration>();

            this.beforeCallDeclarations = new List <LocalVariableDeclaration>();

            for (int i = 0; i < otherReturnValues.Count - 1; i++)
            {
                VariableDeclaration varDecl = otherReturnValues[i];
                paramsAsVarDecls.Add(varDecl);
                ParameterDeclarationExpression p = new ParameterDeclarationExpression(varDecl.TypeReference, varDecl.Name);
                p.ParamModifier = ParameterModifiers.Out;
                if (!newMethod.Parameters.Contains(p))
                {
                    newMethod.Parameters.Add(p);
                }
                else
                {
                    this.beforeCallDeclarations.Add(new LocalVariableDeclaration(varDecl));
                }
            }

            CreateReturnStatement(newMethod, possibleReturnValues);

            newMethod.Name = "NewMethod";

            this.extractedMethod = newMethod;

            return(true);
        }
        void ProjectTreeScanningBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            if (this.project == null)
            {
                return;
            }

            ProjectResourceInfo selectedProjectResource = e.Argument as ProjectResourceInfo;

            IProjectContent projectContent = ParserService.GetProjectContent(this.project);

            TreeNode root           = new TreeNode(this.project.Name, 0, 0);
            TreeNode preSelection   = null;
            TreeNode lastFileNode   = null;
            int      fileNodesCount = 0;

            foreach (FileProjectItem item in this.project.GetItemsOfType(ItemType.EmbeddedResource).OfType <FileProjectItem>().OrderBy(fpi => Path.GetFileName(fpi.VirtualName)))
            {
                if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                // Skip files where the generated class name
                // would conflict with an existing class.
                string namespaceName = item.GetEvaluatedMetadata("CustomToolNamespace");
                if (string.IsNullOrEmpty(namespaceName))
                {
                    namespaceName = CustomToolsService.GetDefaultNamespace(item.Project, item.FileName);
                }
                IClass existingClass = projectContent.GetClass(namespaceName + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(item.FileName), projectContent.Language.CodeDomProvider), 0);
                if (existingClass != null)
                {
                    if (!ProjectResourceService.IsGeneratedResourceClass(existingClass))
                    {
                        continue;
                    }
                }

                bool     selectedFile = (selectedProjectResource != null) && FileUtility.IsEqualFileName(selectedProjectResource.ResourceFile, item.FileName);
                TreeNode file         = null;

                try {
                    foreach (KeyValuePair <string, object> r in this.GetResources(item.FileName).OrderBy(pair => pair.Key))
                    {
                        if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        if (file == null)
                        {
                            file = CreateAndAddFileNode(root, item);
                        }

                        TreeNode resNode = new TreeNode(r.Key, 3, 3);
                        resNode.Tag = r.Value;
                        file.Nodes.Add(resNode);

                        if (selectedFile)
                        {
                            if (String.Equals(r.Key, selectedProjectResource.ResourceKey, StringComparison.Ordinal))
                            {
                                preSelection = resNode;
                            }
                        }
                    }

                    if (file != null)
                    {
                        lastFileNode = file;
                        ++fileNodesCount;
                    }
                } catch (Exception ex) {
                    if (file == null)
                    {
                        file = CreateAndAddFileNode(root, item);
                    }
                    TreeNode error = new TreeNode(ex.Message, 4, 4);
                    file.Nodes.Add(error);
                }
            }

            if (e.Cancel)
            {
                DisposeNodeImages(root);
            }
            else
            {
                // Preselect the file node if there is only one
                if (preSelection == null && fileNodesCount == 1)
                {
                    preSelection = lastFileNode;
                }
                e.Result = new TreeScanResult(root, preSelection);
            }
        }
Ejemplo n.º 28
0
        internal static string BuildMyNamespaceCode(CompilableProject vbProject)
        {
            string ns;

            if (string.IsNullOrEmpty(vbProject.RootNamespace))
            {
                ns = "My";
            }
            else
            {
                ns = vbProject.RootNamespace + ".My";
            }

            string projectType;

            if (vbProject.OutputType == OutputType.WinExe)
            {
                projectType = "WindowsApplication";
            }
            else if (vbProject.OutputType == OutputType.Exe)
            {
                projectType = "ConsoleApplication";
            }
            else
            {
                projectType = "Library";
            }

            StringBuilder output       = new StringBuilder();
            bool          outputActive = true;

            using (StreamReader r = new StreamReader(OpenResource())) {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    string trimmedLine = line.Trim();
                    if (trimmedLine == "#endif")
                    {
                        outputActive = true;
                        continue;
                    }
                    if (!outputActive)
                    {
                        continue;
                    }
                    if (trimmedLine == "/*LIST OF FORMS*/")
                    {
                        IClass myFormsClass = FindMyFormsClass(ParserService.GetProjectContent(vbProject), ns);
                        if (myFormsClass != null)
                        {
                            string indentation = line.Substring(0, line.Length - trimmedLine.Length);
                            foreach (IProperty p in myFormsClass.Properties)
                            {
                                string typeName = "global::" + p.ReturnType.FullyQualifiedName;
                                output.AppendLine(indentation + typeName + " " + p.Name + "_instance;");
                                output.AppendLine(indentation + "bool " + p.Name + "_isCreating;");
                                output.AppendLine(indentation + "public " + typeName + " " + p.Name + " {");
                                output.AppendLine(indentation + "\t[DebuggerStepThrough] get { return GetForm(ref " + p.Name + "_instance, ref " + p.Name + "_isCreating); }");
                                output.AppendLine(indentation + "\t[DebuggerStepThrough] set { SetForm(ref " + p.Name + "_instance, value); }");
                                output.AppendLine(indentation + "}");
                                output.AppendLine(indentation);
                            }
                        }
                    }
                    else if (trimmedLine.StartsWith("#if "))
                    {
                        outputActive = trimmedLine.Substring(4) == projectType;
                    }
                    else
                    {
                        output.AppendLine(StringParser.Parse(line.Replace("MyNamespace", ns)));
                    }
                }
            }
            return(output.ToString());
        }
        public void GenerateCode(FileProjectItem item, CustomToolContext context)
        {
            /*context.GenerateCodeDomAsync(item, context.GetOutputFileName(item, ".Designer"),
             *                           delegate {
             *                              return GenerateCodeDom();
             *                           });*/
            string inputFilePath = item.FileName;

            // Ensure that the generated code will not conflict with an
            // existing class.
            if (context.Project != null)
            {
                IProjectContent pc = ParserService.GetProjectContent(context.Project);
                if (pc != null)
                {
                    IClass existingClass = pc.GetClass(context.OutputNamespace + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(inputFilePath), pc.Language.CodeDomProvider), 0);
                    if (existingClass != null)
                    {
                        if (!IsGeneratedResourceClass(existingClass))
                        {
                            context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.ClassConflict"), inputFilePath, existingClass.FullyQualifiedName));
                            return;
                        }
                    }
                }
            }

            IResourceReader reader;

            if (string.Equals(Path.GetExtension(inputFilePath), ".resx", StringComparison.OrdinalIgnoreCase))
            {
                reader = new ResXResourceReader(inputFilePath);
                ((ResXResourceReader)reader).BasePath = Path.GetDirectoryName(inputFilePath);
            }
            else
            {
                reader = new ResourceReader(inputFilePath);
            }

            Hashtable resources = new Hashtable();

            foreach (DictionaryEntry de in reader)
            {
                resources.Add(de.Key, de.Value);
            }

            string[] unmatchable = null;

            context.WriteCodeDomToFile(
                item,
                context.GetOutputFileName(item, ".Designer"),
                StronglyTypedResourceBuilder.Create(
                    resources,                                          // resourceList
                    Path.GetFileNameWithoutExtension(inputFilePath),    // baseName
                    context.OutputNamespace,                            // generatedCodeNamespace
                    context.OutputNamespace,                            // resourcesNamespace
                    context.Project.LanguageProperties.CodeDomProvider, // codeProvider
                    createInternalClass,                                // internal class
                    out unmatchable
                    ));

            foreach (string s in unmatchable)
            {
                context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.CouldNotGenerateResourceProperty"), s));
            }
        }
Ejemplo n.º 30
0
            void AppendError(string file, int lineNumber, int columnNumber,
                             string message, bool isWarning,
                             string category, string checkId, string subcategory)
            {
                LoggingService.Debug("Got " + (isWarning ? "warning" : "error") + ":\n"
                                     + "  file: " + file + "\n"
                                     + "  line: " + lineNumber + ", col: " + columnNumber + "\n"
                                     + "  message: " + message + "\n"
                                     + "  category: " + category + "\n"
                                     + "  checkId: " + checkId + "\n"
                                     + "  subcategory: " + subcategory);

                string[]   moreData = (subcategory ?? "").Split('|');
                BuildError err      = engineWorker.CurrentErrorOrWarning;

                err.ErrorCode = (checkId != null) ? checkId.Split(':')[0] : null;
                if (FileUtility.IsValidPath(file) &&
                    Path.GetFileName(file) == "SharpDevelop.CodeAnalysis.targets")
                {
                    err.FileName = null;
                }
                IProject project = ProjectService.GetProject(engineWorker.CurrentProjectFile);

                if (project != null)
                {
                    IProjectContent pc = ParserService.GetProjectContent(project);
                    if (pc != null)
                    {
                        if (file.StartsWith("positionof#"))
                        {
                            string memberName = file.Substring(11);
                            file = "";
                            FilePosition pos = GetPosition(pc, memberName);
                            if (pos.IsEmpty == false && pos.CompilationUnit != null)
                            {
                                err.FileName = pos.FileName ?? "";
                                err.Line     = pos.Line;
                                err.Column   = pos.Column;
                            }
                            else
                            {
                                err.FileName = null;
                            }
                        }

                        if (moreData.Length > 1 && !string.IsNullOrEmpty(moreData[0]))
                        {
                            err.Tag = new FxCopTaskTag {
                                ProjectContent = pc,
                                TypeName       = moreData[0],
                                MemberName     = moreData[1],
                                Category       = category,
                                CheckID        = checkId
                            };
                        }
                        else
                        {
                            err.Tag = new FxCopTaskTag {
                                ProjectContent = pc,
                                Category       = category,
                                CheckID        = checkId
                            };
                        }
                        err.ContextMenuAddInTreeEntry = "/SharpDevelop/Pads/ErrorList/CodeAnalysisTaskContextMenu";
                        if (moreData.Length > 2)
                        {
                            (err.Tag as FxCopTaskTag).MessageID = moreData[2];
                        }
                    }
                }
            }