Ejemplo n.º 1
0
        /// <summary>
        /// Called from context menu of Solution Explorer, processes given list of ProjectItems
        /// </summary>
        /// <param name="selectedItems">Items selected in Solution Explorer - to be searched</param>
        /// <param name="verbose">True if processing info should be printed to the output</param>
        public override void Process(Array selectedItems, bool verbose)
        {
            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Batch Move to Resources command started on selected items from Solution Explorer");
            }
            if (verbose)
            {
                ProgressBarHandler.StartIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
            }

            try {
                Results = new List <CodeStringResultItem>();

                base.Process(selectedItems, verbose);

                // remove empty strings
                Results.RemoveAll((item) => { return(item.Value.Trim().Length == 0); });

                // set each source file as readonly
                Results.ForEach((item) => {
                    VLDocumentViewsManager.SetFileReadonly(item.SourceItem.GetFullPath(), true);
                });
            } finally {
                if (verbose)
                {
                    ProgressBarHandler.StopIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
                }
            }

            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Batch Move to Resources completed - found {0} items to be moved", Results.Count);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Checks active document whether it can be searched
        /// </summary>
        protected void CheckActiveDocument()
        {
            Document currentDocument = VisualLocalizerPackage.Instance.DTE.ActiveDocument;

            if (currentDocument == null)
            {
                throw new Exception("No selected document");
            }
            if (currentDocument.ProjectItem == null)
            {
                throw new Exception("Selected document has no corresponding Project Item.");
            }
            if (currentDocument.ProjectItem.ContainingProject == null)
            {
                throw new Exception("Selected document is not a part of any Project.");
            }
            if (RDTManager.IsFileReadonly(currentDocument.FullName) || VLDocumentViewsManager.IsFileLocked(currentDocument.FullName))
            {
                throw new Exception("Cannot perform this operation - active document is readonly");
            }
            if (VisualLocalizerPackage.Instance.DTE.Solution.FindProjectItem(currentDocument.FullName) == null)
            {
                throw new Exception("Selected document is not a part of an open Solution.");
            }
        }
