예제 #1
0
        private void ApplyINPCBasic(object sender, ApplyContentEventArgs ea)
        {
            Property property = GetActiveProperty(ea.Element);

            ConvertProperty(ea.TextDocument, property, false, ea.ClassInterfaceOrStruct);
            ImplementInterfaceIfNotPresent(ea.TextDocument, ea.ClassInterfaceOrStruct, true);
        }
 private void refactoringProvider1_Apply(object sender, ApplyContentEventArgs ea)
 {
     if (enabled)
     {
         executeRefactoring(ea);
     }
 }
        private void codeProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            //select the entire block that belongs to the active element.
            _activeElement.SelectFullBlock();
            //_fullBlockText = Environment.NewLine + CodeRush.Selection.Text;
            //CodeRush.Selection.Delete();
            _activeBlock = CodeRush.TextViews.Active.Selection;

            //get the document for the parent class and activate it.
            Document parentDocument = CodeRush.Documents.Get(_parentClass.FileNode.Name);
            CodeRush.Documents.Activate(parentDocument);

            //now select the target location in the parent class' document.
            if(_parentClass.FirstChild == null)
            {
                //this is temporary. i would like to use the "cc" command in the dxcore but dont know how...
                actionHint.Color = Color.Orange;
                actionHint.Text = "Add a constructor first..";
                actionHint.PointTo(_parentClass.NameRange.End.Line, _parentClass.NameRange.End.Offset);
                _activeBlock.Clear();
            }
            else 
            {
                targetPicker.Start(_parentClass.View as TextView,_parentClass.FirstChild);
            }
        }
        private void ApplyINPCBasic(object sender, ApplyContentEventArgs ea)
        {
            Property property = GetActiveProperty(ea.Element);
            ConvertProperty(ea.TextDocument, property, false, ea.ClassInterfaceOrStruct);
            ImplementInterfaceIfNotPresent(ea.TextDocument, ea.ClassInterfaceOrStruct, true);

        }
		/// <summary>
		/// TODO Add summary
		/// </summary>
		private void moveTypesToFilesRefactoring_Apply(object sender, ApplyContentEventArgs ea)
		{
			SourceFile sourceFile = CodeRush.Source.ActiveSourceFile;

			// Get all types
			var allTypes = sourceFile.AllTypes;

			// Filter to classes
			var allClassesDesc = allTypes.Cast<TypeDeclaration>()
				.Where(td => td.ElementType == LanguageElementType.Class)
				.OrderByDescending(td => td.NameRange.Start);

			// Move to files
			RefactoringProviderBase moveRefactoring = CodeRush.Refactoring.Get("Move Type to File");
			foreach (TypeDeclaration classDecl in allClassesDesc)
			{
				// Skip last class
				if (allClassesDesc.Count() == 1)
					continue;

				// Move to files
				CodeRush.Caret.MoveTo(classDecl.NameRange.Start);
				CodeRush.SmartTags.UpdateContext();
				moveRefactoring.Execute();
				CodeRush.Documents.Activate((Document)sourceFile.Document);
			}

			// Rename the file to match last type
			RefactoringProviderBase renameRefactoring = CodeRush.Refactoring.Get("Rename File to Match Type");
			CodeRush.SmartTags.UpdateContext();
			renameRefactoring.Execute();
		}
예제 #6
0
        private void ConvertToMultilineComment_Execute(Object sender, ApplyContentEventArgs ea)
        {
            var     Comment = ea.CodeActive as Comment;
            Comment FirstComment;
            Comment LastComment;

            Comment.GetFirstAndLastConnectedComments(out FirstComment, out LastComment);

            string  CommentText    = Environment.NewLine;
            Comment CurrentComment = FirstComment;
            string  Whitespace     = CodeRush.Documents.GetLeadingWhiteSpace(FirstComment.Range.Start.Line);

            do
            {
                CommentText   += Whitespace + CurrentComment.Name + Environment.NewLine;
                CurrentComment = CurrentComment.NextConnectedComment;
            } while (CurrentComment != null);

            CommentText += Whitespace;
            // Determine First Comment

            var         NewComment   = GetCommentMultiline(CommentText);
            SourceRange CommentRange = new SourceRange(FirstComment.Range.Start, LastComment.Range.End);
            var         ActiveDoc    = CodeRush.Documents.ActiveTextDocument;

            ActiveDoc.QueueReplace(CommentRange, NewComment);
            ActiveDoc.ApplyQueuedEdits("Convert to Multiline Comment", true);
        }
예제 #7
0
        private void codeProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            //select the entire block that belongs to the active element.
            _activeElement.SelectFullBlock();
            //_fullBlockText = Environment.NewLine + CodeRush.Selection.Text;
            //CodeRush.Selection.Delete();
            _activeBlock = CodeRush.TextViews.Active.Selection;

            //get the document for the parent class and activate it.
            Document parentDocument = CodeRush.Documents.Get(_parentClass.FileNode.Name);

            CodeRush.Documents.Activate(parentDocument);

            //now select the target location in the parent class' document.
            if (_parentClass.FirstChild == null)
            {
                //this is temporary. i would like to use the "cc" command in the dxcore but dont know how...
                actionHint.Color = Color.Orange;
                actionHint.Text  = "Add a constructor first..";
                actionHint.PointTo(_parentClass.NameRange.End.Line, _parentClass.NameRange.End.Offset);
                _activeBlock.Clear();
            }
            else
            {
                targetPicker.Start(_parentClass.View as TextView, _parentClass.FirstChild);
            }
        }
