public static VSUndo StartUndo()
 {
     undoContext = ((DTE2)Package.GetGlobalService(typeof(DTE))).UndoContext;
     undoContext.Open(Guid.NewGuid().ToString());
     // return new instance for calling dispose to close current undocontext
     return(new VSUndo());
 }
Example #2
0
        protected int CreateEventHandler(string document, string codeBehind, string codeBehindFile, string className, string objectTypeName, string eventName, string eventHandlerName)
        {
            var binder = GetBinder(document, codeBehind, codeBehindFile);

            if (binder == null)
            {
                return(NativeMethods.E_FAIL);
            }

            CodeFunction codeFunction = null;
            UndoContext  undoContext  = binder.FileCodeModel.DTE.UndoContext;

            if (undoContext != null)
            {
                if (!undoContext.IsOpen)
                {
                    undoContext.Open(eventHandlerName, false);
                }
                else
                {
                    undoContext = null;
                }
            }
            try
            {
                codeFunction = binder.CreateEventHandler(codeBehindFile, className, objectTypeName, eventName, eventHandlerName);

                EditPoint point = codeFunction.StartPoint.CreateEditPoint();
                if (point != null)
                {
                    point.SmartFormat(codeFunction.EndPoint);
                }

                return(NativeMethods.S_OK);
            }
            finally
            {
                if (undoContext != null)
                {
                    if (codeFunction != null)
                    {
                        undoContext.Close();

                        var nemerleFileCodeModel = binder.FileCodeModel as Nemerle.VisualStudio.FileCodeModel.NemerleFileCodeModel;
                        if (nemerleFileCodeModel != null)
                        {
                            nemerleFileCodeModel.FlushChanges();
                        }
                    }
                    else
                    {
                        undoContext.SetAborted();
                    }
                }
            }
        }
Example #3
0
            public ScopedUndoContext(UndoContext context, string Name, bool Strict = false)
            {
                Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

                if (!context.IsOpen)
                {
                    uc = context;
                    uc.Open(Name, Strict);
                }
            }
Example #4
0
        /***************************************************************************
         * exec */
        /**
         * Retrieves the selected block of text and replaces it with the result of a
         * call to <c>convertBlock</c>.
         *
         * @param  sender  Command object.
         ***************************************************************************/
        public override void exec(object sender, EventArgs e)
        {
            /*----------------------------------------*/
            /* Get the document and selection. Indent */
            /* offset is current caret position.      */
            /*----------------------------------------*/
            Document      doc    = app.ActiveDocument;
            TextSelection select = (TextSelection)doc.Selection;
            VirtualPoint  top    = select.TopPoint;
            VirtualPoint  bottom = select.BottomPoint;
            int           indent = select.CurrentColumn - 1;

            /*--------------------------------------------*/
            /* Set edit points at the start and end of    */
            /* the lines where selection starts and ends. */
            /*--------------------------------------------*/
            EditPoint ep1 = top.CreateEditPoint();
            EditPoint ep2 = bottom.CreateEditPoint();

            ep1.MoveToLineAndOffset(top.Line, 1);
            ep2.MoveToLineAndOffset(bottom.Line, bottom.LineLength + 1);

            /*---------------------------------------*/
            /* Convert the block from the content of */
            /* the start and end line of selection.  */
            /*---------------------------------------*/
            string block = convertBlock(ep1.GetText(ep2), indent);

            if (block != null)
            {
                /*------------------------------------*/
                /* Open an undo context if none open. */
                /*------------------------------------*/
                UndoContext undo = app.UndoContext;

                if (!undo.IsOpen)
                {
                    undo.Open(GetType().Name, false);
                }

                /*----------------------------------------------------------*/
                /* Replace the selected block, move the caret to the indent */
                /* position on the last line, and close the Undo Context.   */
                /*----------------------------------------------------------*/
                ep1.Delete(ep2);
                ep1.Insert(block);

                select.MoveToLineAndOffset(ep1.Line, indent + 1, false);

                undo.Close();
            }
        }
