Пример #1
0
        void ShowDotCompletion(string currentText)
        {
            StackFrame frame = this.process.GetCurrentExecutingFrame();

            if (frame == null)
            {
                return;
            }

            var seg = frame.NextStatement;

            if (seg == null)
            {
                return;
            }

            var expressionFinder = ParserService.GetExpressionFinder(seg.Filename);
            var info             = ParserService.GetParseInformation(seg.Filename);

            string text = ParserService.GetParseableFileContent(seg.Filename).Text;

            int currentOffset = TextEditor.Caret.Offset - console.CommandOffset - 1;

            var expr = expressionFinder.FindExpression(currentText, currentOffset);

            expr.Region = new DomRegion(seg.StartLine, seg.StartColumn, seg.EndLine, seg.EndColumn);

            var rr = resolver.Resolve(expr, info, text);

            if (rr != null)
            {
                TextEditor.ShowCompletionWindow(new DotCodeCompletionItemProvider().GenerateCompletionListForResolveResult(rr, expr.Context));
            }
        }
Пример #2
0
        public static void ShowAsSearchResults(string title, List <Reference> list)
        {
            if (list == null)
            {
                return;
            }
            List <SearchResultMatch> results  = new List <SearchResultMatch>(list.Count);
            TextDocument             document = null;
            ITextBuffer        buffer         = null;
            FileName           fileName       = null;
            ISyntaxHighlighter highlighter    = null;

            foreach (Reference r in list)
            {
                var f = new FileName(r.FileName);
                if (document == null || !f.Equals(fileName))
                {
                    buffer      = ParserService.GetParseableFileContent(r.FileName);
                    document    = new TextDocument(DocumentUtilitites.GetTextSource(buffer));
                    fileName    = new FileName(r.FileName);
                    highlighter = EditorControlService.Instance.CreateHighlighter(new AvalonEditDocumentAdapter(document, null), fileName);
                }
                var start             = document.GetLocation(r.Offset).ToLocation();
                var end               = document.GetLocation(r.Offset + r.Length).ToLocation();
                var builder           = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter);
                SearchResultMatch res = new SearchResultMatch(fileName, start, end, r.Offset, r.Length, builder, highlighter.DefaultTextColor);
                results.Add(res);
            }
            SearchResultsPad.Instance.ShowSearchResults(title, results);
            SearchResultsPad.Instance.BringToFront();
        }
        /// <summary>
        /// Determines if the property is a so-called auto-implemented property.
        /// </summary>
        public static bool IsAutoImplemented(this IProperty property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (property.IsAbstract || property.DeclaringType.ClassType == ICSharpCode.SharpDevelop.Dom.ClassType.Interface)
            {
                return(false);
            }

            string fileName = property.CompilationUnit.FileName;

            if (fileName == null)
            {
                return(false);
            }

            IDocument document    = DocumentUtilitites.LoadDocumentFromBuffer(ParserService.GetParseableFileContent(fileName));
            bool      isAutomatic = false;

            if (property.CanGet)
            {
                if (property.GetterRegion.IsEmpty)
                {
                    isAutomatic = true;
                }
                else
                {
                    int getterStartOffset = document.PositionToOffset(property.GetterRegion.BeginLine, property.GetterRegion.BeginColumn);
                    int getterEndOffset   = document.PositionToOffset(property.GetterRegion.EndLine, property.GetterRegion.EndColumn);

                    string text = document.GetText(getterStartOffset, getterEndOffset - getterStartOffset)
                                  .Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");

                    isAutomatic = text == "get;";
                }
            }

            if (property.CanSet)
            {
                if (property.SetterRegion.IsEmpty)
                {
                    isAutomatic |= true;
                }
                else
                {
                    int setterStartOffset = document.PositionToOffset(property.SetterRegion.BeginLine, property.SetterRegion.BeginColumn);
                    int setterEndOffset   = document.PositionToOffset(property.SetterRegion.EndLine, property.SetterRegion.EndColumn);

                    string text = document.GetText(setterStartOffset, setterEndOffset - setterStartOffset)
                                  .Replace(" ", "").Replace("\t", "").Replace("\n", "").Replace("\r", "");

                    isAutomatic |= text == "set;";
                }
            }

            return(isAutomatic);
        }