예제 #8
0
        private void ReplaceGetElementById(ApplyContentEventArgs ea)
        {
            MethodCallExpression ex = ea.Element as MethodCallExpression;
            string source           = GetSource(ex);

            ea.TextDocument.Replace(ex.Range, source, "Convert to jQuery", true);
        }
		/// <summary>
		/// TODO Add summary
		/// </summary>
		private void createPartialClassesCodeProvider_Apply(object sender, ApplyContentEventArgs ea)
		{
			SourceFile sourceFile = CodeRush.Source.ActiveSourceFile;

			// Get all types
			var allTypes = sourceFile.AllTypes;

			// Filter to classes
			var allPartialClasses = allTypes.Cast<TypeDeclaration>()
				.Where(td => td.ElementType == LanguageElementType.Class && td.IsPartial);

			// Generate path
			string filePath = Path.Combine(Path.GetDirectoryName(sourceFile.FilePath), "PartialClasses.cs");
			using (StreamWriter sourceFileStream = File.CreateText(filePath))
			{
				string namespaceName = allPartialClasses.First().GetNamespace().FullName;
				sourceFileStream.WriteLine("namespace " + namespaceName);
				sourceFileStream.WriteLine("{");
				sourceFileStream.WriteLine("\tusing System;");
				sourceFileStream.WriteLine();

				// Generate partial classes
				var lastType = allPartialClasses.Last();
				foreach (TypeDeclaration type in allPartialClasses)
				{
					string className = type.Name;

					// TODO: Change string builder into code generator
					sourceFileStream.WriteLine("\t/// <summary>");
					sourceFileStream.WriteLine("\t/// Your comment here");
					sourceFileStream.WriteLine("\t/// </summary>");
					sourceFileStream.WriteLine("\tpublic partial class " + className);
					sourceFileStream.WriteLine("\t{");

					var keySearch = type.AllMembers.Cast<Member>()
						.Where(m => (m.ElementType == LanguageElementType.Property || m.ElementType == LanguageElementType.Variable) &&
							m.Attributes.Cast<DevExpress.CodeRush.StructuralParser.Attribute>().Where(a => a.Name == "Key").Any());
					string keyName = (keySearch.Any()) ? keySearch.First().Name : String.Empty;
					if (!string.IsNullOrEmpty(keyName))
					{
						Member keyMember = keySearch.First();
						sourceFileStream.WriteLine();
						sourceFileStream.WriteLine("\t\t/// <summary>");
						sourceFileStream.WriteLine("\t\t/// Your comment here");
						sourceFileStream.WriteLine("\t\t/// </summary>");
						sourceFileStream.WriteLine("\t\tpublic static " + className + " GetByKey(" + keyMember.MemberType + " key, Session session) {");
						sourceFileStream.WriteLine("\t\t\t" + "return session.FindObject<" + className + ">(" + className + ".Fields." + keyName + ");");
						sourceFileStream.WriteLine("\t\t}");
					}

					sourceFileStream.WriteLine("\t} // " + className);
					if (type != lastType)
						sourceFileStream.WriteLine();
				}
				sourceFileStream.WriteLine("} // " + namespaceName);
			}

			// Add file to solution
			CodeRush.Solution.AddFileToProject(CodeRush.Source.ActiveProject.Name, filePath);
		}
예제 #10
0
        private void SortFormatTokens_Execute(Object sender, ApplyContentEventArgs ea)
        {
            MethodCallExpression TheStringFormat = _PrimitiveString.Parent as MethodCallExpression;
            string TheString = _PrimitiveString.Name;
            List<Expression> TheArguments = TheStringFormat.Arguments.ToList<Expression>().Skip(1).ToList<Expression>();
            SourceRange TheStringFormatRange = TheStringFormat.Range;

            //Get List of Tokens
            var Tokens = new TokenGatherer().GetTokens(TheString);

            // Determine "Sort" map.
            List<MapItem> Map = MapGenerator.GenerateMap(from item in Tokens select item.Index);

            // Affect string using map
            TheString = new StringTokenRenumberer().Renumber(TheString, Tokens, Map);

            // Affect params using map?
            TheArguments = new ListReorderer().Reorder(TheArguments, Tokens, Map);

            // Write TheString and TheList back to the code.
            TheStringFormat.Arguments.Clear();
            TheStringFormat.Arguments.Add(new PrimitiveExpression(TheString));
            TheStringFormat.Arguments.AddRange(TheArguments);
            string TheNewCode = CodeRush.CodeMod.GenerateCode(TheStringFormat, true);
            ea.TextDocument.SetText(TheStringFormatRange, TheNewCode);
        }
예제 #11
0
        private void NameMethodAfterFact_Execute(Object sender, ApplyContentEventArgs ea)
        {
            // This method is executed when the system executes your refactoring
            string NewName = Regex.Replace(DisplayNameArg.RightSide.Name.RemoveQuotes(), "[^A-Za-z0-9]", "_");

            ea.TextDocument.QueueReplace((ea.Element as Method).NameRange, NewName);
            ea.TextDocument.ApplyQueuedEdits("Renamed Fact Method to Reflect DisplayName");
        }
예제 #12
0
        void refactoringProviderWORegions_Apply(object sender, ApplyContentEventArgs ea)
        {
            ClassOrganizer organizer = new ClassOrganizer();

            organizer.Organize(CodeRush.Documents.ActiveTextDocument,
                               CodeRush.Source.ActiveType,
                               false);
        }
예제 #13
0
        private void RemoveStringToken_Apply(Object sender, ApplyContentEventArgs ea)
        {
            using (ea.TextDocument.NewCompoundAction("Remove string Token"))
            {
                PrimitiveExpression ThePrimitive = (PrimitiveExpression)CodeRush.Source.GetNodeAt(CodeRush.Caret.SourcePoint);
                SourceRange ReplaceRange = ThePrimitive.NameRange;
                SourceRange StringFormatRange = SourceRange.Empty;
                if (WithinStringFormat(ThePrimitive))
                {
                    StringFormatRange = ((MethodCallExpression)ThePrimitive.Parent).Range;
                }
                string text = ThePrimitive.Name;
                string token = GetTokenNearCaret(ThePrimitive);
                IHasArguments MCE = (IHasArguments)ThePrimitive.Parent;

                int tokenOffset = CodeRush.Caret.SourcePoint.Offset - ThePrimitive.Range.Start.Offset; // text.IndexOf(token);
                int caretOffset = tokenOffset - text.LastIndexOf("{", tokenOffset);
                int tokenLength = token.Length;
                int tokenID = int.Parse(token.Substring(1, tokenLength - 2));

                var HigherTokenNumbers = from number in new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
                                         where text.IndexOf("{" + number + "}") > -1
                                         && number > tokenID
                                         orderby number ascending
                                         select number;

                // Remove Specific occurance of {2} or whatever
                text = text.Remove(tokenOffset - caretOffset, tokenLength);

                // Detect additional copies of {2}.
                tokenOffset = text.IndexOf(token);
                // if {2} cannot be found assume it has been eliminated
                if (tokenOffset == -1)
                {
                    // Token is now entirely missing from the text. Need to shuffle higher tokens up

                    // Renumber Remaining Tokens
                    // Renumber {3} -> {Highest} with {2} -> {Highest-1}
                    if (HigherTokenNumbers.Count() > 0)
                    {
                        int HigherTokensCapture = HigherTokenNumbers.Last();
                        for (int tokenIndex = tokenID; tokenIndex < HigherTokensCapture; tokenIndex++)
                        {
                            text = text.Replace("{" + (tokenIndex + 1) + "}", "{" + (tokenIndex) + "}");
                        }
                    }

                    MCE.Arguments.RemoveAt(tokenID + 1);
                    var MCEAsLang = (LanguageElement)MCE;
                    ea.TextDocument.SetText(MCEAsLang.Range, CodeRush.CodeMod.GenerateCode(MCEAsLang));
                }

                // Write string back over original string.
                if (!text.Contains("{") && !(StringFormatRange.IsEmpty))
                    ReplaceRange = StringFormatRange;
                ea.TextDocument.SetText(ReplaceRange, text);
            }
        }
        private void ChangeToFieldCallRefactoringProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            var    property       = ea.Element.GetProperty();
            var    toReplace      = GetCodeElementToReplace(ea.Element, property);
            var    elementBuilder = ea.NewElementBuilder();
            string generatedCode  = GetChangeToFieldCallCode(elementBuilder, toReplace, property);

            ea.TextDocument.Replace(toReplace.Range, generatedCode, "Change to field call", true);
        }
 private void cpConvertToJQuery_Apply(object sender, ApplyContentEventArgs ea)
 {
     if (!IsAvailable(ea.Element))
         return;
     if (ea.Element is MethodCallExpression)
         ReplaceGetElementById(ea);
     else if (ea.Element is ElementReferenceExpression)
         ReplaceGetElementProperty(ea);
 }