Example #5
0
        public void Execute(string commandName, Action commandAction)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            // Put all of the changes in a single Undo context.
            UndoContext undo            = this.dte.UndoContext;
            bool        undoAlreadyOpen = undo.IsOpen;

            if (!undoAlreadyOpen)
            {
                if (string.IsNullOrEmpty(commandName))
                {
                    commandName = "Set Selected Text";
                }

                undo.Open(commandName + UndoContextSuffix, false);
            }

            try
            {
                commandAction();
            }
            catch (Exception ex)
            {
                // Most commands won't change anything until they try to push in the final SelectedText value.
                // But some commands (e.g., Sort Members) need to update things in intermediate steps (e.g.,
                // removing members from the editor's code model).  If any exception occurs, we need to abort
                // everything that was done in the current context to avoid data loss (e.g., losing the members
                // that were temporarily removed from the editor's code model).
                undo.SetAborted();

                // If the file is read-only (e.g., in source control) and the user cancels the edit,
                // then a COMException is thrown with HRESULT 0x80041005 (WBEM_E_TYPE_MISMATCH).
                // We'll ignore that exception, but we'll re-throw anything else.
                const uint WBEM_E_TYPE_MISMATCH = 0x80041005;
                if (!(ex is COMException) || ex.HResult != unchecked ((int)WBEM_E_TYPE_MISMATCH))
                {
                    throw;
                }
            }
            finally
            {
                // Make sure we close the UndoContext.
                if (!undoAlreadyOpen && !undo.IsAborted)
                {
                    undo.Close();
                }
            }
        }
Example #6
0
        /// <summary>Extracts the string to a resource file and replaces it with a reference to the new entry</summary>
        /// <param name="file">A resource file to extract string to</param>
        /// <param name="resourceName">Name ot be given to the resource</param>
        public void ExtractStringToResource(ResourceFile file, string resourceName)
        {
            UndoContext undo = StringToExtract.Parent.Document.DTE.UndoContext;

            undo.Open(Strings.ExtractResourceUndoContextName);
            try {
                Project project = null;
                try { project = this.StringToExtract.Parent.Document.ProjectItem.ContainingProject; } catch { }
                string reference = this.actionObject.GetResourceReference(file, resourceName, project, stringInstance);
                reference = this.StringToExtract.GetShortestReference(reference, this.StringToExtract.GetImportedNamespaces());
                this.StringToExtract.Replace(reference);
                undo.Close();
            } catch {
                undo.SetAborted();
                throw;
            }
        }