Пример #4
0
        Report GetReport(string filename)
        {
            if (!File.Exists(filename))
            {
                return(null);
            }

            return(GetReport(filename, new StringReader(ParserService.GetParseableFileContent(filename))));
        }
Пример #5
0
        protected void ConvertFile(FileProjectItem sourceItem, FileProjectItem targetItem,
                                   string sourceExtension, string targetExtension,
                                   SupportedLanguage sourceLanguage, IOutputAstVisitor outputVisitor)
        {
            FixExtensionOfExtraProperties(targetItem, sourceExtension, targetExtension);
            if (sourceExtension.Equals(Path.GetExtension(sourceItem.FileName), StringComparison.OrdinalIgnoreCase))
            {
                string  code = ParserService.GetParseableFileContent(sourceItem.FileName);
                IParser p    = ParserFactory.CreateParser(sourceLanguage, new StringReader(code));
                p.Parse();
                if (p.Errors.Count > 0)
                {
                    conversionLog.AppendLine();
                    conversionLog.AppendLine(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.Convert.IsNotConverted}",
                                                                new string[, ] {
                        { "FileName", sourceItem.FileName }
                    }));
                    conversionLog.AppendLine(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.Convert.ParserErrorCount}",
                                                                new string[, ] {
                        { "ErrorCount", p.Errors.Count.ToString() }
                    }));
                    conversionLog.AppendLine(p.Errors.ErrorOutput);
                    base.ConvertFile(sourceItem, targetItem);
                    return;
                }

                List <ISpecial> specials = p.Lexer.SpecialTracker.CurrentSpecials;

                ConvertAst(p.CompilationUnit, specials, sourceItem);

                using (SpecialNodesInserter.Install(specials, outputVisitor)) {
                    outputVisitor.VisitCompilationUnit(p.CompilationUnit, null);
                }

                p.Dispose();

                if (outputVisitor.Errors.Count > 0)
                {
                    conversionLog.AppendLine();
                    conversionLog.AppendLine(StringParser.Parse("${res:ICSharpCode.SharpDevelop.Commands.Convert.ConverterErrorCount}",
                                                                new string[, ] {
                        { "FileName", sourceItem.FileName },
                        { "ErrorCount", outputVisitor.Errors.Count.ToString() }
                    }));
                    conversionLog.AppendLine(outputVisitor.Errors.ErrorOutput);
                }

                targetItem.Include = Path.ChangeExtension(targetItem.Include, targetExtension);
                File.WriteAllText(targetItem.FileName, outputVisitor.Text);
            }
            else
            {
                base.ConvertFile(sourceItem, targetItem);
            }
        }
 public static string GetParsableFileContent(string fileName)
 {
     if (fileContents == null)
     {
         return(ParserService.GetParseableFileContent(fileName));
     }
     else
     {
         return(fileContents[fileName]);
     }
 }
        public static ProvidedDocumentInformation GetDocumentInformation(string fileName)
        {
            OpenedFile file = FileService.GetOpenedFile(fileName);

            if (file != null)
            {
                IFileDocumentProvider documentProvider = file.CurrentView as IFileDocumentProvider;
                if (documentProvider != null)
                {
                    IDocument document = documentProvider.GetDocumentForFile(file);
                    if (document != null)
                    {
                        return(new ProvidedDocumentInformation(document, fileName, 0));
                    }
                }
            }
            ITextBuffer fileContent = ParserService.GetParseableFileContent(fileName);

            return(new ProvidedDocumentInformation(fileContent, fileName, 0));
        }
        private void ShowDotCompletion(string currentText)
        {
            var seg = Breakpoint;

            var expressionFinder = ParserService.GetExpressionFinder(seg.FileName.ToString());
            var info             = ParserService.GetParseInformation(seg.FileName.ToString());

            string text = ParserService.GetParseableFileContent(seg.FileName.ToString()).Text;

            int currentOffset = TextEditor.Caret.Offset - console.CommandOffset - 1;

            var expr = expressionFinder.FindExpression(currentText, currentOffset);

            expr.Region = new DomRegion(seg.LineNumber, seg.ColumnNumber, seg.LineNumber, seg.ColumnNumber);

            var rr = resolver.Resolve(expr, info, text);

            if (rr != null)
            {
                TextEditor.ShowCompletionWindow(new DotCodeCompletionItemProvider().GenerateCompletionListForResolveResult(rr, expr.Context));
            }
        }
        public static void ShowAsSearchResults(string title, List <Reference> list)
        {
            if (list == null)
            {
                return;
            }
            List <SearchResultMatch> results  = new List <SearchResultMatch>(list.Count);
            TextDocument             document = null;
            FileName     fileName             = null;
            IHighlighter highlighter          = null;

            foreach (Reference r in list)
            {
                var f = new FileName(r.FileName);
                if (document == null || !f.Equals(fileName))
                {
                    document = new TextDocument(DocumentUtilitites.GetTextSource(ParserService.GetParseableFileContent(r.FileName)));
                    fileName = new FileName(r.FileName);
                    var def = HighlightingManager.Instance.GetDefinitionByExtension(Path.GetExtension(r.FileName));
                    if (def != null)
                    {
                        highlighter = new DocumentHighlighter(document, def.MainRuleSet);
                    }
                    else
                    {
                        highlighter = null;
                    }
                }
                var start             = document.GetLocation(r.Offset).ToLocation();
                var end               = document.GetLocation(r.Offset + r.Length).ToLocation();
                var builder           = SearchResultsPad.CreateInlineBuilder(start, end, document, highlighter);
                SearchResultMatch res = new SearchResultMatch(fileName, start, end, r.Offset, r.Length, builder);
                results.Add(res);
            }
            SearchResultsPad.Instance.ShowSearchResults(title, results);
            SearchResultsPad.Instance.BringToFront();
        }
        public static void MoveClassToFile(IClass c, string newFileName)
        {
            LanguageProperties language     = c.ProjectContent.Language;
            string             existingCode = ParserService.GetParseableFileContent(c.CompilationUnit.FileName).Text;
            DomRegion          fullRegion   = language.RefactoringProvider.GetFullCodeRangeForType(existingCode, c);

            if (fullRegion.IsEmpty)
            {
                return;
            }

            Action removeExtractedCodeAction;
            string newCode = ExtractCode(c, fullRegion, c.BodyRegion.BeginLine, out removeExtractedCodeAction);

            newCode = language.RefactoringProvider.CreateNewFileLikeExisting(existingCode, newCode);
            if (newCode == null)
            {
                return;
            }
            IViewContent viewContent = FileService.NewFile(newFileName, newCode);

            viewContent.PrimaryFile.SaveToDisk(newFileName);
            // now that the code is saved in the other file, remove it from the original document
            removeExtractedCodeAction();

            IProject project = (IProject)c.ProjectContent.Project;

            if (project != null)
            {
                FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
                projectItem.FileName = newFileName;
                ProjectService.AddProjectItem(project, projectItem);
                FileService.FireFileCreated(newFileName, false);
                project.Save();
                ProjectBrowserPad.RefreshViewAsync();
            }
        }