예제 #16
0
        private void CorrectReturnType_Apply(Object sender, ApplyContentEventArgs ea)
        {
            Method method = ea.Element.GetParentMethod();
            SourceRange TypeRange = GetMethodReturnTypeRange(method);
            var Return = (Return)ea.Element;

            string Code = GetExpressionTypeCode(Return.Expression);
            ea.TextDocument.SetText(TypeRange, Code);
        }
예제 #17
0
        private void DeclareClassInSpecificProject_Apply(object sender, ApplyContentEventArgs ea)
        {
            string selectedProjectName = ea.SelectedSubMenuItem.Name;

            CodeRush.UndoStack.BeginUpdate("Declare Class in Project");
            CodeRush.Markers.Drop();

            _declareClassInProject.Apply(ea, selectedProjectName);
        }
        private void DeclareClassInSpecificProject_Apply(object sender, ApplyContentEventArgs ea)
        {
            string selectedProjectName = ea.SelectedSubMenuItem.Name;

            CodeRush.UndoStack.BeginUpdate("Declare Class in Project");
            CodeRush.Markers.Drop();

            _declareClassInProject.Apply(ea, selectedProjectName);

        }
예제 #19
0
		void rpRenameXamlNamespacePrefix_Apply(object sender, ApplyContentEventArgs ea)
    {
      IEnumerable<TagPrefix> tagPrefixes = GetTagPrefixes(ea.Element);

			ILinkedIdentifierList linkedIdentifiers = CodeRush.LinkedIdentifiers.ActiveStorage.NewList();
			foreach (TagPrefix tp in tagPrefixes)
        linkedIdentifiers.Add(tp.Range);

      CodeRush.LinkedIdentifiers.ActiveStorage.Invalidate();
    }
		void refactoringProvider_Apply(object sender, ApplyContentEventArgs ea)
		{
			var doc = CodeRush.Documents.ActiveTextDocument;
			var oldRefs = doc.GetNamespaceReferences();
			var oldRange = new SourceRange(oldRefs.First().Range.Start, 
										   oldRefs.Last().Range.End);

			var newRefs = SortReferencesByScope(oldRefs);
			var newCode = newRefs.OfType<LanguageElement>().GenerateCode();
			doc.Replace(oldRange, newCode, "Sorted Namespace References by Scope");
		}
예제 #21
0
 private void SplitTag_Apply(Object sender, ApplyContentEventArgs ea)
 {
     SourceRange range = ea.Element.Parent.Parent.Range;
     SP.HtmlElement tag = (SP.HtmlElement)ea.Element.Parent;
     string code = String.Format("</{0}>{1}<{0}>", tag.Name, System.Environment.NewLine);
     using (ea.TextDocument.NewCompoundAction("Split Tag"))
     {
         ea.TextDocument.InsertText(ea.Selection.StartSourcePoint, code);
         ea.TextDocument.Format(range, true);
     }
 }
예제 #22
0
        void refactoringProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            var doc      = CodeRush.Documents.ActiveTextDocument;
            var oldRefs  = doc.GetNamespaceReferences();
            var oldRange = new SourceRange(oldRefs.First().Range.Start,
                                           oldRefs.Last().Range.End);

            var newRefs = SortReferencesByScope(oldRefs);
            var newCode = newRefs.OfType <LanguageElement>().GenerateCode();

            doc.Replace(oldRange, newCode, "Sorted Namespace References by Scope");
        }
        private void MoveTypeToFileInSpecificProjectProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            string selectedProjectName = ea.SelectedSubMenuItem.Name;

            CodeRush.UndoStack.BeginUpdate("Move Type To File in Project");
            CodeRush.Markers.Drop();

            string filename = _moveTypeToFile.Apply(ea, selectedProjectName);

            CodeRush.File.Activate(filename);
            CodeRush.Documents.Format();
        }
 private void cpRemoveOuterBlock_Apply(object sender, ApplyContentEventArgs ea)
 {
     if (_NewCode == null)
     {
         CalculateCode(ea.Element as ParentingStatement);
     }
     ea.TextDocument.QueueDelete(_DeleteRange);
     ea.TextDocument.QueueInsert(_DeleteRange.Top, _NewCode);
     ea.TextDocument.ApplyQueuedEdits("Remove Outer Block", true);
     CodeRush.Caret.MoveTo(_DeleteRange.Top);
     _NewCode = null;
 }
예제 #25
0
        private void rpUseNamedParameters_Apply(object sender, ApplyContentEventArgs ea)
        {
            LanguageElement originalCall  = GetMethodCall(ea.Element);
            string          generatedCode = GetGeneratedCode(originalCall);

            if (String.IsNullOrEmpty(generatedCode))
            {
                return;
            }

            ea.TextDocument.SetText(originalCall.Range, generatedCode);
        }