Example #7
0
        public void CommentSelectedText()
        {
            TextSelection textSelection = ActiveTextSelection;

            if (textSelection != null)
            {
                //editpoint,virsualpoint 都继承于TextPoint
                EditPoint topEditPoint = textSelection.TopPoint.CreateEditPoint();
                TextPoint bottomPoint  = textSelection.BottomPoint;

                UndoContext undoContext = ApplicationObject.UndoContext;
                undoContext.Open("Comment Region");
                while (topEditPoint.LessThan(bottomPoint))
                {
                    topEditPoint.Insert("//");
                    topEditPoint.LineDown();
                    topEditPoint.StartOfLine();
                }
                undoContext.Close();
            }
        }
        /// <summary>
        ///      Implements the Exec method of the IDTCommandTarget interface.
        ///      This is called when the command is invoked.
        /// </summary>
        /// <param term='commandName'>
        ///		The name of the command to execute.
        /// </param>
        /// <param term='executeOption'>
        ///		Describes how the command should be run.
        /// </param>
        /// <param term='varIn'>
        ///		Parameters passed from the caller to the command handler.
        /// </param>
        /// <param term='varOut'>
        ///		Parameters passed from the command handler to the caller.
        /// </param>
        /// <param term='handled'>
        ///		Informs the caller if the command was handled or not.
        /// </param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, EnvDTE.vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == EnvDTE.vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName == "SynchAdd.Connect.SynchAdd")
                {
                    handled = true;

                    if (((Project)((System.Array)applicationObject.ActiveSolutionProjects).GetValue(0)).Kind !=
                        VSLangProj.PrjKind.prjKindCSharpProject)
                    {
                        System.Windows.Forms.MessageBox.Show("Sorry - C# only.");
                        return;
                    }

                    //get target class and modification requirements
                    UndoContext undoCtxt = null;
                    try{
                        TagetClassSelect tcs = new TagetClassSelect(applicationObject);
                        tcs.ShowDialog();
                        CodeClass cc = tcs.TargetClass;
                        if (cc == null)
                        {
                            return;
                        }
                        undoCtxt = applicationObject.UndoContext;
                        undoCtxt.Open("Base class synch. modifications", false);
                        CodeProcessor processor = new CodeProcessor(cc);
                        if (!processor.MakeBaseClassCompatiableWithSyncPattern())
                        {
                            if (undoCtxt.IsOpen)
                            {
                                undoCtxt.SetAborted();
                                if (undoCtxt.IsOpen)
                                {
                                    undoCtxt.Close();
                                }
                                return;
                            }
                        }
                        undoCtxt.Close();
                        undoCtxt.Open("Synch. class creation", false);
                        if (processor.CreateSynchClass())
                        {
                            System.Windows.Forms.MessageBox.Show("Synch. type created.");
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("Error during synch. type creation.");
                            undoCtxt.SetAborted();
                            cc.ProjectItem.Document.Undo();
                        }
                        if (undoCtxt.IsOpen)
                        {
                            undoCtxt.Close();
                        }
                    }
                    catch (Exception e) {
                        System.Windows.Forms.MessageBox.Show("The following exception occured - (" +
                                                             e.Message + ").\nThe synchronized wrapped cannot be added at this time.");
                        if (undoCtxt != null && undoCtxt.IsOpen)
                        {
                            undoCtxt.SetAborted();
                            undoCtxt.Close();
                        }
                    }

                    return;
                }
            }
        }