Пример #11
0
        protected override void ConvertFile(FileProjectItem sourceItem, FileProjectItem targetItem)
        {
            FixExtensionOfExtraProperties(targetItem, ".cs", ".boo");
            FixExtensionOfExtraProperties(targetItem, ".vb", ".boo");

            string ext = Path.GetExtension(sourceItem.FileName);

            if (".cs".Equals(ext, StringComparison.OrdinalIgnoreCase) || ".vb".Equals(ext, StringComparison.OrdinalIgnoreCase))
            {
                Module module;
                IList <ICSharpCode.NRefactory.ISpecial> specials;
                CompileUnit compileUnit = new CompileUnit();
                using (StringReader r = new StringReader(ParserService.GetParseableFileContent(sourceItem.FileName))) {
                    module = Parser.ParseModule(compileUnit, r, ConvertBuffer.ApplySettings(sourceItem.VirtualName, errors, warnings), out specials);
                }
                if (module == null)
                {
                    conversionLog.AppendLine("Could not parse '" + sourceItem.FileName + "', see error list for details.");
                    base.ConvertFile(sourceItem, targetItem);
                }
                else
                {
                    using (StringWriter w = new StringWriter()) {
                        BooPrinterVisitorWithComments printer = new BooPrinterVisitorWithComments(specials, w);
                        printer.OnModule(module);
                        printer.Finish();

                        targetItem.Include = Path.ChangeExtension(targetItem.Include, ".boo");
                        File.WriteAllText(targetItem.FileName, w.ToString());
                    }
                }
            }
            else
            {
                base.ConvertFile(sourceItem, targetItem);
            }
        }
        public static void ExtractInterface(IClass c)
        {
            ExtractInterfaceOptions extractInterface = new ExtractInterfaceOptions(c);

            using (ExtractInterfaceDialog eid = new ExtractInterfaceDialog()) {
                extractInterface = eid.ShowDialog(extractInterface);
                if (extractInterface.IsCancelled)
                {
                    return;
                }

                // do rename

                /*
                 * MessageService.ShowMessageFormatted("Extracting interface",
                 *                                  @"Extracting {0} [{1}] from {2} into {3}",
                 *                                  extractInterface.NewInterfaceName,
                 *                                  extractInterface.FullyQualifiedName,
                 *                                  extractInterface.ClassEntity.Name,
                 *                                  extractInterface.NewFileName
                 *                                 );
                 * `				*/
            }

            string newInterfaceFileName = Path.Combine(Path.GetDirectoryName(c.CompilationUnit.FileName),
                                                       extractInterface.NewFileName);

            if (File.Exists(newInterfaceFileName))
            {
                int confirmReplace = MessageService.ShowCustomDialog("Extract Interface",
                                                                     newInterfaceFileName + " already exists!",
                                                                     0,
                                                                     1,
                                                                     "${res:Global.ReplaceButtonText}",
                                                                     "${res:Global.AbortButtonText}");
                if (confirmReplace != 0)
                {
                    return;
                }
            }

            LanguageProperties language          = c.ProjectContent.Language;
            string             classFileName     = c.CompilationUnit.FileName;
            string             existingClassCode = ParserService.GetParseableFileContent(classFileName).Text;

            // build the new interface...
            string newInterfaceCode = language.RefactoringProvider.GenerateInterfaceForClass(extractInterface.NewInterfaceName,
                                                                                             existingClassCode,
                                                                                             extractInterface.ChosenMembers,
                                                                                             c, extractInterface.IncludeComments);

            if (newInterfaceCode == null)
            {
                return;
            }

            // ...dump it to a file...
            IViewContent        viewContent = FileService.GetOpenFile(newInterfaceFileName);
            ITextEditorProvider editable    = viewContent as ITextEditorProvider;

            if (viewContent != null && editable != null)
            {
                // simply update it
                editable.TextEditor.Document.Text = newInterfaceCode;
                viewContent.PrimaryFile.SaveToDisk();
            }
            else
            {
                // create it
                viewContent = FileService.NewFile(newInterfaceFileName, newInterfaceCode);
                viewContent.PrimaryFile.SaveToDisk(newInterfaceFileName);

                // ... and add it to the project
                IProject project = (IProject)c.ProjectContent.Project;
                if (project != null)
                {
                    FileProjectItem projectItem = new FileProjectItem(project, ItemType.Compile);
                    projectItem.FileName = newInterfaceFileName;
                    ProjectService.AddProjectItem(project, projectItem);
                    FileService.FireFileCreated(newInterfaceFileName, false);
                    project.Save();
                    ProjectBrowserPad.RefreshViewAsync();
                }
            }

            ICompilationUnit newCompilationUnit = ParserService.ParseFile(newInterfaceFileName).CompilationUnit;
            IClass           newInterfaceDef    = newCompilationUnit.Classes[0];

            // finally, add the interface to the base types of the class that we're extracting from
            if (extractInterface.AddInterfaceToClass)
            {
                string modifiedClassCode = language.RefactoringProvider.AddBaseTypeToClass(existingClassCode, c, newInterfaceDef);
                if (modifiedClassCode == null)
                {
                    return;
                }

                // TODO: replacing the whole text is not an option, we would loose all breakpoints/bookmarks.
                viewContent = FileService.OpenFile(classFileName);
                editable    = viewContent as ITextEditorProvider;
                if (editable == null)
                {
                    return;
                }
                editable.TextEditor.Document.Text = modifiedClassCode;
            }
        }
        // Steps to load the designer:
        // - Parse main file
        // - Find other files containing parts of the form
        // - Parse all files and look for fields (for controls) and InitializeComponents method
        // - Create CodeDom objects for fields and InitializeComponents statements
        // - If debug build and Ctrl pressed, output CodeDom to console
        // - Return CodeDom objects to the .NET designer
        protected override CodeCompileUnit Parse()
        {
            LoggingService.Debug("NRefactoryDesignerLoader.Parse()");

            lastTextContent = this.Generator.ViewContent.DesignerCodeFileContent;

            ParseInformation parseInfo = ParserService.GetParseInformation(this.Generator.ViewContent.DesignerCodeFile.FileName);

            IClass         formClass;
            bool           isFirstClassInFile;
            IList <IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile);

            const string missingReferenceMessage = "Your project is missing a reference to '${Name}' - please add it using 'Project > Add Reference'.";

            if (formClass.ProjectContent.GetClass("System.Drawing.Point", 0) == null)
            {
                throw new FormsDesignerLoadException(
                          StringParser.Parse(
                              missingReferenceMessage, new string[, ] {
                    { "Name", "System.Drawing" }
                }
                              ));
            }
            if (formClass.ProjectContent.GetClass("System.Windows.Forms.Form", 0) == null)
            {
                throw new FormsDesignerLoadException(
                          StringParser.Parse(
                              missingReferenceMessage, new string[, ] {
                    { "Name", "System.Windows.Forms" }
                }
                              ));
            }

            List <KeyValuePair <string, CompilationUnit> > compilationUnits = new List <KeyValuePair <string, CompilationUnit> >();
            bool foundInitMethod = false;

            foreach (IClass part in parts)
            {
                string fileName = part.CompilationUnit.FileName;
                if (fileName == null)
                {
                    continue;
                }
                bool found = false;
                foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits)
                {
                    if (FileUtility.IsEqualFileName(fileName, entry.Key))
                    {
                        found = true;
                        break;
                    }
                }
                if (found)
                {
                    continue;
                }

                ITextBuffer fileContent;
                if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.PrimaryFileName))
                {
                    fileContent = this.Generator.ViewContent.PrimaryFileContent;
                }
                else if (FileUtility.IsEqualFileName(fileName, this.Generator.ViewContent.DesignerCodeFile.FileName))
                {
                    fileContent = new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent);
                }
                else
                {
                    fileContent = ParserService.GetParseableFileContent(fileName);
                }

                ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, fileContent.CreateReader());
                p.Parse();
                if (p.Errors.Count > 0)
                {
                    throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput);
                }

                // Try to fix the type names to fully qualified ones
                FixTypeNames(p.CompilationUnit, part.CompilationUnit, ref foundInitMethod);
                compilationUnits.Add(new KeyValuePair <string, CompilationUnit>(fileName, p.CompilationUnit));
            }

            if (!foundInitMethod)
            {
                throw new FormsDesignerLoadException("The InitializeComponent method was not found. Designer cannot be loaded.");
            }

            CompilationUnit      combinedCu = new CompilationUnit();
            NamespaceDeclaration nsDecl     = new NamespaceDeclaration(formClass.Namespace);

            combinedCu.AddChild(nsDecl);
            TypeDeclaration formDecl = new TypeDeclaration(Modifiers.Public, null);

            nsDecl.AddChild(formDecl);
            formDecl.Name = formClass.Name;
            foreach (KeyValuePair <string, CompilationUnit> entry in compilationUnits)
            {
                foreach (object o in entry.Value.Children)
                {
                    TypeDeclaration td = o as TypeDeclaration;
                    if (td != null && td.Name == formDecl.Name)
                    {
                        foreach (INode node in td.Children)
                        {
                            formDecl.AddChild(node);
                        }
                        formDecl.BaseTypes.AddRange(td.BaseTypes);
                    }
                    if (o is NamespaceDeclaration)
                    {
                        foreach (object o2 in ((NamespaceDeclaration)o).Children)
                        {
                            td = o2 as TypeDeclaration;
                            if (td != null && td.Name == formDecl.Name)
                            {
                                foreach (INode node in td.Children)
                                {
                                    formDecl.AddChild(node);
                                }
                                formDecl.BaseTypes.AddRange(td.BaseTypes);
                            }
                        }
                    }
                }
            }

            CodeDomVisitor visitor = new CodeDomVisitor();

            visitor.EnvironmentInformationProvider = new ICSharpCode.SharpDevelop.Dom.NRefactoryResolver.NRefactoryInformationProvider(formClass.ProjectContent);
            visitor.VisitCompilationUnit(combinedCu, null);

            // output generated CodeDOM to the console :
                        #if DEBUG
            if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
            {
                CodeDomVerboseOutputGenerator outputGenerator = new CodeDomVerboseOutputGenerator();
                outputGenerator.GenerateCodeFromMember(visitor.codeCompileUnit.Namespaces[0].Types[0], Console.Out, null);
                this.CodeDomProvider.GenerateCodeFromCompileUnit(visitor.codeCompileUnit, Console.Out, null);
            }
                        #endif

            LoggingService.Debug("NRefactoryDesignerLoader.Parse() finished");

            if (!isFirstClassInFile)
            {
                MessageService.ShowWarning("The form must be the first class in the file in order for form resources be compiled correctly.\n" +
                                           "Please move other classes below the form class definition or move them to other files.");
            }

            return(visitor.codeCompileUnit);
        }
 static ITextBuffer GetFileContent(string fileName)
 {
     return(ParserService.GetParseableFileContent(fileName));
 }
 /// <summary>
 /// Creates a TextReader for the specified file.
 /// </summary>
 public TextReader Create(string fileName)
 {
     return(ParserService.GetParseableFileContent(fileName).CreateReader());
 }
        protected override CodeDomLocalizationModel GetCurrentLocalizationModelFromDesignedFile()
        {
            ParseInformation parseInfo = ParserService.ParseFile(this.Generator.ViewContent.DesignerCodeFile.FileName, new StringTextBuffer(this.Generator.ViewContent.DesignerCodeFileContent));

            IClass         formClass;
            bool           isFirstClassInFile;
            IList <IClass> parts = FindFormClassParts(parseInfo, out formClass, out isFirstClassInFile);

            foreach (string fileName in
                     parts.Select(p => p.CompilationUnit.FileName)
                     .Where(n => n != null)
                     .Distinct(StringComparer.OrdinalIgnoreCase))
            {
                ICSharpCode.NRefactory.IParser p = ICSharpCode.NRefactory.ParserFactory.CreateParser(language, ParserService.GetParseableFileContent(fileName).CreateReader());
                p.Parse();
                if (p.Errors.Count > 0)
                {
                    throw new FormsDesignerLoadException("Syntax errors in " + fileName + ":\r\n" + p.Errors.ErrorOutput);
                }

                FindLocalizationModelVisitor visitor = new FindLocalizationModelVisitor();
                p.CompilationUnit.AcceptVisitor(visitor, null);
                if (visitor.Model != CodeDomLocalizationModel.None)
                {
                    return(visitor.Model);
                }
            }

            return(CodeDomLocalizationModel.None);
        }
 /// <summary>
 /// Gets the content of the file from the parser service.
 /// </summary>
 protected virtual string GetParseableFileContent(string fileName)
 {
     return(ParserService.GetParseableFileContent(fileName).Text);
 }
        /// <summary>
        /// Gets the project resource from the specified expression.
        /// </summary>
        public ProjectResourceInfo GetProjectResource(CodePropertyReferenceExpression propRef)
        {
            CodeTypeReferenceExpression typeRef = propRef.TargetObject as CodeTypeReferenceExpression;

            if (typeRef == null)
            {
                LoggingService.Info("Target of possible project resources property reference is not a type reference, but " + propRef.TargetObject.ToString() + ".");
                return(null);
            }

            // Get the (generated) class where the resource is defined.
            IClass resourceClass = this.projectContent.GetClassByReflectionName(typeRef.Type.BaseType, true);

            if (resourceClass == null)
            {
                throw new InvalidOperationException("Could not find class for project resources: '" + typeRef.Type.BaseType + "'.");
            }

            if (resourceClass.CompilationUnit == null || resourceClass.CompilationUnit.FileName == null)
            {
                return(null);
            }

            // Make sure the class we have found is a generated resource class.
            if (!IsGeneratedResourceClass(resourceClass))
            {
                return(null);
            }

            // Get the name of the resource file based on the file that contains the generated class.
            string resourceFileName = Path.GetFileNameWithoutExtension(resourceClass.CompilationUnit.FileName);

            if (resourceFileName.EndsWith("Designer", StringComparison.OrdinalIgnoreCase))
            {
                resourceFileName = Path.GetFileNameWithoutExtension(resourceFileName);
            }
            resourceFileName = Path.Combine(Path.GetDirectoryName(resourceClass.CompilationUnit.FileName), resourceFileName);
            if (File.Exists(resourceFileName + ".resources"))
            {
                resourceFileName = resourceFileName + ".resources";
            }
            else if (File.Exists(resourceFileName + ".resx"))
            {
                resourceFileName = resourceFileName + ".resx";
            }
            else
            {
                throw new FileNotFoundException("Could not find the resource file for type '" + resourceClass.FullyQualifiedName + "'. Tried these file names: '" + resourceFileName + ".(resources|resx)'.");
            }

            // Get the property for the resource.
            IProperty prop = resourceClass.Properties.SingleOrDefault(p => p.Name == propRef.PropertyName);

            if (prop == null)
            {
                throw new InvalidOperationException("Property '" + propRef.PropertyName + "' not found in type '" + resourceClass.FullyQualifiedName + "'.");
            }

            if (!prop.CanGet)
            {
                throw new InvalidOperationException("Property '" + propRef.PropertyName + "' in type '" + resourceClass.FullyQualifiedName + "' does not have a getter.");
            }

            // Get the code of the resource class and
            // extract the resource key from the property.
            // This is necessary because the key may differ from the property name
            // if special characters are used.
            // It would be better if we could use a real code parser for this, but
            // that is not possible without getting dependent on the programming language.

            IDocument doc = new ICSharpCode.SharpDevelop.Editor.AvalonEdit.AvalonEditDocumentAdapter();

            doc.Text = ParserService.GetParseableFileContent(resourceClass.CompilationUnit.FileName).Text;

            int startOffset = doc.PositionToOffset(prop.GetterRegion.BeginLine, prop.GetterRegion.BeginColumn);
            int endOffset   = doc.PositionToOffset(prop.GetterRegion.EndLine, prop.GetterRegion.EndColumn);

            string code = doc.GetText(startOffset, endOffset - startOffset + 1);

            int index = code.IndexOf("ResourceManager", StringComparison.Ordinal);

            if (index == -1)
            {
                throw new InvalidOperationException("No reference to ResourceManager found in property getter of '" + prop.FullyQualifiedName + "'. Code: '" + code + "'");
            }

            index = code.IndexOf("Get", index, StringComparison.Ordinal);
            if (index == -1)
            {
                throw new InvalidOperationException("No call to Get... found in property getter of '" + prop.FullyQualifiedName + "'. Code: '" + code + "'");
            }

            index = code.IndexOf(this.StringLiteralDelimiter, index + 1, StringComparison.Ordinal);
            if (index == -1)
            {
                throw new InvalidOperationException("No string delimiter ('" + this.StringLiteralDelimiter + "') found in property getter of '" + prop.FullyQualifiedName + "'. Code: '" + code + "'");
            }
            index += this.StringLiteralDelimiter.Length;

            int endIndex = code.LastIndexOf(this.StringLiteralDelimiter, StringComparison.Ordinal);

            if (endIndex == -1)
            {
                throw new InvalidOperationException("No string terminator ('" + this.StringLiteralDelimiter + "') found in property getter of '" + prop.FullyQualifiedName + "'. Code: '" + code + "'");
            }

            string resourceKey = code.Substring(index, endIndex - index);

            LoggingService.Debug("-> Decoded resource: In: " + resourceFileName + ". Key: " + resourceKey);

            return(new ProjectResourceInfo(resourceFileName, resourceKey));
        }
Пример #19
0
        public static string GetFileContents(FileName fileName)
        {
            ITextBuffer fileContent = ParserService.GetParseableFileContent(fileName);

            return(fileContent.Text);
        }