예제 #26
0
        private void MoveTypeToFileInSpecificProjectProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            string selectedProjectName = ea.SelectedSubMenuItem.Name;

            CodeRush.UndoStack.BeginUpdate("Move Type To File in Project");
            CodeRush.Markers.Drop();

            string filename = _moveTypeToFile.Apply(ea, selectedProjectName);

            CodeRush.File.Activate(filename);
            CodeRush.Documents.Format();
        }
        /// <summary>
        /// Handles the Apply event of the cpCreateContract control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="ea">The <see cref="DevExpress.CodeRush.Core.ApplyContentEventArgs"/> instance containing the event data.</param>
        private void Apply(object sender, ApplyContentEventArgs ea)
        {
            // Must have cached instance of interface and interface declaration.
            if (this.activeInterface == null)
            {
                return;
            }

            if (ea.TextDocument == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(this.interfaceFilePath))
            {
                return;
            }

            if (this.interfaceSourceFile == null)
            {
                return;
            }

            if (this.codeRushProxy == null)
            {
                return;
            }

            if (this.cpCreateContract == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(this.interfaceName))
            {
                return;
            }

            var interfaceUpdater = new InterfaceUpdater(
                ea.TextDocument,
                this.activeInterface,
                this.interfaceSourceFile,
                this.interfaceFilePath,
                this.interfaceName);
            var contractClassBuilder = new ContractClassBuilder(interfaceUpdater, this.codeRushProxy);

            using (this.codeRushProxy.TextBuffers.NewMultiFileCompoundAction(this.cpCreateContract.ActionHintText))
            {
                this.codeRushProxy.Markers.Drop(MarkerStyle.Standard);
                interfaceUpdater.UpdateInterface();
                contractClassBuilder.CreateContractClassFile();
            }
        }
    /// <summary>
    /// Handles the Apply event of the cpCreateContract control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="ea">The <see cref="DevExpress.CodeRush.Core.ApplyContentEventArgs"/> instance containing the event data.</param>
    private void Apply(object sender, ApplyContentEventArgs ea)
    {
      // Must have cached instance of interface and interface declaration.
      if (this.activeInterface == null)
      {
        return;
      }

      if (ea.TextDocument == null)
      {
        return;
      }

      if (string.IsNullOrEmpty(this.interfaceFilePath))
      {
        return;
      }

      if (this.interfaceSourceFile == null)
      {
        return;
      }

      if (this.codeRushProxy == null)
      {
        return;
      }

      if (this.cpCreateContract == null)
      {
        return;
      }

      if (string.IsNullOrEmpty(this.interfaceName))
      {
        return;
      }

      var interfaceUpdater = new InterfaceUpdater(
        ea.TextDocument,
        this.activeInterface, 
        this.interfaceSourceFile,
        this.interfaceFilePath,
        this.interfaceName);
      var contractClassBuilder = new ContractClassBuilder(interfaceUpdater, this.codeRushProxy);
      using (this.codeRushProxy.TextBuffers.NewMultiFileCompoundAction(this.cpCreateContract.ActionHintText))
      {
        this.codeRushProxy.Markers.Drop(MarkerStyle.Standard);
        interfaceUpdater.UpdateInterface();
        contractClassBuilder.CreateContractClassFile();
      }
    }
예제 #29
0
        void rpRenameXamlNamespacePrefix_Apply(object sender, ApplyContentEventArgs ea)
        {
            IEnumerable <TagPrefix> tagPrefixes = GetTagPrefixes(ea.Element);

            ILinkedIdentifierList linkedIdentifiers = CodeRush.LinkedIdentifiers.ActiveStorage.NewList();

            foreach (TagPrefix tp in tagPrefixes)
            {
                linkedIdentifiers.Add(tp.Range);
            }

            CodeRush.LinkedIdentifiers.ActiveStorage.Invalidate();
        }
        private void cpMoveToSetup_Apply(object sender, ApplyContentEventArgs ea)
        {
            var containingMethod = _parentAssignment.Parent;
            containingMethod.RemoveNode(_parentAssignment);
            
            _setupMethod.AddDetailNode(_parentAssignment);

            ea.TextDocument.Replace(_parentAssignment.Range, string.Empty, string.Empty, true);
            var insertionLine = _setupMethod.BlockEnd.Bottom.Line;
            ea.TextDocument.InsertText(insertionLine, _setupMethod.BlockEnd.Bottom.Offset - 1, CodeRush.Language.GenerateElement(_parentAssignment));
            ea.TextDocument.Format(_setupMethod.Range);

        }
예제 #31
0
        private void cpAssignmentExpressionToEqualityCheck_Apply(object sender, ApplyContentEventArgs ea)
        {
            AssignmentExpression assignmentExpression = GetAssignmentExpression(ea.Element);

            if (assignmentExpression == null)
            {
                return;
            }
            ea.TextDocument.Replace(assignmentExpression.Range,
                                    GetNewEqualityTestCode(assignmentExpression),
                                    "Convert assignment to equality check.",
                                    true);
        }
 internal void ReplaceGetElementProperty(ApplyContentEventArgs ea)
 {
     ElementReferenceExpression ex = ea.Element as ElementReferenceExpression;
     var elementName = ex.Name;
     string source = CodeRush.Language.GenerateElement(ex);
     
     if(elementName == "value")
         source = GetSource(ex.FirstNode as MethodCallExpression).Replace("get(0)","val()");
     if (elementName == "checked")
         source = GetSource(ex.FirstNode as MethodCallExpression).Replace("get(0)", "is(\":checked\")");
     ea.TextDocument.Replace(ex.Range, source, "Convert to jQuery");
     
 }
        private void codeProvider1_Apply(object sender, ApplyContentEventArgs ea)
        {
            var currentFile    = CodeRush.Documents.ActiveFileName;
            var currentProject = CodeRush.Project.Active;

            using (var form = new SolutionBrowser(currentFile))
            {
                if (form.ShowAt(CodeRush.IDE, GetCaretPositionScreenPoint(true)) == DialogResult.OK)
                {
                    MoveFile(currentFile, currentProject, form.SelectedPath, form.SelectedProject);
                }
            }
        }
        public string Apply(ApplyContentEventArgs ea, string selectedProjectName)
        {
            Project project = _projectServices.GetProject(selectedProjectName);

            IEnumerable<NamespaceReference> namespaceReferences = _namespaceServices.BuildNamespaceReferences(ea.Element);
            Namespace namespaceScope = new Namespace(_namespaceServices.GetNamespaceForElement(ea.Element));
            TypeDeclaration typeDeclaration = GetTypeDeclarationForElement(ea.Element);

            if (typeDeclaration != null)
                DeleteTypeDeclaration(typeDeclaration);

            string code = BuildCode(namespaceReferences, namespaceScope, typeDeclaration);
            return WriteCodeToNewFileInProject(project, code, ea.Element.Name);
        }
예제 #35
0
 private void cpConvertToJQuery_Apply(object sender, ApplyContentEventArgs ea)
 {
     if (!IsAvailable(ea.Element))
     {
         return;
     }
     if (ea.Element is MethodCallExpression)
     {
         ReplaceGetElementById(ea);
     }
     else if (ea.Element is ElementReferenceExpression)
     {
         ReplaceGetElementProperty(ea);
     }
 }