Example #9
0
            private void AddPageMethod()
            {
                try
                {
                    // Reset to the default name of the page method
                    string name = _signature.DeclaringType.Name;

                    // Ensure we don't have a ServicePath set
                    PropertyDescriptor pagePathProperty = TypeDescriptor.GetProperties(Component)[_attribute.ServicePathProperty];
                    if (pagePathProperty != null)
                    {
                        string servicePath = pagePathProperty.GetValue(Component) as string;
                        if (!string.IsNullOrEmpty(servicePath))
                        {
                            ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because the extender is using web service \"{1}\" instead!", name, servicePath));
                            return;
                        }
                    }

                    // Optionally set UseContextKey to true
                    if (_attribute.IncludeContextParameter)
                    {
                        PropertyDescriptor useContextKeyProperty = TypeDescriptor.GetProperties(Component)[_attribute.UseContextKeyProperty];
                        if (useContextKeyProperty != null)
                        {
                            useContextKeyProperty.SetValue(Component, true);
                        }
                    }

                    // Open the code for the page
                    IEventBindingService bindingService;
                    if (!EnsureService(out bindingService))
                    {
                        return;
                    }
                    bindingService.ShowCode();

                    // Load the automation service
                    object _dte = GetService(ReferencedAssemblies.EnvDTE.GetType("EnvDTE._DTE"));
                    if (_dte == null)
                    {
                        ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because {1} could not be acquired!", _signature.DeclaringType.Name, "EnvDTE._DTE"));
                        return;
                    }
                    DTE2 automation = new DTE2(_dte);

                    try
                    {
                        // Get the CodeModel for the file
                        FileCodeModel2 fileCodeModel = LoadFileCodeModel(automation.ActiveDocument.ProjectItem);
                        if (fileCodeModel == null || fileCodeModel.Reference == null)
                        {
                            ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because no CodeBehind or CodeFile file was found!", name));
                            return;
                        }

                        // Get the class for the page
                        IDesignerHost host;
                        if (!EnsureService(out host))
                        {
                            return;
                        }
                        CodeClass2 classModel = FindClass(fileCodeModel, host.RootComponentClassName);
                        if (classModel == null || classModel.Reference == null)
                        {
                            ShowMessage(string.Format(CultureInfo.CurrentCulture, "Cannot create page method \"{0}\" because no CodeBehind or CodeFile file was found!", name));
                            return;
                        }

                        // Either set the ServiceMethod to the default name, or use an existing value to look it up
                        PropertyDescriptor pageMethodProperty = TypeDescriptor.GetProperties(Component)[_attribute.ServiceMethodProperty];
                        if (pageMethodProperty != null)
                        {
                            string value = pageMethodProperty.GetValue(Component) as string;
                            if (!string.IsNullOrEmpty(value))
                            {
                                // Use the existing value as the name
                                name = value;
                            }
                            else
                            {
                                // Ensure we get a unique name when use the default value
                                string defaultName = name;
                                int    i           = 2;
                                while (FindMethod(classModel, name, _signature) != null)
                                {
                                    name = defaultName + i++;
                                }

                                // Set the value to the default name
                                pageMethodProperty.SetValue(Component, name);
                            }
                        }

                        // Get the UndoContext for the currently open document
                        // (since creating a DesignerTransaction will refer to the aspx page,
                        // not the code behind that we opened)
                        UndoContext undo = automation.UndoContext;
                        if (undo != null && undo.Reference != null && undo.IsOpen)
                        {
                            undo = null;
                        }
                        try
                        {
                            CodeFunction2 method = FindMethod(classModel, name, _signature);
                            if (method != null && method.Reference != null)
                            {
                                if (PageMethodNeedsRepair(method) && (ShowMessage(string.Format(CultureInfo.CurrentCulture, "Would you like to repair the existing page method \"{0}\"?", name), MessageBoxButtons.YesNo) == DialogResult.Yes))
                                {
                                    // Repair an existing page method
                                    if (undo != null)
                                    {
                                        undo.Open(string.Format(CultureInfo.CurrentCulture, "Repair \"{0}\" page method", name), false);
                                    }
                                    RepairPageMethod(method);
                                }
                            }
                            else
                            {
                                // Create a new page method
                                if (undo != null)
                                {
                                    undo.Open(string.Format(CultureInfo.CurrentCulture, "Add \"{0}\" page method", name), false);
                                }
                                CreatePageMethod(classModel, name);
                            }
                        }
                        finally
                        {
                            if (undo != null && undo.IsOpen)
                            {
                                undo.Close();
                            }
                        }
                    }
                    finally
                    {
                        UnloadWebProjectItem(automation.ActiveDocument.ProjectItem);
                    }
                }
                catch (Exception ex)
                {
                    ShowMessage(string.Format(CultureInfo.CurrentCulture, "Unexpected error ({0}): {1}{2}{3}", ex.GetType().Name, ex.Message, Environment.NewLine, ex.StackTrace));
                }
            }
Example #10
0
 //这里返回VSUndo是为了使用using调用结束的时候,自动调用dispose方法来关闭undocontext
 public static VSUndo StartUndo()
 {
     undoContext = ApplicationObject.UndoContext;
     undoContext.Open(Guid.NewGuid().ToString());
     return(new VSUndo());
 }
Example #11
0
 //这里返回VSUndo是为了使用using调用结束的时候,自动调用dispose方法来关闭undocontext
 public static VSUndo StartUndo()
 {
     undoContext = ApplicationObject.UndoContext;
     undoContext.Open(Guid.NewGuid().ToString());
     return new VSUndo();
 }
