/// <summary>
        /// Called on click - when overriden, finds object in current selection and displayes dialog offering to move it.
        /// </summary>
        public override void Process()
        {
            base.Process();                        // initialize basic variables

            T resultItem = GetReplaceStringItem(); // get result item (language specific)

            if (resultItem != null)                // result item found and ok - proceed
            {
                TextSpan replaceSpan        = resultItem.ReplaceSpan;
                string   referencedCodeText = resultItem.Value;
                resultItem.SourceItem = currentDocument.ProjectItem; // set origin project item of the result item

                // display dialog enabling user to modify resource key, select destination resource file etc.
                // also enables user to resolve conflicts (duplicate key entries)
                SelectResourceFileForm            f      = new SelectResourceFileForm(currentDocument.ProjectItem, resultItem);
                System.Windows.Forms.DialogResult result = f.ShowDialog();

                resultItem.DestinationItem = f.SelectedItem; // set destination project item - ResX file

                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    bool removeConst = false;
                    if (resultItem.IsConst)
                    {
                        var deleteConst = VisualLocalizer.Library.Components.MessageBox.Show("This field is marked as 'const'. In order to continue with this operation, this modifier must be removed. Continue?", "Const", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_WARNING);
                        if (deleteConst == DialogResult.Yes)
                        {
                            removeConst = true;
                        }
                        else
                        {
                            return;
                        }
                    }

                    bool            unitsFromStackRemoved = false;
                    bool            unitMovedToResource   = false;
                    ReferenceString referenceText;
                    bool            addUsing = false;

                    // Now we must resolve the namespaces issue. If user selected the "use full name" in previous dialog,
                    // there's no trouble. Otherwise we must find out, if necessary namespace has already been included (using)
                    // and if not, create new using block with the namespace name.

                    try {
                        resultItem.DestinationItem = f.SelectedItem;
                        if (resultItem.DestinationItem == null)
                        {
                            throw new InvalidOperationException("Destination item must be selected.");
                        }
                        if (resultItem.DestinationItem.InternalProjectItem == null)
                        {
                            throw new InvalidOperationException("Destination item must be selected.");
                        }
                        if (!File.Exists(resultItem.DestinationItem.InternalProjectItem.GetFullPath()))
                        {
                            throw new InvalidOperationException("Destination item file does not exist.");
                        }

                        if (f.UsingFullName || resultItem.MustUseFullName || (resultItem.Language == LANGUAGE.VB && resultItem.DestinationItem.IsProjectDefault(resultItem.SourceItem.ContainingProject)))
                        {
                            referenceText = new ReferenceString(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key);
                            addUsing      = false;
                        }
                        else
                        {
                            NamespacesList usedNamespaces = resultItem.GetUsedNamespaces();
                            addUsing = usedNamespaces.ResolveNewElement(f.SelectedItem.Namespace, f.SelectedItem.Class, f.Key,
                                                                        currentDocument.ProjectItem.ContainingProject, out referenceText);
                        }

                        string newText = resultItem.GetReferenceText(referenceText);

                        // perform actual replace
                        int hr = textLines.ReplaceLines(replaceSpan.iStartLine, replaceSpan.iStartIndex, replaceSpan.iEndLine, replaceSpan.iEndIndex,
                                                        Marshal.StringToBSTR(newText), newText.Length, new TextSpan[] { replaceSpan });
                        Marshal.ThrowExceptionForHR(hr);

                        // set selection to the new text
                        hr = textView.SetSelection(replaceSpan.iStartLine, replaceSpan.iStartIndex,
                                                   replaceSpan.iStartLine, replaceSpan.iStartIndex + newText.Length);
                        Marshal.ThrowExceptionForHR(hr);

                        if (removeConst)
                        {
                            CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                            codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                        }

                        if (addUsing)
                        {
                            resultItem.AddUsingBlock(textLines);
                        }

                        if (f.Result == SELECT_RESOURCE_FILE_RESULT.INLINE)
                        {
                            // conflict -> user chooses to reference existing key
                            unitsFromStackRemoved = CreateMoveToResourcesReferenceUndoUnit(f.Key, addUsing, removeConst);
                        }
                        else if (f.Result == SELECT_RESOURCE_FILE_RESULT.OVERWRITE)
                        {
                            // conflict -> user chooses to overwrite existing key and reference the new one
                            f.SelectedItem.AddString(f.Key, f.Value);
                            unitMovedToResource   = true;
                            unitsFromStackRemoved = CreateMoveToResourcesOverwriteUndoUnit(f.Key, f.Value, f.OverwrittenValue, f.SelectedItem, addUsing, removeConst);
                        }
                        else
                        {
                            // no conflict occured
                            f.SelectedItem.AddString(f.Key, f.Value);
                            unitMovedToResource   = true;
                            unitsFromStackRemoved = CreateMoveToResourcesUndoUnit(f.Key, f.Value, f.SelectedItem, addUsing, removeConst);
                        }
                    } catch (Exception) {
                        // exception occured - rollback all already performed actions in order to restore original state

                        VLOutputWindow.VisualLocalizerPane.WriteLine("Exception caught, rolling back...");
                        if (!unitsFromStackRemoved)
                        {
                            int unitsToRemoveCount    = (addUsing && removeConst) ? 3 : (addUsing || removeConst ? 2 : 1);
                            List <IOleUndoUnit> units = undoManager.RemoveTopFromUndoStack(unitsToRemoveCount);
                            foreach (var unit in units)
                            {
                                unit.Do(undoManager);
                            }
                            undoManager.RemoveTopFromUndoStack(units.Count);
                            if (unitMovedToResource)
                            {
                                f.SelectedItem.RemoveKey(f.Key);
                            }
                        }
                        else
                        {
                            AbstractUndoUnit unit = (AbstractUndoUnit)undoManager.RemoveTopFromUndoStack(1)[0];
                            int unitsToRemove     = unit.AppendUnits.Count + 1;
                            unit.Do(undoManager);
                            undoManager.RemoveTopFromUndoStack(unitsToRemove);
                        }
                        throw;
                    }
                }
            }
            else
            {
                throw new Exception("This part of code cannot be referenced");
            }
        }