예제 #36
0
        /// <summary>
        /// TODO Add summary
        /// </summary>
        private void createPersistentClassCodeProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            SourceFile sourceFile = CodeRush.Source.ActiveSourceFile;

            // Get all types
            var allTypes = sourceFile.AllTypes;

            // Filter to classes
            var allPersistentClasses = allTypes.Cast <TypeDeclaration>()
                                       .Where(td => td.ElementType == LanguageElementType.Class &&
                                              td.Attributes.Cast <DevExpress.CodeRush.StructuralParser.Attribute>()
                                              .Where(a => a.Name == "Persistent").Any());

            // Generate path
            string filePath = Path.Combine(Path.GetDirectoryName(sourceFile.FilePath), "PersistentClassHelper.cs");

            using (StreamWriter sourceFileStream = File.CreateText(filePath))
            {
                string firstClassNamespace = allPersistentClasses.First().GetNamespace().FullName;
                sourceFileStream.WriteLine("namespace " + firstClassNamespace);
                sourceFileStream.WriteLine("{");
                sourceFileStream.WriteLine("\tusing System;");
                sourceFileStream.WriteLine();
                sourceFileStream.WriteLine("\tpublic class PersistentClassHelper");
                sourceFileStream.WriteLine("\t{");
                sourceFileStream.WriteLine("\t\tpublic Type[] GetPersistentTypes()");
                sourceFileStream.WriteLine("\t\t{");
                sourceFileStream.WriteLine("\t\t\tType[] persistentTypes = new Type[]");
                sourceFileStream.WriteLine("\t\t\t{");

                // Generate partial classes
                var lastClass = allPersistentClasses.Last();
                foreach (TypeDeclaration type in allPersistentClasses)
                {
                    sourceFileStream.WriteLine("\t\t\t\ttypeof(" + type.GetNamespace() + "." + type.Name + ")" +
                                               ((lastClass != type) ? "," : String.Empty));
                }
                sourceFileStream.WriteLine("\t\t\t};");
                sourceFileStream.WriteLine();
                sourceFileStream.WriteLine("\t\t\treturn persistentTypes;");
                sourceFileStream.WriteLine("\t\t} // GetPersistentTypes");
                sourceFileStream.WriteLine("\t} // PersistentClassHelper");
                sourceFileStream.WriteLine("} // " + firstClassNamespace);
            }

            // Add generated file to project
            CodeRush.Solution.AddFileToProject(CodeRush.Source.ActiveProject.Name, filePath);
        }
예제 #37
0
        internal void ReplaceGetElementProperty(ApplyContentEventArgs ea)
        {
            ElementReferenceExpression ex = ea.Element as ElementReferenceExpression;
            var    elementName            = ex.Name;
            string source = CodeRush.Language.GenerateElement(ex);

            if (elementName == "value")
            {
                source = GetSource(ex.FirstNode as MethodCallExpression).Replace("get(0)", "val()");
            }
            if (elementName == "checked")
            {
                source = GetSource(ex.FirstNode as MethodCallExpression).Replace("get(0)", "is(\":checked\")");
            }
            ea.TextDocument.Replace(ex.Range, source, "Convert to jQuery");
        }
예제 #38
0
 private void ConvertToMultipleSingleLineComments_Execute(Object sender, ApplyContentEventArgs ea)
 {
     var Comment = ea.CodeActive as Comment;
     var CommentRange = Comment.Range;
     var ActiveDoc = CodeRush.Documents.ActiveTextDocument;
     string[] Lines = Comment.Name.Replace('\r', ' ').Split('\n');
     string NewText = String.Empty;
     for (int i = 0; i < Lines.Length; i++)
     {
         string CommentText = Lines[i].Trim();
         if (CommentText != String.Empty)
             NewText += CodeRush.Language.GetComment(" " + CommentText);
     }
     ActiveDoc.QueueReplace(CommentRange, NewText);
     ActiveDoc.ApplyQueuedEdits("Convert to Singleline comments", true);
 }
		/// <summary>
		/// TODO Add summary
		/// </summary>
		private void createPersistentClassCodeProvider_Apply(object sender, ApplyContentEventArgs ea)
		{
			SourceFile sourceFile = CodeRush.Source.ActiveSourceFile;

			// Get all types
			var allTypes = sourceFile.AllTypes;

			// Filter to classes
			var allPersistentClasses = allTypes.Cast<TypeDeclaration>()
				.Where(td => td.ElementType == LanguageElementType.Class && 
					td.Attributes.Cast<DevExpress.CodeRush.StructuralParser.Attribute>()
						.Where(a => a.Name == "Persistent").Any());

			// Generate path
			string filePath = Path.Combine(Path.GetDirectoryName(sourceFile.FilePath), "PersistentClassHelper.cs");
			using (StreamWriter sourceFileStream = File.CreateText(filePath))
			{
				string firstClassNamespace = allPersistentClasses.First().GetNamespace().FullName;
				sourceFileStream.WriteLine("namespace " + firstClassNamespace);
				sourceFileStream.WriteLine("{");
				sourceFileStream.WriteLine("\tusing System;");
				sourceFileStream.WriteLine();
				sourceFileStream.WriteLine("\tpublic class PersistentClassHelper");
				sourceFileStream.WriteLine("\t{");
				sourceFileStream.WriteLine("\t\tpublic Type[] GetPersistentTypes()");
				sourceFileStream.WriteLine("\t\t{");
				sourceFileStream.WriteLine("\t\t\tType[] persistentTypes = new Type[]");
				sourceFileStream.WriteLine("\t\t\t{");

				// Generate partial classes
				var lastClass = allPersistentClasses.Last();
				foreach (TypeDeclaration type in allPersistentClasses)
				{
					sourceFileStream.WriteLine("\t\t\t\ttypeof(" + type.GetNamespace() + "." + type.Name + ")" +
						((lastClass != type) ? "," : String.Empty));
				}
				sourceFileStream.WriteLine("\t\t\t};");
				sourceFileStream.WriteLine();
				sourceFileStream.WriteLine("\t\t\treturn persistentTypes;");
				sourceFileStream.WriteLine("\t\t} // GetPersistentTypes");
				sourceFileStream.WriteLine("\t} // PersistentClassHelper");
				sourceFileStream.WriteLine("} // " + firstClassNamespace);
			}

			// Add generated file to project
			CodeRush.Solution.AddFileToProject(CodeRush.Source.ActiveProject.Name, filePath);
		}