Example #12
0
        /// <summary>实现 IDTCommandTarget 接口的 Exec 方法。此方法在调用该命令时调用。</summary>
        /// <param term='commandName'>要执行的命令的名称。</param>
        /// <param term='executeOption'>描述该命令应如何运行。</param>
        /// <param term='varIn'>从调用方传递到命令处理程序的参数。</param>
        /// <param term='varOut'>从命令处理程序传递到调用方的参数。</param>
        /// <param term='handled'>通知调用方此命令是否已被处理。</param>
        /// <seealso class='Exec' />
        public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)
        {
            handled = false;
            if (executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)
            {
                if (commandName == "MyCodeAddin.Connect.MyCodeAddin")
                {
                    //此处添加自己的逻辑代码
                    #region
                    //Point pos = new Point();
                    //var aa = GetCaretPos(ref pos);
                    #endregion


                    //TextPoint pt;
                    //var ab = pt.CodeElement[vsCMElement



                    //获取被选中文件路径及文件名
                    string fileFullPath = GetSelecteditempath();
                    //获取被选中文件路径(不包含文件名)
                    string filePath = GetSelectedProjectPath();
                    //获取被选中的工程
                    Project project = GetSelectedProject();

                    SelectedItem item = GetProjectItemSel();

                    //文档
                    Document      doc     = _applicationObject.ActiveDocument;
                    TextDocument  textDoc = (TextDocument)_applicationObject.ActiveDocument.Object("");
                    TextSelection texSel  = (TextSelection)_applicationObject.ActiveDocument.Selection;


                    EditPoint Start = texSel.AnchorPoint.CreateEditPoint();
                    TextPoint endpt = texSel.BottomPoint;

                    UndoContext undoObj = _applicationObject.UndoContext;
                    undoObj.Open("Comment Region");

                    #region Business Methods

                    //<# foreach(var item in Items)
                    //{
                    // #>

                    //public <#= item.Type #> <#= item.Name #>
                    //{
                    //	get ;
                    //	set ;
                    //}

                    //<#}#>

                    #endregion

                    //Do While (Start.LessThan(endpt))
                    Start.Insert("public  {get;set;}");
                    Start.LineDown();
                    Start.StartOfLine();
                    //Loop
                    undoObj.Close();

                    string actDocName = doc.Name;

                    //var er=textPT.get_CodeElement(vsCMElement.vsCMElementClass);


                    //var pt = textPT.CodeElement[vsCMElement.vsCMElementClass];

                    //MainForm mainF = new MainForm();
                    //mainF.applicationObject = _applicationObject;
                    //mainF.project = project;
                    //mainF.fileFullPath = fileFullPath;
                    //mainF.filePath = filePath;
                    //mainF.Show();

                    //handled = true;
                    //return;


                    //Form1 mainF = new Form1();
                    //mainF.applicationObject = _applicationObject;
                    //mainF.project = project;
                    //mainF.projectSel = item;
                    //mainF.fileFullPath = fileFullPath;
                    //mainF.filePath = filePath;

                    //mainF.doc = doc;
                    //mainF.textDoc = textDoc;

                    //mainF.texSel = texSel;
                    //mainF.start = Start;
                    //mainF.undoObj = undoObj;
                    //mainF.Show();

                    handled = true;
                    return;

                    //if (!GetSelecteditempath().ToLower().EndsWith(".cs"))
                    //{
                    //	return;
                    //}
                    ////读取选中类文件
                    //FileStream fs = new FileStream(GetSelecteditempath(), FileMode.Open, FileAccess.Read);
                    //StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("GB2312"));
                    ////将文件内容编译生成对象
                    //string conString = sr.ReadToEnd();
                    //object classobject = DynamicCompiling.Compo(conString);

                    //string aa = classobject.GetType().Namespace;

                    //if (classobject is string)
                    //{
                    //	MessageBox.Show("动态编译失败:" + "\r\n" + classobject, "类文件编译错误!");
                    //	sr.Close();
                    //	fs.Close();
                    //	handled = true;
                    //	return;
                    //}

                    ////创建代码文件,并添加到项目中
                    //Createcode(classobject, GetSelectedProject(), GetSelectedProjectPath());

                    //sr.Close();
                    //fs.Close();

                    //handled = true;
                }
            }
        }