示例#2
0
        public void Move(List <CodeStringResultItem> dataList, ref int errorRows)
        {
            // sort according to position
            dataList.Sort(new ResultItemsPositionCompararer <CodeStringResultItem>());

            for (int i = dataList.Count - 1; i >= 0; i--)
            {
                try {
                    // initialization of data
                    CodeStringResultItem resultItem   = dataList[i];
                    string              path          = resultItem.SourceItem.GetFullPath();
                    ReferenceString     referenceText = null;
                    bool                addUsingBlock = false;
                    CONTAINS_KEY_RESULT keyConflict   = CONTAINS_KEY_RESULT.DOESNT_EXIST;

                    if (resultItem.MoveThisItem) // row was checked in the toolwindow
                    {
                        Validate(resultItem);    // check that key, value and destination item was specifed and that row has no errors
                        if (!resultItem.DestinationItem.IsLoaded)
                        {
                            resultItem.DestinationItem.Load();
                        }
                        if (!loadedResxItems.Contains(resultItem.DestinationItem))
                        {
                            loadedResxItems.Add(resultItem.DestinationItem);
                        }

                        // check if such item already exists in destination file
                        keyConflict = resultItem.DestinationItem.GetKeyConflictType(resultItem.Key, resultItem.Value, true);
                        if (keyConflict == CONTAINS_KEY_RESULT.EXISTS_WITH_DIFF_VALUE)
                        {
                            throw new InvalidOperationException(string.Format("Key \"{0}\" already exists with different value.", resultItem.Key));
                        }
                        resultItem.Key = resultItem.DestinationItem.GetRealKey(resultItem.Key); // if key already exists, return its name (solves case-sensitivity problems)

                        NamespacesList usedNamespaces = GetUsedNamespacesFor(resultItem);

                        if (UseFullName || resultItem.MustUseFullName || (resultItem.Language == LANGUAGE.VB && resultItem.DestinationItem.IsProjectDefault(resultItem.SourceItem.ContainingProject)))   // reference will contain namespace
                        {
                            referenceText = new ReferenceString(resultItem.DestinationItem.Namespace, resultItem.DestinationItem.Class, resultItem.Key);
                            addUsingBlock = false; // no using block will be added
                        }
                        else
                        {
                            // use resolver whether it is ok to add using block
                            addUsingBlock = usedNamespaces.ResolveNewElement(resultItem.DestinationItem.Namespace, resultItem.DestinationItem.Class, resultItem.Key,
                                                                             resultItem.SourceItem.ContainingProject, out referenceText);
                        }
                        if (addUsingBlock)   // new using block will be added
                        {
                            if (!usedNamespacesCache.ContainsKey(resultItem.SourceItem))
                            {
                                usedNamespacesCache.Add(resultItem.SourceItem, new NamespacesList());
                            }
                            foreach (var pair in usedNamespacesCache)
                            {
                                if (!pair.Value.ContainsNamespace(resultItem.DestinationItem.Namespace))
                                {
                                    pair.Value.Add(resultItem.DestinationItem.Namespace, null, true);
                                }
                            }
                        }
                    }

                    if (RDTManager.IsFileOpen(path) && RDTManager.IsFileVisible(path))                                                    // file is open
                    {
                        if (resultItem.MoveThisItem || (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)) // string literal in text will be modified (referenced or marked with comment)
                        {
                            if (!buffersCache.ContainsKey(path))
                            {
                                // load file's buffer
                                IVsTextLines textLines = DocumentViewsManager.GetTextLinesForFile(path, false);
                                buffersCache.Add(path, textLines);

                                IOleUndoManager m;
                                // get file's undo manager
                                int hr = textLines.GetUndoManager(out m);
                                Marshal.ThrowExceptionForHR(hr);
                                undoManagersCache.Add(path, m);
                            }
                        }

                        if (resultItem.MoveThisItem)
                        {
                            // perform the text replacement
                            MoveToResource(buffersCache[path], resultItem, referenceText);

                            if (resultItem.IsConst && resultItem.CodeModelSource is CodeVariable2)
                            {
                                CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                                codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                            }

                            if (addUsingBlock)
                            {
                                // add using block to the source file
                                int beforeLines, afterLines;
                                buffersCache[path].GetLineCount(out beforeLines);
                                resultItem.AddUsingBlock(buffersCache[path]);
                                buffersCache[path].GetLineCount(out afterLines);
                                int diff = afterLines - beforeLines;

                                // because of the previous step, it is necessary to adjust position of all not-yet referenced result items
                                for (int j = i; j >= 0; j--)
                                {
                                    var item = dataList[j];
                                    if (item.SourceItem == resultItem.SourceItem)
                                    {
                                        TextSpan ts = new TextSpan();
                                        ts.iEndIndex     = item.ReplaceSpan.iEndIndex;
                                        ts.iEndLine      = item.ReplaceSpan.iEndLine + diff;
                                        ts.iStartIndex   = item.ReplaceSpan.iStartIndex;
                                        ts.iStartLine    = item.ReplaceSpan.iStartLine + diff;
                                        item.ReplaceSpan = ts;
                                    }
                                }
                            }

                            // previous step (replace and possibly new using block) caused undo unit to be added - remove it
                            int unitsToRemoveCount    = (resultItem.IsConst && addUsingBlock ? 3 : (resultItem.IsConst || addUsingBlock ? 2 : 1));
                            List <IOleUndoUnit> units = undoManagersCache[path].RemoveTopFromUndoStack(unitsToRemoveCount);

                            // and add custom undo unit
                            AbstractUndoUnit newUnit = null;
                            if (keyConflict == CONTAINS_KEY_RESULT.DOESNT_EXIST)
                            {
                                newUnit = new MoveToResourcesUndoUnit(resultItem.Key, resultItem.Value, resultItem.DestinationItem);
                            }
                            else if (keyConflict == CONTAINS_KEY_RESULT.EXISTS_WITH_SAME_VALUE)
                            {
                                newUnit = new MoveToResourcesReferenceUndoUnit(resultItem.Key);
                            }

                            newUnit.AppendUnits.AddRange(units);
                            undoManagersCache[path].Add(newUnit);
                        }
                        else if (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)     // string literal should be marked with comment
                        {
                            AspNetStringResultItem aitem = resultItem as AspNetStringResultItem;

                            // this operation is only possible if string literal comes from C# code
                            if (resultItem is CSharpStringResultItem || (aitem != null && aitem.ComesFromCodeBlock && aitem.Language == LANGUAGE.CSHARP))
                            {
                                // add the comment
                                int c = MarkAsNoLoc(buffersCache[path], resultItem);

                                // add undo unit
                                List <IOleUndoUnit> units = undoManagersCache[path].RemoveTopFromUndoStack(1);
                                MarkAsNotLocalizedStringUndoUnit newUnit = new MarkAsNotLocalizedStringUndoUnit(resultItem.Value);
                                newUnit.AppendUnits.AddRange(units);
                                undoManagersCache[path].Add(newUnit);
                            }
                        }
                    }
                    else     // file is closed
                    // same as with open file, only operating with text, not buffers

                    {
                        if (resultItem.MoveThisItem || (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment))   // string literal will be modified
                        // load file's text into the cache
                        {
                            if (!filesCache.ContainsKey(path))
                            {
                                filesCache.Add(path, new StringBuilder(File.ReadAllText(path)));
                            }
                        }

                        if (resultItem.IsConst && resultItem.CodeModelSource is CodeVariable2)
                        {
                            CodeVariable2 codeVar = (CodeVariable2)resultItem.CodeModelSource;
                            fieldsToRemoveConst.Add(codeVar);
                        }

                        if (resultItem.MoveThisItem)
                        {
                            StringBuilder b = filesCache[path];

                            // perform the replacement
                            string insertText = resultItem.GetReferenceText(referenceText);
                            b.Remove(resultItem.AbsoluteCharOffset, resultItem.AbsoluteCharLength);
                            b.Insert(resultItem.AbsoluteCharOffset, insertText);

                            if (addUsingBlock)
                            {
                                // add using block
                                if (!newUsingsPlan.ContainsKey(path))
                                {
                                    newUsingsPlan.Add(path, new List <string>());
                                }
                                newUsingsPlan[path].Add(resultItem.DestinationItem.Namespace);
                            }
                        }
                        else if (MarkUncheckedStringsWithComment && !resultItem.IsMarkedWithUnlocalizableComment)
                        {
                            AspNetStringResultItem aitem = resultItem as AspNetStringResultItem;

                            if (resultItem is CSharpStringResultItem || (aitem != null && aitem.ComesFromCodeBlock && aitem.Language == LANGUAGE.CSHARP))
                            {
                                StringBuilder b = filesCache[path];
                                b.Insert(resultItem.AbsoluteCharOffset, resultItem.NoLocalizationComment);
                            }
                        }
                    }

                    if (resultItem.MoveThisItem && keyConflict == CONTAINS_KEY_RESULT.DOESNT_EXIST)
                    {
                        if (!resultItem.DestinationItem.IsInBatchMode)
                        {
                            resultItem.DestinationItem.BeginBatch();
                        }
                        // add the key to the ResX file
                        resultItem.DestinationItem.AddString(resultItem.Key, resultItem.Value);
                    }
                } catch (Exception ex) {
                    errorRows++;
                    VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                }
            }

            // add using blocks to closed files texts
            foreach (var pair in newUsingsPlan)
            {
                foreach (string nmspc in pair.Value)
                {
                    AddUsingBlockTo(pair.Key, nmspc);
                }
            }

            // flush closed files texts
            foreach (var pair in filesCache)
            {
                if (RDTManager.IsFileOpen(pair.Key))
                {
                    RDTManager.SetIgnoreFileChanges(pair.Key, true);
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                    RDTManager.SetIgnoreFileChanges(pair.Key, false);
                    RDTManager.SilentlyReloadFile(pair.Key);
                }
                else
                {
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                }
            }

            // remove 'const' modifier from fields in closed files
            HashSet <ProjectItem> itemsToSave = new HashSet <ProjectItem>();

            foreach (CodeVariable2 codeVar in fieldsToRemoveConst)
            {
                codeVar.ConstKind = vsCMConstKind.vsCMConstKindNone;
                itemsToSave.Add(codeVar.ProjectItem);
            }
            foreach (ProjectItem item in itemsToSave)
            {
                item.Save(null);
            }

            foreach (ResXProjectItem item in loadedResxItems)
            {
                if (item.IsInBatchMode)
                {
                    item.EndBatch();
                }
                item.Unload();
            }
            if (errorRows > 0)
            {
                throw new Exception("Error occured while processing some rows - see Output window for details.");
            }
        }
        public void Inline(List <CodeReferenceResultItem> dataList, bool externalChange, ref int errorRows)
        {
            // sort according to position
            dataList.Sort(new ResultItemsPositionCompararer <CodeReferenceResultItem>());

            // start with the last items - not necessary to adjust position of many items after replace
            for (int i = dataList.Count - 1; i >= 0; i--)
            {
                try {
                    CodeReferenceResultItem resultItem = dataList[i];

                    if (resultItem.MoveThisItem)   // the item was checked in the toolwindow grid
                    {
                        int absoluteStartIndex, absoluteLength;

                        // get text that replaces the result item
                        string text = GetReplaceString(resultItem);

                        // get position information about block to replace
                        TextSpan inlineSpan = GetInlineReplaceSpan(resultItem, out absoluteStartIndex, out absoluteLength);

                        string path = resultItem.SourceItem.GetFullPath();
                        if (RDTManager.IsFileOpen(path) && RDTManager.IsFileVisible(path)) // file is open
                        {
                            if (!buffersCache.ContainsKey(path))                           // file's buffer is not yet loaded
                            // load buffer
                            {
                                IVsTextLines textLines = DocumentViewsManager.GetTextLinesForFile(path, false);
                                buffersCache.Add(path, textLines);

                                IOleUndoManager m;
                                // load undo manager
                                int hr = textLines.GetUndoManager(out m);
                                Marshal.ThrowExceptionForHR(hr);
                                undoManagersCache.Add(path, m);
                            }

                            // replace the result item with the new text
                            int h = buffersCache[path].ReplaceLines(inlineSpan.iStartLine, inlineSpan.iStartIndex, inlineSpan.iEndLine, inlineSpan.iEndIndex,
                                                                    Marshal.StringToBSTR(text), text.Length, new TextSpan[] { inlineSpan });
                            Marshal.ThrowExceptionForHR(h);

                            // previous step caused undo unit to be added - remove it
                            List <IOleUndoUnit> units = undoManagersCache[path].RemoveTopFromUndoStack(1);

                            // and add custom undo unit which includes whole operation
                            AbstractUndoUnit newUnit = GetUndoUnit(resultItem, externalChange);
                            newUnit.AppendUnits.AddRange(units);
                            undoManagersCache[path].Add(newUnit);
                        }
                        else
                        {
                            if (!filesCache.ContainsKey(path))   // file is not yet loaded
                            // load the file and save it in cache
                            {
                                filesCache.Add(path, new StringBuilder(File.ReadAllText(path)));
                            }
                            StringBuilder b = filesCache[path];

                            // replace the text
                            b = b.Remove(absoluteStartIndex, absoluteLength);
                            b = b.Insert(absoluteStartIndex, text);
                            filesCache[path] = b;
                        }
                    }
                } catch (Exception ex) {
                    errorRows++;
                    VLOutputWindow.VisualLocalizerPane.WriteException(ex);
                }
            }

            foreach (var pair in filesCache)
            {
                if (RDTManager.IsFileOpen(pair.Key))
                {
                    RDTManager.SetIgnoreFileChanges(pair.Key, true);
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                    RDTManager.SetIgnoreFileChanges(pair.Key, false);
                    RDTManager.SilentlyReloadFile(pair.Key);
                }
                else
                {
                    File.WriteAllText(pair.Key, pair.Value.ToString());
                }
            }
            if (errorRows > 0)
            {
                throw new Exception("Error occured while processing some rows - see Output window for details.");
            }
        }