public override bool HandleKeyPress(SharpDevelopTextAreaControl editor, char ch)
        {
            if (this.CompletionPossible(editor, ch))
            {
                ResourceResolveResult result = ResourceResolverService.Resolve(editor, ch);
                if (result != null)
                {
                    IResourceFileContent content;
                    if ((content = result.ResourceFileContent) != null)
                    {
                        // If the resolved resource set is the local ICSharpCode.Core resource set
                        // (this may happen through the ICSharpCodeCoreNRefactoryResourceResolver),
                        // we will have to merge in the host resource set (if available)
                        // for the code completion window.
                        if (result.ResourceSetReference.ResourceSetName == ICSharpCodeCoreResourceResolver.ICSharpCodeCoreLocalResourceSetName)
                        {
                            IResourceFileContent hostContent = ICSharpCodeCoreResourceResolver.GetICSharpCodeCoreHostResourceSet(editor.FileName).ResourceFileContent;
                            if (hostContent != null)
                            {
                                content = new MergedResourceFileContent(content, new IResourceFileContent[] { hostContent });
                            }
                        }

                        editor.ShowCompletionWindow(new ResourceCodeCompletionDataProvider(content, this.OutputVisitor, result.CallingClass != null ? result.CallingClass.Name + "." : null), ch);
                        return(true);
                    }
                }
            }

            return(false);
        }
        /// <summary>
        /// Determines if the specified type is a ResourceManager type that can
        /// be handled by this resolver.
        /// </summary>
        /// <param name="type">The type that will be checked if it is a ResourceManager.</param>
        /// <param name="sourceFileName">The name of the source code file where the reference to this type occurs.</param>
        static bool IsResourceManager(IReturnType type, string sourceFileName)
        {
            IProject        p = ProjectFileDictionaryService.GetProjectForFile(sourceFileName);
            IProjectContent pc;

            if (p == null)
            {
                pc = ParserService.CurrentProjectContent;
            }
            else
            {
                pc = ResourceResolverService.GetProjectContent(p);
            }

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

            IClass c = type.GetUnderlyingClass();

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

            IClass resourceManager = pc.GetClass("System.Resources.ResourceManager", 0);

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

            return(c.CompareTo(resourceManager) == 0 || c.IsTypeInInheritanceTree(resourceManager));
        }
        System.Collections.ICollection IMenuItemBuilder.BuildItems(Codon codon, object owner)
        {
            ITextEditor editor = owner as ITextEditor;

            if (editor == null)
            {
                ITextEditorProvider provider = owner as ITextEditorProvider;
                if (provider == null)
                {
                    return(EmptyControlArray);
                }
                editor = provider.TextEditor;
            }

            ResourceResolveResult result = ResourceResolverService.Resolve(editor, null);

            if (result != null && result.ResourceFileContent != null && result.Key != null)
            {
                List <MenuItem> items = new List <MenuItem>();
                MenuItem        item  = new MenuItem();

                // add resource (if key does not exist) / edit resource (if key exists)
                if (result.ResourceFileContent.ContainsKey(result.Key))
                {
                    item.Header = MenuService.ConvertLabel(StringParser.Parse("${res:Hornung.ResourceToolkit.TextEditorContextMenu.EditResource}"));
                }
                else
                {
                    item.Header = MenuService.ConvertLabel(StringParser.Parse("${res:Hornung.ResourceToolkit.TextEditorContextMenu.AddResource}"));
                }
                item.Click += this.EditResource;
                item.Tag    = result;
                items.Add(item);

                // find references
                item        = new MenuItem();
                item.Header = MenuService.ConvertLabel(StringParser.Parse("${res:SharpDevelop.Refactoring.FindReferencesCommand}"));
                item.Click += this.FindReferences;
                item.Tag    = result;
                items.Add(item);

                // rename
                item        = new MenuItem();
                item.Header = MenuService.ConvertLabel(StringParser.Parse("${res:SharpDevelop.Refactoring.RenameCommand}"));
                item.Click += this.Rename;
                item.Tag    = result;
                items.Add(item);


                // put the resource menu items into a submenu
                // with the resource key as title
                item             = new MenuItem();
                item.Header      = result.Key;
                item.ItemsSource = items;
                return(new System.Windows.Controls.Control[] { item, new Separator() });
            }

            return(EmptyControlArray);
        }
        /// <summary>
        /// Resolves a resource reference.
        /// Line and column are 0-based.
        /// </summary>
        protected ResourceResolveResult Resolve(string fileName, string code, int caretLine, int caretColumn, char?charTyped, bool parseFile)
        {
            this.EnlistTestFile(fileName, code, parseFile);
            IDocument doc = new AvalonEditDocumentAdapter();

            doc.Text = code;
            return(ResourceResolverService.Resolve(fileName, doc, caretLine, caretColumn, charTyped));
        }
        /// <summary>
        /// Resolves a resource reference.
        /// Line and column are 0-based.
        /// </summary>
        protected ResourceResolveResult Resolve(string fileName, string code, int caretLine, int caretColumn, char?charTyped, bool parseFile)
        {
            this.EnlistTestFile(fileName, code, parseFile);
            IDocument doc = new DocumentFactory().CreateDocument();

            doc.TextContent = code;
            return(ResourceResolverService.Resolve(fileName, doc, caretLine, caretColumn, charTyped));
        }