예제 #40
0
        public string Apply(ApplyContentEventArgs ea, string selectedProjectName)
        {
            Project project = _projectServices.GetProject(selectedProjectName);

            IEnumerable <NamespaceReference> namespaceReferences = _namespaceServices.BuildNamespaceReferences(ea.Element);
            Namespace       namespaceScope  = new Namespace(_namespaceServices.GetNamespaceForElement(ea.Element));
            TypeDeclaration typeDeclaration = GetTypeDeclarationForElement(ea.Element);

            if (typeDeclaration != null)
            {
                DeleteTypeDeclaration(typeDeclaration);
            }

            string code = BuildCode(namespaceReferences, namespaceScope, typeDeclaration);

            return(WriteCodeToNewFileInProject(project, code, ea.Element.Name));
        }
        public void Apply(ApplyContentEventArgs ea, string selectedProjectName)
        {
            Project selectedProject = _projectServices.GetProject(selectedProjectName);

            string filename = _projectServices.GetUniqueFilepathForNewFileInProject(selectedProject, ea.Element.Name);

            //selectedProject.CodeModel.DTE.ItemOperations.AddNewItem(@"Visual C# Items\Code\Class", filename);
           
            var currentProject = DevExpress.CodeRush.Core.SolutionHelper.GetProjectByName(CodeRush.Project.Active.Name);
            var projectToAddAsReference = DevExpress.CodeRush.Core.SolutionHelper.GetProjectByName(selectedProjectName);

            currentProject.CodeModel.DTE.ItemOperations.AddNewItem(@"Visual C# Items\Code\Class", filename);
            
            var vsProj = currentProject.Object as VSLangProj.VSProject;
            if (vsProj != null)
                vsProj.References.AddProject(projectToAddAsReference);

        }
예제 #42
0
        private void NavToSibling(ApplyContentEventArgs ea, SiblingDirection siblingDirection)
        {
            LanguageElement methodOrProperty = CodeRush.Source.ActiveMethodOrProperty;

            if (methodOrProperty == null)
                return;
            LanguageElement sibling = methodOrProperty;
            while (sibling != null)
            {
                if (siblingDirection == SiblingDirection.Next)
                    sibling = sibling.NextCodeSibling;
                else
                    sibling = sibling.PreviousCodeSibling;
                if (sibling is Method || sibling is Property)
                    break;
            }

            if (sibling == null)
            {
                string msg;
                string searchItem;

                if (methodOrProperty is Property)
                    searchItem = "properties";
                else
                    searchItem = "methods";

                if (siblingDirection == SiblingDirection.Next)
                    msg = String.Format("No more {0} below this location.", searchItem);	// Translate: {0} is the item we're searching for (e.g., "properties" or "methods").
                else
                    msg = String.Format("No more {0} above this location.", searchItem);	// Translate: {0} is the item we're searching for (e.g., "properties" or "methods").
                CodeRush.ApplicationObject.StatusBar.Text = msg;
                return;
            }
            if (_Caret == null)
                _Caret = ElementLocation.From(methodOrProperty, CodeRush.Caret.SourcePoint);
            TextView textView = ea.TextView;
            if (textView == null)
                return;
            if (_Anchor == null)
                if (textView.Selection.Exists)
                    _Anchor = ElementLocation.From(methodOrProperty, textView.Selection.AnchorSourcePoint);
            Restore(sibling, textView);
        }
예제 #43
0
        void _refactorFormatXaml_Apply(object sender, ApplyContentEventArgs ea)
        {
            var element             = GetActiveHtmlElement(ea.Element, Options.Sort);
            var keepFirstOnBaseLine = this.Options.KeepFirstAttribute;
            var closeOnOwnLine      = Options.PutCloseTagOnOwnLine;

            if (((element != null) && (element.Attributes != null)) && (element.Attributes.Count != 0))
            {
                HtmlElement newElement = GetNewElement(element);
                string      tabsBefore = GetTabsBefore(element, keepFirstOnBaseLine);
                for (int i = 0; i < element.Attributes.Count; i++)
                {
                    HtmlAttribute attribute = element.Attributes[i];
                    if (keepFirstOnBaseLine && (i == 0))
                    {
                        newElement.AddAttribute(attribute.Name, attribute.Value, attribute.AttributeQuoteType);
                    }
                    else
                    {
                        newElement.AddAttribute(string.Format("\r\n{0}{1}", tabsBefore, attribute.Name), attribute.Value, attribute.AttributeQuoteType);
                    }
                }

                ////if (closeOnOwnLine && !newElement.IsEmptyTag)
                ////{
                ////    string s = CodeRush.Language.GenerateElement(newElement);
                ////    s = CodeRush.StrUtil.RemoveLastLineTerminator(s);
                ////    s += string.Format("\r\n{0}", tabsBefore);

                ////    ////var endLine = newElement.EndLine;
                ////    ////endLine += 1;
                ////    ////var endOffset = newElement.EndOffset;
                ////    ////var sr = new SourceRange(endLine, endOffset);
                ////    ////((XmlElement)newElement).SetBlockEnd(sr);

                ////    newElement = new HtmlElement()
                ////    {

                ////    };
                ////}

                Apply(_refactorFormatXamlAttributes.DisplayName, element, newElement, tabsBefore);
            }
        }
        public void Apply(ApplyContentEventArgs ea, string selectedProjectName)
        {
            Project selectedProject = _projectServices.GetProject(selectedProjectName);

            string filename = _projectServices.GetUniqueFilepathForNewFileInProject(selectedProject, ea.Element.Name);

            //selectedProject.CodeModel.DTE.ItemOperations.AddNewItem(@"Visual C# Items\Code\Class", filename);

            var currentProject          = DevExpress.CodeRush.Core.SolutionHelper.GetProjectByName(CodeRush.Project.Active.Name);
            var projectToAddAsReference = DevExpress.CodeRush.Core.SolutionHelper.GetProjectByName(selectedProjectName);

            currentProject.CodeModel.DTE.ItemOperations.AddNewItem(@"Visual C# Items\Code\Class", filename);

            var vsProj = currentProject.Object as VSLangProj.VSProject;

            if (vsProj != null)
            {
                vsProj.References.AddProject(projectToAddAsReference);
            }
        }