Ejemplo n.º 3
0
        public void ProcessTest()
        {
            Agent.EnsureSolutionOpen();

            DTE2 DTE = Agent.GetDTE();
            BatchInlineCommand target = Agent.BatchInlineCommand;

            var window = DTE.OpenFile(null, Agent.VBReferencesTestFile1);

            window.Activate();

            target.Process(true);

            Assert.IsTrue(VLDocumentViewsManager.IsFileLocked(Agent.VBReferencesTestFile1));

            ValidateResults(GetExpectedResultsFor(Agent.VBReferencesTestFile1), target.Results);

            Assert.IsTrue(VLDocumentViewsManager.IsFileLocked(Agent.VBReferencesTestFile1));

            VLDocumentViewsManager.SetFileReadonly(Agent.VBReferencesTestFile1, false);
            Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(Agent.VBReferencesTestFile1));

            window.Detach();
            window.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Handles "Translate resources" command from Solution Explorer's context menu.
        /// </summary>
        private void TranslateSolExpClick(object sender, EventArgs args)
        {
            try {
                if (OperationInProgress)
                {
                    throw new Exception("Cannot start operation 'Global translate', because another operation is in progress.");
                }
                OperationInProgress = true;

                globalTranslateCommand.Process((Array)VisualLocalizerPackage.Instance.UIHierarchy.SelectedItems);
            } catch (Exception ex) {
                if (OperationInProgress)
                {
                    VLDocumentViewsManager.ReleaseLocks();
                }

                Dictionary <string, string> add = null;
                if (ex is CannotParseResponseException)
                {
                    CannotParseResponseException cpex = ex as CannotParseResponseException;
                    add = new Dictionary <string, string>();
                    add.Add("Full response:", cpex.FullResponse);
                }

                VLOutputWindow.VisualLocalizerPane.WriteException(ex, add);
                MessageBox.ShowException(ex, add);
                OperationInProgress = false;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// "Run" button was clicked
        /// </summary>
        private void RunClick(object sender, EventArgs args)
        {
            int checkedRows = panel.ToolGrid.CheckedRowsCount;
            int rowCount    = panel.ToolGrid.Rows.Count;
            int rowErrors   = 0;

            try {
                VLDocumentViewsManager.ReleaseLocks();                                               // unlock the documents
                MenuManager.OperationInProgress = false;                                             // permit other operations

                bool usingFullName = currentNamespacePolicy == NAMESPACE_POLICY_ITEMS[1];            // whether full references will be used
                bool markUncheckedStringsWithComment = currentRememberOption == REMEMBER_OPTIONS[1]; // whether unchecked strings will be marked with "no-localization" comment

                BatchMover mover = new BatchMover(usingFullName, markUncheckedStringsWithComment);

                mover.Move(panel.ToolGrid.GetData(), ref rowErrors); // run the mover
            } catch (Exception ex) {
                VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                VisualLocalizer.Library.Components.MessageBox.ShowException(ex);
            } finally {
                IVsWindowFrame frame = ((IVsWindowFrame)this.Frame);
                if (frame != null)
                {
                    frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);                // close the toolwindow
                }
                panel.ToolGrid.Clear();

                VLOutputWindow.VisualLocalizerPane.Activate();
                VLOutputWindow.VisualLocalizerPane.WriteLine("Batch Move to Resources command completed - selected {0} rows of {1}, {2} rows processed successfully", checkedRows, rowCount, checkedRows - rowErrors);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles "Batch inline" command from Solution Explorer's context menu.
        /// </summary>
        private void BatchInlineSolExpClick(object sender, EventArgs args)
        {
            try {
                if (OperationInProgress)
                {
                    throw new Exception("Cannot start operation 'Batch inline', because another operation is in progress.");
                }
                OperationInProgress = true;

                batchInlineCommand.Process((Array)VisualLocalizerPackage.Instance.UIHierarchy.SelectedItems, true);
                BatchInlineToolWindow win = ShowToolWindow <BatchInlineToolWindow>();
                if (win != null)
                {
                    win.SetData(batchInlineCommand.Results);
                }
                else
                {
                    throw new Exception("Unable to display tool window.");
                }
                batchInlineCommand.Results.Clear();
            } catch (Exception ex) {
                if (OperationInProgress)
                {
                    VLDocumentViewsManager.ReleaseLocks();
                }
                VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false);
                VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                MessageBox.ShowException(ex);
                OperationInProgress = false;
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Set opened-state of the specified files
 /// </summary>
 /// <param name="testFiles"></param>
 /// <param name="shouldBeOpened">True if files should be opened, false otherwise</param>
 protected void SetFilesOpened(string[] testFiles, bool shouldBeOpened)
 {
     foreach (string sourcePath in testFiles)
     {
         if (!shouldBeOpened && RDTManager.IsFileOpen(sourcePath))
         {
             var win = VsShellUtilities.GetWindowObject(VLDocumentViewsManager.GetWindowFrameForFile(sourcePath, false));
             // close the window
             win.Detach();
             win.Close(vsSaveChanges.vsSaveChangesNo);
         }
         if (shouldBeOpened)
         {
             Window win = null;
             // open the file and activate the window
             if (!RDTManager.IsFileOpen(sourcePath))
             {
                 win = Agent.GetDTE().OpenFile(null, sourcePath);
             }
             else
             {
                 win = VsShellUtilities.GetWindowObject(VLDocumentViewsManager.GetWindowFrameForFile(sourcePath, true));
             }
             Assert.IsNotNull(win, "Window cannot be opened " + sourcePath);
             win.Visible = true;
             win.Activate();
         }
     }
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Runs inline command on specified files and returns list of found result items.
        /// </summary>
        protected List <CodeReferenceResultItem> BatchInlineLookup(string[] files)
        {
            // select the files in Solution Explorer
            UIHierarchyItem[] selectedItems = new UIHierarchyItem[files.Length];
            int i = 0;

            foreach (var key in files)
            {
                selectedItems[i] = Agent.FindUIHierarchyItem(Agent.GetUIHierarchy().UIHierarchyItems, key);
                Assert.IsNotNull(selectedItems[i]);
                i++;
            }

            // run the command
            Agent.BatchInlineCommand.Results = null;
            Agent.BatchInlineCommand.Process(selectedItems, true);
            VLDocumentViewsManager.ReleaseLocks();

            // copy the results
            List <CodeReferenceResultItem> list = new List <CodeReferenceResultItem>();

            foreach (CodeReferenceResultItem item in Agent.BatchInlineCommand.Results)
            {
                list.Add(item);
            }

            return(list);
        }
Ejemplo n.º 9
0
        public void ProcessTest1()
        {
            Agent.EnsureSolutionOpen();

            DTE2             DTE    = Agent.GetDTE();
            BatchMoveCommand target = Agent.BatchMoveCommand;

            for (int i = 0; i < 3; i++)
            {
                var window = DTE.OpenFile(null, Agent.VBStringsTestFile1);
                window.Activate();

                target.Process(true);

                Assert.IsTrue(VLDocumentViewsManager.IsFileLocked(Agent.VBStringsTestFile1));

                ValidateResults(GetExpectedResultsFor(Agent.VBStringsTestFile1), target.Results);

                window.Detach();
                window.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo);
                Assert.IsTrue(VLDocumentViewsManager.IsFileLocked(Agent.VBStringsTestFile1));

                VLDocumentViewsManager.ReleaseLocks();
                Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(Agent.VBStringsTestFile1));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Runs the move to resources command on specified files and returns list of found result items.
        /// </summary>
        protected List <CodeStringResultItem> BatchMoveLookup(string[] testFiles)
        {
            List <CodeStringResultItem> list = new List <CodeStringResultItem>();

            // select the files in Solution Explorer
            UIHierarchyItem[] selectedItems = new UIHierarchyItem[testFiles.Length];
            for (int i = 0; i < testFiles.Length; i++)
            {
                selectedItems[i] = Agent.FindUIHierarchyItem(Agent.GetUIHierarchy().UIHierarchyItems, testFiles[i]);
                Assert.IsNotNull(selectedItems[i]);
            }

            // run the command
            Agent.BatchMoveCommand.Results = null;
            Agent.BatchMoveCommand.Process(selectedItems, true);

            // copy the results
            foreach (CodeStringResultItem item in Agent.BatchMoveCommand.Results)
            {
                list.Add(item);
            }

            VLDocumentViewsManager.ReleaseLocks();

            return(list);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Handles "Batch move on selection" command from code context menu.
        /// </summary>
        private void BatchMoveSelectionCodeClick(object sender, EventArgs args)
        {
            try {
                if (OperationInProgress)
                {
                    throw new Exception("Cannot start operation 'Batch move to resources', because another operation is in progress.");
                }
                OperationInProgress = true;

                batchMoveCommand.ProcessSelection(true);
                BatchMoveToResourcesToolWindow win = ShowToolWindow <BatchMoveToResourcesToolWindow>();
                if (win != null)
                {
                    win.SetData(batchMoveCommand.Results);
                }
                else
                {
                    throw new Exception("Unable to display tool window.");
                }
                batchMoveCommand.Results.Clear();
            } catch (Exception ex) {
                if (OperationInProgress)
                {
                    VLDocumentViewsManager.ReleaseLocks();
                }
                VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchMoveCommand), false);
                VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                MessageBox.ShowException(ex);
                OperationInProgress = false;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Generic test method
        /// </summary>
        /// <param name="files">List of files whose references should be renamed</param>
        public void InternalTest(string[] files)
        {
            // backup the files
            var backups = CreateBackupsOf(files);

            try {
                // get the result items
                List <CodeReferenceResultItem> list = BatchInlineLookup(files);
                VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false);
                int originalCount = list.Count;
                Assert.IsTrue(list.Count > 0);

                // rename each item by adding "XX". These resources must be present in the ResX files.
                list.ForEach((item) => {
                    item.Key            = item.FullReferenceText.Substring(item.FullReferenceText.LastIndexOf('.') + 1);
                    item.KeyAfterRename = item.Key + "XX";
                });

                // run the replacer
                int errors = 0;
                BatchReferenceReplacer replacer = new BatchReferenceReplacer();
                replacer.Inline(list, true, ref errors);
                VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false);

                Assert.AreEqual(0, errors);

                // run the inline command again - the number of result items should be equal to the one before renaming
                int newCount = BatchInlineLookup(files).Count((item) => { return(item.OriginalReferenceText.EndsWith("XX")); });
                VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false);
                Assert.AreEqual(originalCount, newCount);
            } finally {
                RestoreBackups(backups);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Explores given file, using parent batch command's methods as callbacks
        /// </summary>
        /// <param name="parentCommand"></param>
        /// <param name="projectItem"></param>
        /// <param name="maxLine">Line where parser should stop</param>
        /// <param name="maxIndex">Column where parser should stop</param>
        public void Explore(AbstractBatchCommand parentCommand, ProjectItem projectItem, int maxLine, int maxIndex)
        {
            if (parentCommand == null)
            {
                throw new ArgumentNullException("parentCommand");
            }
            if (projectItem == null)
            {
                throw new ArgumentNullException("projectItem");
            }

            lock (syncObject) {
                fullPath = projectItem.GetFullPath();
                if (string.IsNullOrEmpty(fullPath))
                {
                    throw new Exception("Cannot process item " + projectItem.Name);
                }

                this.parentCommand = parentCommand;
                this.declaredNamespaces.Clear();
                this.ClassFileName = Path.GetFileNameWithoutExtension(fullPath);
                this.projectItem   = projectItem;
                this.openedElements.Clear();

                // initialize type resolver
                if (parentCommand is BatchMoveCommand)
                {
                    webConfig = WebConfig.Get(projectItem, VisualLocalizerPackage.Instance.DTE.Solution);
                }
                else
                {
                    webConfig = null;
                }
                fileText = null;

                if (RDTManager.IsFileOpen(fullPath))                                             // file is open
                {
                    var textLines = VLDocumentViewsManager.GetTextLinesForFile(fullPath, false); // get text buffer
                    if (textLines == null)
                    {
                        return;
                    }

                    int lastLine, lastLineIndex;
                    int hr = textLines.GetLastLineIndex(out lastLine, out lastLineIndex);
                    Marshal.ThrowExceptionForHR(hr);

                    hr = textLines.GetLineText(0, 0, lastLine, lastLineIndex, out fileText); // get plain text
                    Marshal.ThrowExceptionForHR(hr);
                }
                else     // file is closed - read it from disk
                {
                    fileText = File.ReadAllText(fullPath);
                }

                Parser parser = new Parser(fileText, this, maxLine, maxIndex); // run ASP .NET parser
                parser.Process();
            }
        }
 /// <summary>
 /// When window is closed
 /// </summary>        
 protected override void OnWindowHidden(object sender, EventArgs e) {
     if (panel.SetDataFinished) {
         VLDocumentViewsManager.ReleaseLocks(); // unlock all previously locked documents
         MenuManager.OperationInProgress = false; // enable other operations to run
         VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false);
     }
     panel.Clear();
 }
Ejemplo n.º 15
0
        public void ProcessSelectionTest()
        {
            Agent.EnsureSolutionOpen();

            IVsTextView  view  = VLDocumentViewsManager.GetTextViewForFile(Agent.VBStringsTestFile1, true, true);
            IVsTextLines lines = VLDocumentViewsManager.GetTextLinesForFile(Agent.VBStringsTestFile1, false);

            GenericSelectionTest(Agent.BatchMoveCommand_Accessor, Agent.VBStringsTestFile1, view, lines, GetExpectedResultsFor);
        }
        public void ProcessSelectionTest2()
        {
            Agent.EnsureSolutionOpen();

            IVsTextView  view  = VLDocumentViewsManager.GetTextViewForFile(Agent.AspNetReferencesTestFile2, true, true);
            IVsTextLines lines = VLDocumentViewsManager.GetTextLinesForFile(Agent.AspNetReferencesTestFile2, false);

            GenericSelectionTest(Agent.BatchInlineCommand_Accessor, Agent.AspNetReferencesTestFile2, view, lines, GetExpectedResultsFor);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Generic test for classic variant of batch commands
        /// </summary>
        /// <param name="target">Command to test</param>
        /// <param name="itemsToSelect">List of items that should be marked as selected in the Solution Explorer</param>
        /// <param name="expectedFiles">List of files that are expected to be searched</param>
        /// <param name="getExpected">Function that returns list of expected result items for specified file</param>
        protected void GenericTest(AbstractBatchCommand target, string[] itemsToSelect, string[] expectedFiles, Func <string, List <AbstractResultItem> > getExpected)
        {
            Agent.EnsureSolutionOpen();
            try {
                // select the items in Solution Explorer
                UIHierarchyItem[] selectedItems = new UIHierarchyItem[itemsToSelect.Length];
                for (int i = 0; i < itemsToSelect.Length; i++)
                {
                    selectedItems[i] = Agent.FindUIHierarchyItem(Agent.GetUIHierarchy().UIHierarchyItems, itemsToSelect[i]);
                    Assert.IsNotNull(selectedItems[i]);
                }

                // run the command on the selection
                target.Process(selectedItems, true);

                // test if all expected files were processed
                for (int i = 0; i < expectedFiles.Length; i++)
                {
                    Assert.IsTrue(VLDocumentViewsManager.IsFileLocked(expectedFiles[i]));
                }

                // create the list of expected results
                List <AbstractResultItem> list = new List <AbstractResultItem>();
                for (int i = 0; i < expectedFiles.Length; i++)
                {
                    list.AddRange(getExpected(expectedFiles[i]));
                }

                // compare the results
                if (target is BatchMoveCommand)
                {
                    ValidateResults(list, (target as BatchMoveCommand).Results);
                }
                else if (target is BatchInlineCommand)
                {
                    ValidateResults(list, (target as BatchInlineCommand).Results);
                }
                else
                {
                    Assert.Fail("Unkown parent command type");
                }
            } finally {
                VLDocumentViewsManager.ReleaseLocks();
                for (int i = 0; i < expectedFiles.Length; i++)
                {
                    Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(expectedFiles[i]));
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// For given BlockSpan located in specified file, its absolute position parameters are calculated
        /// </summary>
        protected static void CalculateAbsolutePosition(string path, BlockSpan span)
        {
            IVsTextLines view = VLDocumentViewsManager.GetTextLinesForFile(path, true);
            object       o;

            view.CreateTextPoint(span.StartLine, span.StartIndex, out o);
            TextPoint tp = (TextPoint)o;

            span.AbsoluteCharOffset = tp.AbsoluteCharOffset + span.StartLine - 1;

            view.CreateTextPoint(span.EndLine, span.EndIndex, out o);
            TextPoint tp2 = (TextPoint)o;

            span.AbsoluteCharLength = tp2.AbsoluteCharOffset + span.EndLine - 1 - span.AbsoluteCharOffset;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// For given result item with specified ReplaceSpan calculates AbsoluteCharOffset and AbsoluteCharLength
        /// </summary>
        protected static void CalculateAbsolutePosition(AbstractResultItem item)
        {
            IVsTextLines view = VLDocumentViewsManager.GetTextLinesForFile(item.SourceItem.GetFullPath(), true);
            object       o;

            view.CreateTextPoint(item.ReplaceSpan.iStartLine, item.ReplaceSpan.iStartIndex, out o);
            TextPoint tp = (TextPoint)o;

            item.AbsoluteCharOffset = tp.AbsoluteCharOffset + item.ReplaceSpan.iStartLine - 1;

            view.CreateTextPoint(item.ReplaceSpan.iEndLine, item.ReplaceSpan.iEndIndex, out o);
            TextPoint tp2 = (TextPoint)o;

            item.AbsoluteCharLength = tp2.AbsoluteCharOffset + item.ReplaceSpan.iEndLine - 1 - item.AbsoluteCharOffset;
        }
Ejemplo n.º 20
0
        public void VBInlineTest()
        {
            Agent.EnsureSolutionOpen();

            VBInlineCommand_Accessor target = new VBInlineCommand_Accessor();
            Window window = Agent.GetDTE().OpenFile(null, Agent.VBReferencesTestFile1);

            IVsTextView  view     = VLDocumentViewsManager.GetTextViewForFile(Agent.VBReferencesTestFile1, true, true);
            IVsTextLines lines    = VLDocumentViewsManager.GetTextLinesForFile(Agent.VBReferencesTestFile1, false);
            var          expected = VBBatchInlineTest.GetExpectedResultsFor(Agent.VBReferencesTestFile1);

            RunTest(target, view, lines, expected);

            window.Detach();
            window.Close(vsSaveChanges.vsSaveChangesNo);
        }
Ejemplo n.º 21
0
        public void CSharpMoveTest()
        {
            Agent.EnsureSolutionOpen();

            CSharpMoveToResourcesCommand_Accessor target = new CSharpMoveToResourcesCommand_Accessor();
            Window window = Agent.GetDTE().OpenFile(null, Agent.CSharpStringsTestFile1);

            IVsTextView  view     = VLDocumentViewsManager.GetTextViewForFile(Agent.CSharpStringsTestFile1, true, true);
            IVsTextLines lines    = VLDocumentViewsManager.GetTextLinesForFile(Agent.CSharpStringsTestFile1, false);
            var          expected = CSharpBatchMoveTest.GetExpectedResultsFor(Agent.CSharpStringsTestFile1);

            RunTest(target, view, lines, expected);

            window.Detach();
            window.Close(vsSaveChanges.vsSaveChangesNo);
        }
        /// <summary>
        /// If the given item is ResX file, adds it to the list of ResX files
        /// </summary>
        private void SearchForResxFiles(ProjectItem item, List <GlobalTranslateProjectItem> resxFiles)
        {
            if (searchedProjectItems.Contains(item))
            {
                return;
            }
            SearchForResxFiles(item.ProjectItems, resxFiles);

            if (item.IsItemResX())
            {
                GlobalTranslateProjectItem r = new GlobalTranslateProjectItem(item);
                r.Checked  = false;
                r.Readonly = VLDocumentViewsManager.IsFileLocked(item.GetFullPath()) || RDTManager.IsFileReadonly(item.GetFullPath());

                resxFiles.Add(r);
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// When the toolwindow is closed
 /// </summary>
 protected override void OnWindowHidden(object sender, EventArgs e)
 {
     try {
         if (panel.ToolGrid.SetDataFinished)
         {
             VLDocumentViewsManager.ReleaseLocks();   // unlocks all locked files
             panel.ToolGrid.UnloadResXItems();        // release all ResX files loaded in the grid
             panel.ToolGrid.ResetConflictResolver();
             MenuManager.OperationInProgress = false; // permits other operations
             VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchMoveCommand), false);
         }
         panel.ToolGrid.Clear();
     } catch (Exception ex) {
         VLOutputWindow.VisualLocalizerPane.WriteException(ex);
         VisualLocalizer.Library.Components.MessageBox.ShowException(ex);
     }
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Called from context menu of a code file, processes selected block of code
        /// </summary>
        /// <param name="verbose">True if processing info should be printed to the output</param>
        public override void ProcessSelection(bool verbose)
        {
            base.ProcessSelection(verbose);

            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Batch Inline command started on text selection of active document ");
            }
            if (verbose)
            {
                ProgressBarHandler.StartIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
            }

            try {
                Results = new List <CodeReferenceResultItem>();

                Process(currentlyProcessedItem, IntersectsWithSelection, verbose);

                // remove items laying outside the selection
                Results.RemoveAll((item) => {
                    return(IsItemOutsideSelection(item));
                });

                // set each source file as readonly
                Results.ForEach((item) => {
                    VLDocumentViewsManager.SetFileReadonly(item.SourceItem.GetFullPath(), true);
                });
            } finally {
                // clear cached data
                trieCache.Clear();
                trieCache.Clear();
                codeUsingsCache.Clear();

                if (verbose)
                {
                    ProgressBarHandler.StopIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
                }
            }
            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Found {0} items to be moved", Results.Count);
            }
        }
Ejemplo n.º 25
0
        public void ProcessEmptySelectionTest()
        {
            Agent.EnsureSolutionOpen();

            BatchMoveCommand_Accessor target = Agent.BatchMoveCommand_Accessor;

            Window      window = Agent.GetDTE().OpenFile(null, Agent.VBStringsTestFile1);
            IVsTextView view   = VLDocumentViewsManager.GetTextViewForFile(Agent.VBStringsTestFile1, false, true);

            view.SetSelection(40, 17, 44, 26);

            List <CodeStringResultItem> emptyList = new List <CodeStringResultItem>();

            target.ProcessSelection(true);
            ValidateResults(emptyList, target.Results);
            Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(Agent.VBStringsTestFile1));

            window.Detach();
            window.Close(vsSaveChanges.vsSaveChangesNo);
        }
        /// <summary>
        /// Change the text in the source file
        /// </summary>
        public override void ApplyTranslation()
        {
            if (!Applied)
            {
                ResXResourceWriter writer = null;
                MemoryStream       stream = null;
                try {
                    stream          = new MemoryStream();
                    writer          = new ResXResourceWriter(stream);
                    writer.BasePath = Path.GetDirectoryName(Filename);

                    // change resource values in all BufferTranslateInfoItems
                    BufferTranslateInfoItem i = this;
                    while (true)
                    {
                        if (i == null || i.Applied)
                        {
                            break;
                        }
                        writer.AddResource(i.ResourceKey, i.Value);

                        i.Applied = true;
                        i         = i.Prev;
                    }
                    foreach (ResXDataNode node in GlobalTranslateItem.NonStringData)
                    {
                        writer.AddResource(node);
                    }

                    writer.Generate();
                    writer.Close();

                    VLDocumentViewsManager.SaveStreamToBuffer(stream, IVsTextLines, false);
                } finally {
                    if (stream != null)
                    {
                        stream.Close();
                    }
                }
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Treats given ProjectItem as a VB code file, using VBCodeExplorer to examine the file. LookInVB method is called as a callback,
        /// given plain methods text.
        /// </summary>
        protected virtual void ProcessVB(ProjectItem projectItem, Predicate <CodeElement> exploreable, bool verbose)
        {
            bool           fileOpened;
            FileCodeModel2 codeModel = projectItem.GetCodeModel(false, true, out fileOpened);

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

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

            currentlyProcessedItem = projectItem;

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

            currentlyProcessedItem = null;
        }
Ejemplo n.º 28
0
        public void ProcessEmptySelectionTest()
        {
            Agent.EnsureSolutionOpen();

            DTE2 DTE = Agent.GetDTE();
            BatchInlineCommand_Accessor target = Agent.BatchInlineCommand_Accessor;

            Window      window = DTE.OpenFile(null, Agent.VBReferencesTestFile1);
            IVsTextView view   = VLDocumentViewsManager.GetTextViewForFile(Agent.VBReferencesTestFile1, false, true);

            view.SetSelection(28, 4, 35, 31);

            List <AbstractResultItem> emptyList = new List <AbstractResultItem>();

            target.ProcessSelection(true);
            ValidateResults(emptyList, target.Results);
            Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(Agent.VBReferencesTestFile1));

            window.Detach();
            window.Close(vsSaveChanges.vsSaveChangesNo);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Called from context menu of a code file, processes selected block of code
        /// </summary>
        /// <param name="verbose">True if processing info should be printed to the output</param>
        public override void ProcessSelection(bool verbose)
        {
            base.ProcessSelection(verbose); // initialize class variables

            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Batch Move to Resources command started on text selection of active document ");
            }
            if (verbose)
            {
                ProgressBarHandler.StartIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
            }

            try {
                Results = new List <CodeStringResultItem>();

                Process(currentlyProcessedItem, IntersectsWithSelection, verbose); // process active document, leaving only those items that have non-empty intersection with the selection

                // remove empty strings and result items laying outside the selection
                Results.RemoveAll((item) => {
                    bool empty = item.Value.Trim().Length == 0;
                    return(empty || IsItemOutsideSelection(item));
                });

                // set each source file as readonly
                Results.ForEach((item) => {
                    VLDocumentViewsManager.SetFileReadonly(item.SourceItem.GetFullPath(), true);
                });
            } finally {
                if (verbose)
                {
                    ProgressBarHandler.StopIndeterminate(Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Find);
                }
            }

            if (verbose)
            {
                VLOutputWindow.VisualLocalizerPane.WriteLine("Found {0} items to be moved", Results.Count);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Handles "Inline" command from code context menu.
        /// </summary>
        private void InlineClick(object sender, EventArgs args)
        {
            bool enteredOk = false;

            try {
                if (OperationInProgress)
                {
                    throw new Exception("Cannot start operation 'Inline', because another operation is in progress.");
                }
                enteredOk = true;

                Document doc = VisualLocalizerPackage.Instance.DTE.ActiveDocument;
                if (doc == null)
                {
                    throw new Exception("No active document.");
                }

                if (doc.ProjectItem.GetFileType() == FILETYPE.ASPX)
                {
                    aspNetInlineCommand.Process();
                }
                else if (doc.ProjectItem.GetFileType() == FILETYPE.CSHARP)
                {
                    csharpInlineCommand.Process();
                }
                else if (doc.ProjectItem.GetFileType() == FILETYPE.VB)
                {
                    vbInlineCommand.Process();
                }
            } catch (Exception ex) {
                VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                MessageBox.ShowException(ex);
            } finally {
                if (enteredOk)
                {
                    VLDocumentViewsManager.ReleaseLocks();
                }
            }
        }