Beispiel #6
0
        public static void InitializeParsers()
        {
            Dictionary <string, IParser> parsers = new Dictionary <string, IParser>();

            parsers.Add(".cs", new CSharpBinding.Parser.TParser());
            parsers.Add(".vb", new VBNetBinding.Parser.TParser());
            ResourceResolverService.SetParsersUnitTestOnly(parsers);
        }
 /// <summary>
 /// Gets the language properties for the specified file.
 /// </summary>
 /// <param name="fileName">The file to get the language properties for.</param>
 /// <returns>The language properties of the specified file, or <c>null</c> if the language cannot be determined.</returns>
 public static LanguageProperties GetLanguagePropertiesForFile(string fileName)
 {
     ICSharpCode.SharpDevelop.Dom.IParser p = ResourceResolverService.GetParser(fileName);
     if (p == null)
     {
         return(null);
     }
     return(p.Language);
 }
        /// <summary>
        /// Generates the completion items.
        /// </summary>
        private void GenerateCompletionItems(IResourceFileContent content, IOutputAstVisitor outputVisitor, string preEnteredName)
        {
            this.Items.Add(new NewResourceCodeCompletionItem(content, outputVisitor, preEnteredName));

            foreach (KeyValuePair <string, object> entry in content.Data)
            {
                this.Items.Add(new ResourceCodeCompletionItem(entry.Key, ResourceResolverService.FormatResourceDescription(content, entry.Key), outputVisitor));
            }
        }
        /// <summary>
        /// Gets the language properties for the specified file.
        /// </summary>
        /// <param name="fileName">The file to get the language properties for.</param>
        /// <returns>The language properties of the specified file, or <c>null</c> if the language cannot be determined.</returns>
        public static LanguageProperties GetLanguagePropertiesForFile(string fileName)
        {
            var p = ResourceResolverService.GetParser(fileName);

            if (p == null)
            {
                return(null);
            }
            return(p.Language);
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="ResourceManagerInitializationFindVisitor" /> class.
            /// </summary>
            /// <param name="resourceManagerMember">The member which the resource manager to be found is assigned to.</param>
            public ResourceManagerInitializationFindVisitor(IMember resourceManagerMember)
                : base(resourceManagerMember.DeclaringType.CompilationUnit.FileName, ResourceResolverService.GetParsableFileContent(resourceManagerMember.DeclaringType.CompilationUnit.FileName))
            {
                this.resourceManagerMember = resourceManagerMember;
                IField resourceManagerField = resourceManagerMember as IField;

                if (resourceManagerField != null && resourceManagerField.IsLocalVariable)
                {
                    this.isLocalVariable = true;
                }
            }
Beispiel #11
0
 public static void InitializeResolvers()
 {
     NRefactoryResourceResolver.SetResourceResolversListUnitTestOnly(
         new INRefactoryResourceResolver[] {
         new BclNRefactoryResourceResolver(),
         new ICSharpCodeCoreNRefactoryResourceResolver()
     });
     ResourceResolverService.SetResourceResolversListUnitTestOnly(
         new IResourceResolver[] {
         new NRefactoryResourceResolver(),
         new ICSharpCodeCoreResourceResolver()
     });
 }
Beispiel #12
0
        /// <summary>
        /// Generates the completion data. This method is called by the text editor control.
        /// </summary>
        public override ICompletionData[] GenerateCompletionData(string fileName, ICSharpCode.TextEditor.TextArea textArea, char charTyped)
        {
            List <ICompletionData> list = new List <ICompletionData>();

            list.Add(new NewResourceCodeCompletionData(this.content, this.outputVisitor, this.preEnteredName));

            foreach (KeyValuePair <string, object> entry in this.content.Data)
            {
                list.Add(new ResourceCodeCompletionData(entry.Key, ResourceResolverService.FormatResourceDescription(this.content, entry.Key), this.outputVisitor));
            }

            return(list.ToArray());
        }
Beispiel #13
0
        public ToolStripItem[] BuildSubmenu(Codon codon, object owner)
        {
            TextEditorControl editor = owner as TextEditorControl;

            if (editor == null)
            {
                return(new ToolStripItem[0]);
            }

            ResourceResolveResult result = ResourceResolverService.Resolve(editor, null);

            if (result != null && result.ResourceFileContent != null && result.Key != null)
            {
                List <ToolStripItem> items = new List <ToolStripItem>();
                MenuCommand          cmd;

                // add resource (if key does not exist) / edit resource (if key exists)
                if (result.ResourceFileContent.ContainsKey(result.Key))
                {
                    cmd = new MenuCommand("${res:Hornung.ResourceToolkit.TextEditorContextMenu.EditResource}", this.EditResource);
                }
                else
                {
                    cmd = new MenuCommand("${res:Hornung.ResourceToolkit.TextEditorContextMenu.AddResource}", this.EditResource);
                }
                cmd.Tag = result;
                items.Add(cmd);

                // find references
                cmd     = new MenuCommand("${res:SharpDevelop.Refactoring.FindReferencesCommand}", this.FindReferences);
                cmd.Tag = result;
                items.Add(cmd);

                // rename
                cmd     = new MenuCommand("${res:SharpDevelop.Refactoring.RenameCommand}", this.Rename);
                cmd.Tag = result;
                items.Add(cmd);


                // put the resource menu items into a submenu
                // with the resource key as title
                ToolStripMenuItem subMenu = new ToolStripMenuItem(result.Key);
                subMenu.DropDownItems.AddRange(items.ToArray());
                return(new ToolStripItem[] { subMenu, new MenuSeparator() });
            }

            return(new ToolStripItem[0]);
        }
        protected void EnlistTestFile(string fileName, string code, bool parseFile)
        {
            ResourceResolverService.SetFileContentUnitTestOnly(fileName, code);
            ProjectFileDictionaryService.AddFile(fileName, this.Project);

            if (parseFile)
            {
                IParser parser = ResourceResolverService.GetParser(fileName);
                Assert.IsNotNull(parser, "Could not get parser for " + fileName + ".");
                ICompilationUnit cu = parser.Parse(this.DefaultProjectContent, fileName, code);
                cu.Freeze();
                Assert.IsFalse(cu.ErrorsDuringCompile, "Errors while parsing test program.");
                ParserService.RegisterParseInformation(fileName, cu);
                this.DefaultProjectContent.UpdateCompilationUnit(null, cu, fileName);
            }
        }
Beispiel #15
0
        protected virtual void DoSetUp()
        {
            TestHelper.InitializeParsers();

            this.solution = new Solution();
            this.project  = this.CreateTestProject();
            ProjectService.CurrentProject = this.project;

            DefaultProjectContent pc = this.CreateNewProjectContent(this.project);

            HostCallback.GetCurrentProjectContent = delegate {
                return(pc);
            };
            ResourceResolverService.SetProjectContentUnitTestOnly(this.project, pc);
            this.defaultPC = pc;
        }
Beispiel #16
0
        public ToolTipInfo GetToolTipInfo(TextArea textArea, ToolTipRequestEventArgs e)
        {
            TextLocation logicPos = e.LogicalPosition;
            IDocument    doc      = textArea.Document;

            if (logicPos.X > doc.GetLineSegment(logicPos.Y).Length - 1)
            {
                return(null);
            }

            ResourceResolveResult result = ResourceResolverService.Resolve(textArea.MotherTextEditorControl.FileName, doc, logicPos.Y, logicPos.X, null);

            if (result != null && result.ResourceFileContent != null)
            {
                return(new ToolTipInfo(ResourceResolverService.FormatResourceDescription(result.ResourceFileContent, result.Key)));
            }

            return(null);
        }
        // ********************************************************************************************************************************

        /// <summary>
        /// Determines whether this resolver supports resolving resources in the given file.
        /// </summary>
        /// <param name="fileName">The name of the file to examine.</param>
        /// <returns><c>true</c>, if this resolver supports resolving resources in the given file, <c>false</c> otherwise.</returns>
        public override bool SupportsFile(string fileName)
        {
            // Any parseable source code file may contain references
            if (ResourceResolverService.GetParser(fileName) != null)
            {
                return(true);
            }

            // Support additional files by extension
            switch (Path.GetExtension(fileName).ToLowerInvariant())
            {
            case ".addin":
            case ".xfrm":
            case ".xml":
                return(true);

            default:
                break;
            }

            return(false);
        }
        public void HandleToolTipRequest(ToolTipRequestEventArgs e)
        {
            if (!e.InDocument)
            {
                return;
            }

            Location  logicPos = e.LogicalPosition;
            IDocument doc      = e.Editor.Document;

            if (logicPos.X > doc.GetLine(logicPos.Y).Length)
            {
                return;
            }

            ResourceResolveResult result = ResourceResolverService.Resolve(e.Editor.FileName, doc, logicPos.Y - 1, logicPos.X - 1, null);

            if (result != null && result.ResourceFileContent != null)
            {
                e.SetToolTip(ResourceResolverService.FormatResourceDescription(result.ResourceFileContent, result.Key));
            }
        }
        // ********************************************************************************************************************************

        /// <summary>
        /// Attempts to resolve a reference to a resource.
        /// </summary>
        /// <param name="fileName">The name of the file that contains the expression to be resolved.</param>
        /// <param name="document">The document that contains the expression to be resolved.</param>
        /// <param name="caretLine">The 0-based line in the file that contains the expression to be resolved.</param>
        /// <param name="caretColumn">The 0-based column position of the expression to be resolved.</param>
        /// <param name="caretOffset">The offset of the position of the expression to be resolved.</param>
        /// <param name="charTyped">The character that has been typed at the caret position but is not yet in the buffer (this is used when invoked from code completion), or <c>null</c>.</param>
        /// <returns>A <see cref="ResourceResolveResult"/> that describes which resource is referenced by the expression at the specified position in the specified file, or <c>null</c> if that expression does not reference a (known) resource.</returns>
        protected override ResourceResolveResult Resolve(string fileName, IDocument document, int caretLine, int caretColumn, int caretOffset, char?charTyped)
        {
            IExpressionFinder ef = ResourceResolverService.GetExpressionFinder(fileName);

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

            bool foundStringLiteral = false;

            while (true)
            {
                ExpressionResult result = ef.FindFullExpression(document.Text, caretOffset);

                if (result.Expression == null)
                {
                    // Try to find an expression to the left, but only
                    // in the same line.
                    if (foundStringLiteral || --caretOffset < 0)
                    {
                        return(null);
                    }
                    var line = document.GetLineForOffset(caretOffset);
                    if (line.LineNumber - 1 != caretLine)
                    {
                        return(null);
                    }
                    continue;
                }

                if (!result.Region.IsEmpty)
                {
                    caretLine   = result.Region.BeginLine - 1;
                    caretColumn = result.Region.BeginColumn - 1;
                }

                PrimitiveExpression pe;
                Expression          expr = NRefactoryAstCacheService.ParseExpression(fileName, result.Expression, caretLine + 1, caretColumn + 1);

                if (expr == null)
                {
                    return(null);
                }
                else if ((pe = expr as PrimitiveExpression) != null)
                {
                    if (pe.Value is string)
                    {
                        if (foundStringLiteral)
                        {
                            return(null);
                        }

                        // We are inside a string literal and need to find
                        // the next outer expression to decide
                        // whether it is a resource key.

                        if (!result.Region.IsEmpty)
                        {
                            // Go back to the start of the string literal - 2.
                            caretOffset = document.PositionToOffset(result.Region.BeginLine, result.Region.BeginColumn) - 2;
                            if (caretOffset < 0)
                            {
                                return(null);
                            }
                        }
                        else
                        {
                            LoggingService.Debug("ResourceToolkit: NRefactoryResourceResolver: Found string literal, but result region is empty. Trying to infer position from text.");
                            int newCaretOffset = document.GetText(0, Math.Min(document.TextLength, caretOffset + result.Expression.Length)).LastIndexOf(result.Expression);
                            if (newCaretOffset == -1)
                            {
                                LoggingService.Warn("ResourceToolkit: NRefactoryResourceResolver: Could not find resolved expression in text.");
                                --caretOffset;
                                continue;
                            }
                            else
                            {
                                caretOffset = newCaretOffset;
                            }
                        }

                        foundStringLiteral = true;
                        continue;
                    }
                    else
                    {
                        return(null);
                    }
                }

                return(TryResolve(result, expr, caretLine, caretColumn, fileName, document.Text, ef, charTyped));
            }
        }
Beispiel #20
0
        public static ResolveResult ResolveLowLevel(string fileName, string fileContent, int caretLine, int caretColumn, CompilationUnit compilationUnit, string expressionString, Expression expression, ExpressionContext context)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (fileContent == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (expression == null)
            {
                throw new ArgumentNullException("expression");
            }

            IProject p = ProjectFileDictionaryService.GetProjectForFile(fileName);

            if (p == null)
            {
                LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. Project is null for file '" + fileName + "'");
                return(null);
            }

            IProjectContent pc = ResourceResolverService.GetProjectContent(p);

            if (pc == null)
            {
                LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. ProjectContent is null for project '" + p.ToString() + "'");
                return(null);
            }

            NRefactoryResolver resolver = ResourceResolverService.CreateResolver(fileName) as NRefactoryResolver;

            if (resolver == null)
            {
                resolver = new NRefactoryResolver(LanguageProperties.CSharp);
            }

            if (compilationUnit == null)
            {
                compilationUnit = GetFullAst(resolver.Language, fileName, fileContent);
            }
            if (compilationUnit == null)
            {
                LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed due to the compilation unit being unavailable.");
                return(null);
            }

            if (!resolver.Initialize(ParserService.GetParseInformation(fileName), caretLine, caretColumn))
            {
                LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: ResolveLowLevel failed. NRefactoryResolver.Initialize returned false.");
                return(null);
            }

            if (resolver.CallingClass != null)
            {
                ResolveResult rr;
                if (expressionString == null)
                {
                    // HACK: Re-generate the code for the expression from the expression object by using the code generator.
                    // This is necessary when invoking from inside an AST visitor where the
                    // code belonging to this expression is unavailable.
                    expressionString = resolver.LanguageProperties.CodeGenerator.GenerateCode(expression, String.Empty);
                }
                if ((rr = CtrlSpaceResolveHelper.GetResultFromDeclarationLine(resolver.CallingClass, resolver.CallingMember as IMethodOrProperty, caretLine, caretColumn, new ExpressionResult(expressionString))) != null)
                {
                    return(rr);
                }
            }

            if (resolver.CallingMember != null)
            {
                // Cache member->node mappings to improve performance
                // (if cache is enabled)
                INode memberNode;
                if (!CacheEnabled || !cachedMemberMappings.TryGetValue(resolver.CallingMember, out memberNode))
                {
                    MemberFindAstVisitor visitor = new MemberFindAstVisitor(resolver.CallingMember);
                    compilationUnit.AcceptVisitor(visitor, null);
                    memberNode = visitor.MemberNode;
                    if (CacheEnabled && memberNode != null)
                    {
                        cachedMemberMappings.Add(resolver.CallingMember, memberNode);
                    }
                }

                if (memberNode == null)
                {
                    LoggingService.Info("ResourceToolkit: NRefactoryAstCacheService: Could not find member in AST: " + resolver.CallingMember.ToString());
                }
                else
                {
                    resolver.RunLookupTableVisitor(memberNode);
                }
            }

            return(resolver.ResolveInternal(expression, context));
        }
        /// <summary>
        /// Finds all references to resources (except the definition) using the specified
        /// <see cref="IResourceReferenceFinder"/> object.
        /// </summary>
        /// <param name="finder">The <see cref="IResourceReferenceFinder"/> to use to find resource references.</param>
        /// <param name="monitor">An object implementing <see cref="IProgressMonitor"/> to report the progress of the operation. Can be <c>null</c>.</param>
        /// <param name="scope">The scope which should be searched.</param>
        /// <returns>A list of references to resources.</returns>
        public static List <Reference> FindReferences(IResourceReferenceFinder finder, IProgressMonitor monitor, SearchScope scope)
        {
            if (finder == null)
            {
                throw new ArgumentNullException("finder");
            }

            if (ParserService.LoadSolutionProjectsThreadRunning)
            {
                if (monitor != null)
                {
                    monitor.ShowingDialog = true;
                }
                MessageService.ShowMessage("${res:SharpDevelop.Refactoring.LoadSolutionProjectsThreadRunning}");
                if (monitor != null)
                {
                    monitor.ShowingDialog = false;
                }
                return(null);
            }

            DateTime startTime = DateTime.UtcNow;

            List <Reference> references = new List <Reference>();

            try {
                NRefactoryAstCacheService.EnableCache();

                ICollection <string> files = GetPossibleFiles(scope);

                if (monitor != null)
                {
                    monitor.BeginTask("${res:SharpDevelop.Refactoring.FindingReferences}", files.Count, true);
                }

                foreach (string fileName in files)
                {
                    if (monitor != null && monitor.IsCancelled)
                    {
                        return(null);
                    }

                    IDocument doc = null;
                    try {
                        // The following line throws an exception if the file does not exist.
                        // But the file may be in an unsaved view content (which would be found by GetDocumentInformation),
                        // so we cannot simply loop on !File.Exists(...).
                        doc = FindReferencesAndRenameHelper.GetDocumentInformation(fileName).CreateDocument();
                    } catch (FileNotFoundException) {
                    }
                    if (doc == null)
                    {
                        if (monitor != null)
                        {
                            ++monitor.WorkDone;
                        }
                        continue;
                    }

                    string fileContent = doc.TextContent;
                    if (String.IsNullOrEmpty(fileContent))
                    {
                        if (monitor != null)
                        {
                            ++monitor.WorkDone;
                        }
                        continue;
                    }

                    int pos = -1;
                    while ((pos = finder.GetNextPossibleOffset(fileName, fileContent, pos)) >= 0)
                    {
                        TextLocation          docPos = doc.OffsetToPosition(pos);
                        ResourceResolveResult rrr    = ResourceResolverService.Resolve(fileName, doc, docPos.Y, docPos.X, null);

                        if (rrr != null && rrr.ResourceFileContent != null)
                        {
                            if (finder.IsReferenceToResource(rrr))
                            {
                                if (rrr.Key != null)
                                {
                                    // The actual location of the key string may be after 'pos' because
                                    // the resolvers may find an expression just before it.
                                    string keyString = rrr.Key;
                                    int    keyPos    = fileContent.IndexOf(keyString, pos, StringComparison.OrdinalIgnoreCase);

                                    if (keyPos < pos)
                                    {
                                        // The key may be escaped in some way in the document.
                                        // Try using the code generator to find this out.
                                        keyPos = FindStringLiteral(fileName, fileContent, rrr.Key, pos, out keyString);
                                    }

                                    if (keyPos < pos)
                                    {
                                        if (monitor != null)
                                        {
                                            monitor.ShowingDialog = true;
                                        }
                                        MessageService.ShowWarning("ResourceToolkit: The key '" + rrr.Key + "' could not be located at the resolved position in the file '" + fileName + "'.");
                                        if (monitor != null)
                                        {
                                            monitor.ShowingDialog = false;
                                        }
                                    }
                                    else
                                    {
                                        references.Add(new Reference(fileName, keyPos, keyString.Length, keyString, rrr));
                                    }
                                }
                                else
                                {
                                    references.Add(new Reference(fileName, pos, 0, null, rrr));
                                }
                            }
                        }
                    }

                    if (monitor != null)
                    {
                        ++monitor.WorkDone;
                    }
                }

                LoggingService.Info("ResourceToolkit: FindReferences finished in " + (DateTime.UtcNow - startTime).TotalSeconds.ToString(System.Globalization.CultureInfo.CurrentCulture) + "s");
            } finally {
                NRefactoryAstCacheService.DisableCache();
                if (monitor != null)
                {
                    monitor.Done();
                }
            }

            return(references);
        }
        // ********************************************************************************************************************************

        /// <summary>
        /// Determines the file which contains the resources referenced by the specified manifest resource name.
        /// </summary>
        /// <param name="sourceFileName">The name of the source code file which the reference occurs in.</param>
        /// <param name="resourceName">The manifest resource name to find the resource file for.</param>
        /// <returns>A <see cref="ResourceSetReference"/> with the specified resource set name and the name of the file that contains the resources with the specified manifest resource name, or <c>null</c> if the file name cannot be determined.</returns>
        /// <exception cref="ArgumentNullException">The <paramref name="resourceName"/> parameter is <c>null</c>.</exception>
        public static ResourceSetReference GetResourceSetReference(string sourceFileName, string resourceName)
        {
            if (resourceName == null)
            {
                throw new ArgumentNullException("resourceName");
            }

            IProject p = ProjectFileDictionaryService.GetProjectForFile(sourceFileName);

            if (p != null)
            {
                string fileName;

                if ((fileName = TryGetResourceFileNameFromProjectDirect(resourceName, p)) != null)
                {
                    return(new ResourceSetReference(resourceName, fileName));
                }

                // SharpDevelop silently strips the (hard-coded) folder names
                // "src" and "source" when generating the default namespace name
                // for new files.
                // When MSBuild generates the manifest resource names for the
                // forms designer resources, it uses the type name of the
                // first class in the file. So we should find all files
                // that contain a type with the name in resourceName
                // and then look for dependent resource files or resource files
                // with the same name in the same directory as the source files.

                // Find all source files that contain a type with the same
                // name as the resource we are looking for.
                List <string>   possibleSourceFiles = new List <string>();
                IProjectContent pc = ResourceResolverService.GetProjectContent(p);
                if (pc != null)
                {
                    IClass resourceClass = pc.GetClass(resourceName, 0);

                    if (resourceClass != null)
                    {
                        CompoundClass cc = resourceClass.GetCompoundClass() as CompoundClass;

                        foreach (IClass c in (cc == null ? (IList <IClass>) new IClass[] { resourceClass } : cc.Parts))
                        {
                            if (c.CompilationUnit != null && c.CompilationUnit.FileName != null)
                            {
                                                                #if DEBUG
                                LoggingService.Debug("ResourceToolkit: NRefactoryResourceResolver found file '" + c.CompilationUnit.FileName + "' to contain the type '" + resourceName + "'");
                                                                #endif

                                possibleSourceFiles.Add(c.CompilationUnit.FileName);
                            }
                        }
                    }
                }

                foreach (string possibleSourceFile in possibleSourceFiles)
                {
                    string possibleSourceFileName = Path.GetFileName(possibleSourceFile);

                    // Find resource files dependent on these source files.
                    foreach (ProjectItem pi in p.Items)
                    {
                        FileProjectItem fpi = pi as FileProjectItem;
                        if (fpi != null)
                        {
                            if (fpi.DependentUpon != null &&
                                (fpi.ItemType == ItemType.EmbeddedResource || fpi.ItemType == ItemType.Resource || fpi.ItemType == ItemType.None) &&
                                FileUtility.IsEqualFileName(fpi.DependentUpon, possibleSourceFileName))
                            {
                                                                #if DEBUG
                                LoggingService.Debug("ResourceToolkit: NRefactoryResourceResolver trying to use dependent file '" + fpi.FileName + "' as resource file");
                                                                #endif

                                if ((fileName = FindResourceFileName(fpi.FileName)) != null)
                                {
                                    // Prefer culture-invariant resource file
                                    // over localized resource file
                                    IResourceFileContent rfc = ResourceFileContentRegistry.GetResourceFileContent(fileName);
                                    if (rfc.Culture.Equals(CultureInfo.InvariantCulture))
                                    {
                                        return(new ResourceSetReference(resourceName, fileName));
                                    }
                                }
                            }
                        }
                    }

                    // Fall back to any found resource file
                    // if no culture-invariant resource file was found
                    if (fileName != null)
                    {
                        return(new ResourceSetReference(resourceName, fileName));
                    }

                    // Find resource files with the same name as the source file
                    // and in the same directory.
                    if ((fileName = FindResourceFileName(possibleSourceFile)) != null)
                    {
                        return(new ResourceSetReference(resourceName, fileName));
                    }
                }
            }
            else
            {
                                #if DEBUG
                LoggingService.Info("ResourceToolkit: NRefactoryResourceResolver.GetResourceSetReference could not determine the project for the source file '" + (sourceFileName ?? "<null>") + "'.");
                                #endif

                if (sourceFileName != null)
                {
                    // The project could not be determined.
                    // Try a simple file search.

                    string directory    = Path.GetDirectoryName(sourceFileName);
                    string resourcePart = resourceName;
                    string fileName;

                    while (true)
                    {
                                                #if DEBUG
                        LoggingService.Debug("ResourceToolkit: NRefactoryResourceResolver.GetResourceSetReference: looking for a resource file like '" + Path.Combine(directory, resourcePart) + "'");
                                                #endif

                        if ((fileName = FindResourceFileName(Path.Combine(directory, resourcePart.Replace('.', Path.DirectorySeparatorChar)))) != null)
                        {
                            return(new ResourceSetReference(resourceName, fileName));
                        }
                        if ((fileName = FindResourceFileName(Path.Combine(directory, resourcePart))) != null)
                        {
                            return(new ResourceSetReference(resourceName, fileName));
                        }

                        if (resourcePart.Contains("."))
                        {
                            resourcePart = resourcePart.Substring(resourcePart.IndexOf('.') + 1);
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

                        #if DEBUG
            LoggingService.Info("ResourceToolkit: NRefactoryResourceResolver.GetResourceSetReference is unable to find a suitable resource file for '" + resourceName + "'");
                        #endif

            return(new ResourceSetReference(resourceName, null));
        }
        /// <summary>
        /// Tries to determine the resource set which is referenced by the
        /// resource manager which is assigned to the specified member.
        /// </summary>
        /// <param name="member">The referenced member to examine.</param>
        /// <returns>
        /// The ResourceSetReference, if successful, or a null reference, if the
        /// specified member is not a resource manager or if the
        /// resource file cannot be determined.
        /// </returns>
        static ResourceSetReference ResolveResourceSet(IMember member)
        {
            if (member != null && member.ReturnType != null &&
                member.DeclaringType != null && member.DeclaringType.CompilationUnit != null)
            {
                ResourceSetReference rsr;
                if (!NRefactoryAstCacheService.CacheEnabled || !cachedResourceSetReferenceMappings.TryGetValue(member, out rsr))
                {
                    string declaringFileName = member.DeclaringType.CompilationUnit.FileName;
                    if (declaringFileName != null)
                    {
                        if (IsResourceManager(member.ReturnType, declaringFileName))
                        {
                            SupportedLanguage?language = NRefactoryResourceResolver.GetFileLanguage(declaringFileName);
                            if (language == null)
                            {
                                return(null);
                            }

                            CompilationUnit cu = NRefactoryAstCacheService.GetFullAst(language.Value, declaringFileName, ResourceResolverService.GetParsableFileContent(declaringFileName));
                            if (cu != null)
                            {
                                ResourceManagerInitializationFindVisitor visitor = new ResourceManagerInitializationFindVisitor(member);
                                cu.AcceptVisitor(visitor, null);
                                if (visitor.FoundResourceSet != null)
                                {
                                    rsr = visitor.FoundResourceSet;

                                    if (NRefactoryAstCacheService.CacheEnabled)
                                    {
                                        cachedResourceSetReferenceMappings.Add(member, rsr);
                                    }

                                    return(rsr);
                                }
                            }
                        }
                    }

                    return(null);
                }

                return(rsr);
            }
            return(null);
        }