예제 #45
0
        private void ConvertToMultipleSingleLineComments_Execute(Object sender, ApplyContentEventArgs ea)
        {
            var Comment      = ea.CodeActive as Comment;
            var CommentRange = Comment.Range;
            var ActiveDoc    = CodeRush.Documents.ActiveTextDocument;

            string[] Lines   = Comment.Name.Replace('\r', ' ').Split('\n');
            string   NewText = String.Empty;

            for (int i = 0; i < Lines.Length; i++)
            {
                string CommentText = Lines[i].Trim();
                if (CommentText != String.Empty)
                {
                    NewText += CodeRush.Language.GetComment(" " + CommentText);
                }
            }
            ActiveDoc.QueueReplace(CommentRange, NewText);
            ActiveDoc.ApplyQueuedEdits("Convert to Singleline comments", true);
        }
        private void executeRefactoring(ApplyContentEventArgs ea)
        {
            try
            {
                if (actionIsAvailable(ea.Element))
                {
                    FileSourceRangeCollection collection = extractHqlNamedQuery(ea.Element);

                    if (collection != null)
                    {
                        RefactoringContext context = new RefactoringContext(ea);
                        LinkedTextHelper.ApplyRename(context, collection);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
        }
        private void executeRefactoring(ApplyContentEventArgs ea)
        {
            try
            {
                if (actionIsAvailable(ea.Element))
                {
                    FileSourceRangeCollection collection = extractHqlNamedQuery(ea.Element);

                    if (collection != null)
                    {
                        RefactoringContext context = new RefactoringContext(ea);
                        LinkedTextHelper.ApplyRename(context, collection);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowException(ex);
            }
        }
        private void IntroduceLocalAllArguments_Execute(Object sender, ApplyContentEventArgs ea)
        {
            TextDocument ActiveDoc = CodeRush.Documents.ActiveTextDocument;

            using (ActiveDoc.NewCompoundAction("Introduce Local (All Arguments)"))
            {
                LanguageElement           element   = CodeRush.Source.Active;
                MethodReferenceExpression MRE       = element as MethodReferenceExpression;
                LanguageElement           parent    = MRE.Parent;
                ExpressionCollection      arguments = getArguments(parent);

                for (int i = 0; i < arguments.Count; i++)
                {
                    // Select expression
                    CodeRush.Selection.SelectRange(arguments[i].Range);
                    // Invoke refactoring to Introduce Local.
                    ExecuteRefactoring("Introduce Local");
                    ActiveDoc.SetText(GetSelectionRange(), "Param" + (i + 1));
                }
            }
        }
예제 #49
0
        private void ReverseArgs_Apply(Object sender, ApplyContentEventArgs ea)
        {
            using (ea.TextDocument.NewCompoundAction("Reverse Params"))
            {
                // Determine Range
                if (_startElement.PreviousCodeSibling == _endElement)
                {
                    var temp = _endElement;
                    _endElement = _startElement;
                    _startElement = temp;
                }

                var OutputRange = new SourceRange(_startElement.Range.Start, _endElement.Range.End);

                var outString = CodeRush.CodeMod.GenerateCode(_endElement)
                    + ", "
                    + CodeRush.CodeMod.GenerateCode(_startElement);

                ea.TextDocument.SetText(OutputRange, outString);
            }
        }
        private void MoveTypeToFileInSpecificProjectProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            string  selectedSubmenuName = ea.SelectedSubMenuItem.Name;
            Project project             = CodeRush.Solution.AllProjects.Where(p => p.Name == selectedSubmenuName).First();

            IEnumerable <NamespaceReference> namespaceReferences = BuildNamespaceReferences(ea.Element);
            Namespace       namespaceScope  = new Namespace(GetNamespaceForElement(ea.Element));
            TypeDeclaration typeDeclaration = GetTypeDeclarationForElement(ea.Element);

            CodeRush.UndoStack.BeginUpdate("Move Type To File in Project");

            CodeRush.Markers.Drop();

            DeleteTypeDeclaration(typeDeclaration);

            string code     = BuildCode(namespaceReferences, namespaceScope, typeDeclaration);
            var    filename = WriteCodeToNewFileInProject(project, code, ea.Element.Name);

            CodeRush.File.Activate(filename);
            CodeRush.Documents.Format();
        }
예제 #51
0
        private void AddDataContract_Apply(Object sender, ApplyContentEventArgs ea)
        {
            TextDocument ActiveDoc = CodeRush.Documents.ActiveTextDocument;

            using (ActiveDoc.NewCompoundAction("Add DataContract"))
            {
                // Add Namespace Reference
                AddNamespaceReference("System.Runtime.Serialization");
                CodeRush.Project.AddReference(ActiveDoc.ProjectElement, "System.Runtime.Serialization");

                // Add DataContract Attribute
                AddAttribute(CodeRush.Source.ActiveClass, "DataContract");
                foreach (Property prop in CodeRush.Source.ActiveClass.AllProperties)
                {
                    // Add DataMember Attribute
                    AddAttribute(prop, "DataMember");
                }
                CodeRush.Documents.ActiveTextDocument.ApplyQueuedEdits();
                CodeRush.Documents.ActiveTextDocument.ParseIfNeeded();
                CodeRush.Actions.Get("FormatFile").DoExecute();
            }
        }
예제 #52
0
        private void AddDataContract_Apply(Object sender, ApplyContentEventArgs ea)
        {
            TextDocument ActiveDoc = CodeRush.Documents.ActiveTextDocument;

            using (ActiveDoc.NewCompoundAction("Add DataContract"))
            {
                // Add Namespace Reference
                AddNamespaceReference("System.Runtime.Serialization");
                CodeRush.Project.AddReference(ActiveDoc.ProjectElement, "System.Runtime.Serialization");

                // Add DataContract Attribute
                AddAttribute(CodeRush.Source.ActiveClass, "DataContract");
                foreach (Property prop in CodeRush.Source.ActiveClass.AllProperties)
                {
                    // Add DataMember Attribute
                    AddAttribute(prop, "DataMember");
                }
                CodeRush.Documents.ActiveTextDocument.ApplyQueuedEdits();
                CodeRush.Documents.ActiveTextDocument.ParseIfNeeded();
                CodeRush.Actions.Get("FormatFile").DoExecute();
            }
        }
        }     // refactoringProvider_CheckAvailability(sender, ea)

        /// <summary>
        /// Refactoring provider apply
        /// </summary>
        private void refactoringProvider_Apply(object sender, ApplyContentEventArgs ea)
        {
            if (_Property != null && ea.SelectedSubMenuItem != null)
            {
                ElementBuilder elementBuilder = ea.NewElementBuilder();
                string         newCode;
                switch (ea.SelectedSubMenuItem.Name)
                {
                case MenuItem_ConvertTo_XPOProperty:
                    newCode = GetNewPropertyDeclaration(elementBuilder, _Property);
                    ea.TextDocument.Replace(_Property.Range, newCode, "Converting into XPO property", true);
                    break;

                case MenuItem_ConvertTo_DelayedProperty:
                    newCode = GetNewDelayedPropertyDeclaration(elementBuilder, _Property);
                    ea.TextDocument.Replace(_Property.Range, newCode, "Converting into delayed property", true);
                    // How detect and remove property variable?
                    //if (_IsXpoProperty && _Property.HasGetter)
                    //    ea.TextDocument.Replace(_Property.Getter.LastChild.FirstDetail.Range, string.Empty, "Converting into delayed property - field var removed", true);
                    break;
                } // switch
            }     // if
        }         // refactoringProvider_Apply(sender, ea)
        private void cdeCreateConstructorCall_Apply(object sender, ApplyContentEventArgs ea)
        {
            FileChange newFileChange = new FileChange();
            newFileChange.Path = CodeRush.Documents.ActiveTextDocument.FileNode.Name;
            newFileChange.Range = _DeleteRange;
            newFileChange.Text = _NewCall;
            CodeRush.Markers.Drop(_DeleteRange.Start, MarkerStyle.Transient);
            if (_Changes == null)
                _Changes = new FileChangeCollection();
            else
                _Changes.Clear();

            _Changes.Add(newFileChange);

            TextDocument textDocument = CodeRush.Documents.Get(_TypeElement.FirstFile.Name) as TextDocument;
            if (textDocument == null)
            {
                _WaitingForViewActivate = true;
                CodeRush.File.Activate(_TypeElement.FirstFile.Name);
                return;
            }

            StartTargetPicker(textDocument);
        }
 private void ReplaceGetElementById(ApplyContentEventArgs ea)
 {
     MethodCallExpression ex = ea.Element as MethodCallExpression;
     string source = GetSource(ex);
     ea.TextDocument.Replace(ex.Range, source, "Convert to jQuery", true);
 }
        private void ConvertStringToAppSetting_Execute(Object sender, ApplyContentEventArgs ea)
        {
            TextDocument CodeDoc = CodeRush.Documents.ActiveTextDocument;
            using (CodeDoc.NewCompoundAction("Extract to App.config setting"))
            {
                ProjectElement ActiveProject = CodeRush.Source.ActiveProject;
                PrimitiveExpression StringLiteral = ea.Element as PrimitiveExpression;

                // Ensure App.config
                string BasePath = System.IO.Path.GetDirectoryName(ActiveProject.FilePath);
                string Filename = BasePath + "\\App.Config";
                TextDocument configDoc = CodeRush.Documents.GetTextDocument(Filename);

                if (configDoc == null)
                {
                    // Open configDoc
                    configDoc = (TextDocument)CodeRush.File.Activate(Filename);
                }

                if (configDoc == null)
                {
                    // Create configDoc
                    string DefaultSettings = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><configuration></configuration>";
                    CodeRush.File.WriteTextFile(Filename, DefaultSettings);
                    CodeRush.Project.AddFile(ActiveProject, Filename);
                    configDoc = (TextDocument)CodeRush.File.Activate(Filename);
                }

                //Ensure RootNode
                SP.HtmlElement RootNode = (SP.HtmlElement)configDoc.FileNode.Nodes[1];

                // Get appSettings node
                SP.HtmlElement AppSettings = GetAppSettings(RootNode);
                if (AppSettings == null)
                {
                    AppSettings = CreateHTMLNode("appSettings");
                    RootNode.AddNode(AppSettings);
                    RewriteNodeInDoc(RootNode, configDoc);
                    RootNode = (SP.HtmlElement)configDoc.FileNode.Nodes[1];
                    AppSettings = GetAppSettings(RootNode);
                }

                // Generate a new setting... Add it to correct location in App.config.
                string SettingValue = (string)StringLiteral.PrimitiveValue;
                string SettingName = SettingValue.Replace(" ", "");
                SP.HtmlElement SettingNode = CreateSettingNode(SettingName, SettingValue);
                AppSettings.AddNode(SettingNode);
                RewriteNodeInDoc(AppSettings, configDoc);

                // Add reference to System.Configuration dll.
                CodeRush.Project.AddReference(ActiveProject, "System.Configuration.dll");

                // Replace Literal with reference to setting through Configuration manager
                string Code = String.Format("System.Configuration.ConfigurationManager.AppSettings[\"{0}\"]", SettingName);
                var NewCodeRange = CodeDoc.SetText(StringLiteral.Range, Code);
                CodeDoc.ParseIfTextChanged();
                CodeDoc.ParseIfNeeded();
                var SourceNode = CodeDoc.GetNodeAt(NewCodeRange.Start);

                // Find Newly created Setting
                configDoc.ParseIfTextChanged();
                configDoc.ParseIfNeeded();
                RootNode = (SP.HtmlElement)configDoc.FileNode.Nodes[1];
                AppSettings = GetAppSettings(RootNode);
                SettingNode = GetSettingWithKeyAndValue(AppSettings, SettingName, SettingValue);

                // Link Code and Setting.
                var LinkSet = CodeRush.LinkedIdentifiers.NewMultiDocumentContainer();
                SourceRange StringRange = (SourceNode.Parent.Parent.Parent.Parent.DetailNodes[0] as LanguageElement).Range;
                SourceRange CodeSourceRange = new SourceRange(StringRange.Start.OffsetPoint(0, 1), StringRange.End.OffsetPoint(0, -1));
                LinkSet.Add(new FileSourceRange(CodeDoc.FileNode, CodeSourceRange));
                LinkSet.Add(new FileSourceRange(configDoc.FileNode, SettingNode.Attributes["key"].ValueRange));
                CodeRush.LinkedIdentifiers.Invalidate(configDoc);
                CodeDoc.Activate();
                CodeRush.LinkedIdentifiers.Invalidate(CodeDoc);
                CodeRush.Selection.SelectRange(CodeSourceRange);
                configDoc.ParseIfTextChanged();
                configDoc.ParseIfNeeded();

            }
        }
 private void refactoringUpdateNamespace_Apply(object sender, ApplyContentEventArgs ea)
 {
     ea.TextDocument.Replace(ea.Element.NameRange, ExpectedNamespace(ea.TextDocument.ProjectElement, ea.TextDocument.Path, ea.Element), "Update To Default Namespace", true);
 }
예제 #58
0
		private void cpAssignmentExpressionToEqualityCheck_Apply(object sender, ApplyContentEventArgs ea)
		{
			AssignmentExpression assignmentExpression = GetAssignmentExpression(ea.Element);
			if (assignmentExpression == null)
				return;
			ea.TextDocument.Replace(assignmentExpression.Range, 
															GetNewEqualityTestCode(assignmentExpression), 
															"Convert assignment to equality check.", 
															true);
		}
예제 #59
0
 private void cpAddReference_Apply(object sender, ApplyContentEventArgs ea)
 {
   CodeRush.Source.DeclareNamespaceReference(_NamespaceOfExtensionMethod);
 }