public void Execute(ISolution solution, ITextControl textControl)
    {
      if (!_literalExpression.IsValid())
        return;

      IFile containingFile = _literalExpression.GetContainingFile();

      CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(_literalExpression.GetPsiModule());

      IExpression newExpression = null;
      _literalExpression.GetPsiServices().PsiManager.DoTransaction(
        () =>
          {
            using (solution.GetComponent<IShellLocks>().UsingWriteLock())
              newExpression = ModificationUtil.ReplaceChild(
                _literalExpression, elementFactory.CreateExpression("System.Int16.MaxValue"));
          }, GetType().Name);

      if (newExpression != null)
      {
        IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent<DocumentManager>());
        containingFile.OptimizeImportsAndRefs(
          marker, false, true, NullProgressIndicator.Instance);
      }
    }
 protected static void SetCaretPosition(ITextControl textControl, PsiIntentionResult result)
 {
   if (result.PrefferedSelection != DocumentRange.InvalidRange)
   {
     textControl.Selection.SetRange(result.PrefferedSelection.TextRange);
   }
 }
Exemplo n.º 3
0
 /// <summary>
 /// Renders the footer tag and appropriate html to the given text control
 /// </summary>
 /// <param name="page">Page to get the content from that is supposed to be rendered</param>
 /// <param name="footerControl">The control to render the html to</param>
 public static void RenderFooterHtmlToControl(Page page, ITextControl footerControl)
 {
     if (!string.IsNullOrEmpty(page.FooterHtml))
     {
         footerControl.Text = "<footer>" + HttpUtility.HtmlEncode(page.FooterHtml) + "</footer>";
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Renders the CanonicalUrl to the passed in text control
 /// </summary>
 /// <param name="page">The page object to get the canonicalUrl from</param>
 /// <param name="canonicalLinkControl">The control to render the html to</param>
 public static void RenderCanonicalUrlToControl(Page page, ITextControl canonicalLinkControl)
 {
     if (!string.IsNullOrEmpty(page.CanonicalUrl))
     {
         canonicalLinkControl.Text = "<link rel=\"canonical\" href=\"" + HttpUtility.HtmlEncode(page.CanonicalUrl) + "\"/>";
     }
 }
        /// <summary>
        /// The execute inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpModifiersOwnerDeclaration declaration = Utils.GetTypeClosestToTextControl<ICSharpModifiersOwnerDeclaration>(solution, textControl);

            if (declaration != null)
            {
                string rulesNamespace = this.Rule.Namespace;

                string ruleText = string.Format("{0}:{1}", this.Rule.CheckId, this.Rule.Name);

                IContextBoundSettingsStore settingsStore = PsiSourceFileExtensions.GetSettingsStore(null, solution);

                string justificationText = settingsStore.GetValue((StyleCopOptionsSettingsKey key) => key.SuppressStyleCopAttributeJustificationText);

                IAttributesOwnerDeclaration attributesOwnerDeclaration = declaration as IAttributesOwnerDeclaration;

                CSharpElementFactory factory = CSharpElementFactory.GetInstance(declaration.GetPsiModule());

                ITypeElement typeElement = Utils.GetTypeElement(declaration, "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute");

                IAttribute attribute = factory.CreateAttribute(typeElement);

                ICSharpArgument newArg1 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), rulesNamespace), null);

                ICSharpArgument newArg2 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), ruleText), newArg1);

                attribute.AddArgumentAfter(Utils.CreateArgumentValueExpression(declaration.GetPsiModule(), "Justification = \"" + justificationText + "\""), newArg2);

                attributesOwnerDeclaration.AddAttributeAfter(attribute, null);
            }
        }
Exemplo n.º 6
0
 /// <summary>
 /// Renders the header tag and appropriate html to the given text control
 /// </summary>
 /// <param name="page">Page to get the content from that is suppose to be rendered</param>
 /// <param name="headerControl">The control to render the html to</param>
 public static void RenderHtmlHeaderToControl(Page page, ITextControl headerControl)
 {
     if (!string.IsNullOrEmpty(page.HeaderHtml))
     {
         headerControl.Text = "<header>" + HttpUtility.HtmlEncode(page.HeaderHtml) + "</header>";
     }
 }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            IRangeMarker marker = this.DocumentRange.CreateRangeMarker();
            file.ArrangeThisQualifier(marker);
        }
Exemplo n.º 8
0
        public void Execute(ISolution solution, ITextControl textControl)
        {
            // TODO extract add attribute to another class
            // method name  IDeclaredParameter AddDeclaredParameter()

            if (missedParameterError.Descriptor.IsAttribute)
            {
                IDocument document = textControl.Document;
                using (ModificationCookie cookie = document.EnsureWritable())
                {
                    int navigationOffset = -1;

                    try
                    {
                        CommandProcessor.Instance.BeginCommand("TextControl:AddAttribute");
                        string toInsert = " " + this.missedParameterError.Descriptor.Name + "=\"\"";
                        document.InsertText(this.headerNameRange.TextRange.EndOffset, toInsert);
                        navigationOffset = (this.headerNameRange.TextRange.EndOffset + toInsert.Length) - 1;
                    }
                    finally
                    {
                        CommandProcessor.Instance.EndCommand();
                    }
                    if (navigationOffset != -1)
                    {
                        textControl.CaretModel.MoveTo(navigationOffset, TextControlScrollType.MAKE_VISIBLE);
                        // todo run Completion Action
                    }
                }
            }
            else
            {
                Assert.Fail();
            }
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            // Fixes SA1639
            DocumentationRules.InsertFileHeaderSummary(file);
        }
        /// <inheritdoc />
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            IDeclaration declaration = Utils.GetTypeClosestToTextControl<IDeclaration>(solution, textControl);

            // Fixes SA1604, 1605
            new DocumentationRules().InsertMissingSummaryElement(declaration);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            IElement element = Utils.GetElementAtCaret(solution, textControl);

            if (element == null)
            {
                return;
            }

            IUsingListNode usingList = element.GetContainingElement(typeof(IUsingListNode), false) as IUsingListNode;

            if (usingList == null)
            {
                return;
            }

            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            // This violation will only run if there are some using statements and definately at least 1 namespace
            // so [0] index will always be OK.
            ICSharpNamespaceDeclaration firstNamespace = file.NamespaceDeclarations[0];

            foreach (IUsingDirectiveNode usingDirectiveNode in usingList.Imports)
            {
                firstNamespace.AddImportBefore(usingDirectiveNode, null);

                file.RemoveImport(usingDirectiveNode);
            }
        }
 /// <summary>
 /// The execute transaction inner.
 /// </summary>
 /// <param name="solution">
 /// The solution.
 /// </param>
 /// <param name="textControl">
 /// The text control.
 /// </param>
 public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
 {
     string documentation = this.DocumentRange.GetText();
     Regex regEx = new Regex("(((///[ ^ ] *)))|((///))");
     documentation = regEx.Replace(documentation, "/// ");
     textControl.Document.ReplaceText(this.DocumentRange.TextRange, documentation);
 }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);
            IBlock containingBlock = element.GetContainingNode<IBlock>(true);

            if (containingBlock != null)
            {
                //// CSharpFormatterHelper.FormatterInstance.Format(containingBlock);
                ICSharpCodeFormatter codeFormatter = (ICSharpCodeFormatter)CSharpLanguage.Instance.LanguageService().CodeFormatter;
                codeFormatter.Format(containingBlock);

                new LayoutRules().CurlyBracketsForMultiLineStatementsMustNotShareLine(containingBlock);
            }
            else
            {
                IFieldDeclaration fieldDeclarationNode = element.GetContainingNode<IFieldDeclaration>(true);
                if (fieldDeclarationNode != null)
                {
                    //// CSharpFormatterHelper.FormatterInstance.Format(fieldDeclarationNode);
                    ICSharpCodeFormatter codeFormatter = (ICSharpCodeFormatter)CSharpLanguage.Instance.LanguageService().CodeFormatter;
                    codeFormatter.Format(fieldDeclarationNode);

                    new LayoutRules().CurlyBracketsForMultiLineStatementsMustNotShareLine(fieldDeclarationNode);
                }
            }
        }
            protected override void AcceptExpression(
        ITextControl textControl, ISolution solution, TextRange resultRange, ICSharpExpression expression)
            {
                // set selection for introduce field
                textControl.Selection.SetRanges(new[] {TextControlPosRange.FromDocRange(textControl, resultRange)});

                const string name = "IntroFieldAction";
                var rules = DataRules
                  .AddRule(name, ProjectModel.DataContext.DataConstants.SOLUTION, solution)
                  .AddRule(name, DataConstants.DOCUMENT, textControl.Document)
                  .AddRule(name, TextControl.DataContext.DataConstants.TEXT_CONTROL, textControl)
                  .AddRule(name, Psi.Services.DataConstants.SELECTED_EXPRESSION, expression);

                Lifetimes.Using(lifetime =>
                  WorkflowExecuter.ExecuteBatch(
                Shell.Instance.GetComponent<DataContexts>().CreateWithDataRules(lifetime, rules),
                new IntroFieldWorkflow(solution, null)));

                // todo: rename hotspots

                var ranges = textControl.Selection.Ranges.Value;
                if (ranges.Count == 1) // reset selection
                {
                  var endPos = ranges[0].End;
                  textControl.Selection.SetRanges(new[] {new TextControlPosRange(endPos, endPos)});
                }
            }
        public void Execute(ISolution solution, ITextControl textControl)
        {
            if (!MethodDeclaration.IsValid())
            {
                return;
            }

            var containingFile = MethodDeclaration.GetContainingFile();
            var psiModule = MethodDeclaration.GetPsiModule();
            var elementFactory = CSharpElementFactory.GetInstance(psiModule);
            var declared = MethodDeclaration.DeclaredElement;
            if (declared != null)
            {
                var newName = declared.ShortName + "Async";

                var refactoringService = solution.GetComponent<RenameRefactoringService>();
                var suggests = new List<string> {newName};
                SearchDomainFactory searchDomainFactory = solution.GetComponent<SearchDomainFactory>();
                var workflow = (IRefactoringWorkflow)new MethodRenameWorkflow(suggests, solution.GetComponent<IShellLocks>(), searchDomainFactory, refactoringService, solution, "TypoRename");

                var renames = RenameRefactoringService.Instance.CreateAtomicRenames(declared, newName, true).ToList();
               // var workflow = RenameFromContexts.InitFromNameChanges(solution, renames);
                //                workflow.CreateRefactoring();
                Lifetimes.Using(lifetime => RefactoringActionUtil.ExecuteRefactoring(solution.GetComponent<IActionManager>().DataContexts.CreateOnSelection(lifetime, DataRules.AddRule("DoTypoRenameWorkflow", DataConstants.SOLUTION, solution)), workflow));
            }
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            IMethodDeclaration memberDeclaration = element.GetContainingNode<IMethodDeclaration>(true);

            new DocumentationRules().RemoveReturnsElement(memberDeclaration);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            IDeclaration declaration = element.GetContainingNode<IDeclaration>(true);

            new DocumentationRules().EnsureDocumentationHasNoBlankLines(declaration);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            IRangeMarker marker = PsiManager.GetInstance(solution).CreatePsiRangeMarker(this.DocumentRange);

            file.ArrangeThisQualifier(marker);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            ITreeNode currentNode = element;

            Utils.RemoveNewLineBefore(currentNode);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            IDeclaration declaration = element.GetContainingNode<IDeclaration>(true);

            new DocumentationRules().InsertMissingTypeParamElement(declaration);
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            IElement element = Utils.GetElementAtCaret(solution, textControl);

            ITreeNode currentNode = (ITreeNode)element;

            currentNode.InsertNewLineAfter();
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            ITreeNode currentNode = element;

            currentNode.FindFormattingRangeToLeft().InsertNewLineAfter();
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            IElement element = Utils.GetElementAtCaret(solution, textControl);

            IPropertyDeclaration propertyDeclaration = element.GetContainingElement<IPropertyDeclaration>(true);

            new DocumentationRules().InsertValueElement(propertyDeclaration);
        }
Exemplo n.º 24
0
        public void Type(ITextControl textControl, char c, NextHandler nextHandler)
        {
            // если не вызвать nextHandler то в редакторе не появляется новый символ
            nextHandler();

            if (!IsSupported(textControl))
                return;

            if (LookupWindowManager.Instance.CurrentLookup == null && c == '<'
                /*&& CodeCompletionSettings.Instance.AutoPopupOnIdentifier.GetValue()*/)
            {
                Action action = null;
                action = delegate
                                    {
                                        CommandProcessor.Instance.BeforeCommandFinished -= action;

                                        // it is really simple
                                        // just execute basic completion
                                        // TODO see SessionStarter and  CodeCompletionSession.ExecuteAsync
                                        // as example for raise completion (smart or basic depend from context)
                                        // and using resharper options (enable completion, pause etc )

                                        bool interrupted = false;

                                        PsiManager.GetInstance(solution).AsyncCommitAllDocuments(
                                                delegate
                                                    {
                                                        return interrupted;
                                                    },
                                                delegate
                                                    {
                                                        if (interrupted)
                                                            return;

                                                        LookupWindowManager.Instance.AfterLookupWindowShown += Instance_OnAfterLookupWindowShown;

                                                        try
                                                        {
                                                            IUpdatableAction updatableAction =
                                                                ActionManager.Instance.GetAction("CompleteCodeBasic");
                                                            ActionManager.Instance.ExecuteActionIfAvailable((IExecutableAction)updatableAction);
                                                        }
                                                        finally
                                                        {
                                                            LookupWindowManager.Instance.AfterLookupWindowShown -= Instance_OnAfterLookupWindowShown;
                                                        }

                                                    },
                                                delegate
                                                    {
                                                        interrupted = true;
                                                    }
                                            );

                                    };
                CommandProcessor.Instance.BeforeCommandFinished += action;
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Render the MetaKeywords and MetaDescription to the specified text control
 /// </summary>
 /// <param name="page">The page object to get the keywords and description from</param>
 /// <param name="metaControl">The control to render the html to</param>
 public static void RenderMetaSectionToControl(Page page, ITextControl metaControl)
 {
     if (string.IsNullOrEmpty(page.MetaKeys))
         page.MetaKeys = page.Title;
     if (string.IsNullOrEmpty(page.MetaDesc))
         page.MetaDesc = page.Title;
     metaControl.Text = "<meta name=\"keywords\" content=\"" + page.MetaKeys + "\"/><meta name=\"description\" content=\"" +
                    page.MetaDesc + "\"/>";
 }
 protected override CodeCleanupProfile GetProfile(
     CodeCleanupSettingsComponent codeCleanupSettings,
     ITextControl textControl)
 {
     var profile = new CodeCleanupProfile(
         false,
         "<Profile name=\"Usings order and spacing\"><FixUsingsOrderAndSpacing>True</FixUsingsOrderAndSpacing></Profile>");
     return profile;
 }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            ITreeNode containingElement = element.GetContainingNode<IFieldDeclaration>(true)
                                          ?? element.GetContainingNode<IMultipleDeclaration>(true) ?? element.PrevSibling;

            ModifiersUtil.SetAccessRights(containingElement, AccessRights.PRIVATE);
        }
 /// <summary>
 /// The execute transaction inner.
 /// </summary>
 /// <param name="solution">
 /// The solution.
 /// </param>
 /// <param name="textControl">
 /// The text control.
 /// </param>
 public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
 {
     ITreeNode element = Utils.GetElementAtCaret(solution, textControl);
     IStartRegion startRegionNode = element.GetContainingNode<IStartRegion>(true);
     if (startRegionNode != null)
     {
         ReadabilityRules.MoveRegionInsideNextOpenCurlyBracket(startRegionNode);
     }
 }
        public bool AcceptTyping(char c, ITextControl textControl, IContextBoundSettingsStore boundSettingsStore)
        {
            if (c == ':') return true;

            if (EmojiCompletionContextProvider.IsEmojiChar(c))
                return this.MatchText(textControl, 1, text => text[0] == ':');

            return false;
        }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);
            IInvocationExpression invocationExpression = element.GetContainingNode<IInvocationExpression>(true);

            if (invocationExpression != null)
            {
                ReadabilityRules.SwapBaseToThisUnlessLocalImplementation(invocationExpression);
            }
        }
Exemplo n.º 31
0
 public void OnHotspotSessionExecutionStarted(NTriplesIntentionResult result, ITextControl textControl)
 {
     this.OnHotspotSessionExecutionStartedInternal(result, textControl);
 }
Exemplo n.º 32
0
 static bool IsTextBoxEmpty(ITextControl textbox)
 {
     return(textbox.Text.Length == 0);
 }
Exemplo n.º 33
0
        protected virtual void OnHotspotSessionExecutionStartedInternal(NTriplesIntentionResult result, ITextControl textControl)
        {
            var hotspotSessionUi = this.HotspotSessionExecutor.CurrentSession;

            if (hotspotSessionUi == null)
            {
                SetCaretPosition(textControl, result);
            }
            else
            {
                hotspotSessionUi.HotspotSession.Closed.Advise(
                    EternalLifetime.Instance,
                    args =>
                {
                    if (args.TerminationType != TerminationType.Finished)
                    {
                        return;
                    }

                    SetCaretPosition(textControl, result);
                });
            }
        }
Exemplo n.º 34
0
 public AutopopupType IsEnabledInSettings(IContextBoundSettingsStore settingsStore, ITextControl textControl)
 {
     return((AutopopupType)settingsStore.GetValue(mySettingsScalarEntry, null));
 }
Exemplo n.º 35
0
        public override void Accept(ITextControl textControl, TextRange nameRange, LookupItemInsertType lookupItemInsertType, Suffix suffix,
                                    ISolution solution, bool keepCaretStill)
        {
            var rangeMarker = nameRange.CreateRangeMarkerWithMappingToDocument(textControl.Document);

            var identifierNode = TextControlToPsi.GetElement <ITreeNode>(solution, textControl);
            var psiServices    = solution.GetPsiServices();

            if (identifierNode != null)
            {
                IErrorElement errorElement;

                ITreeNode usage = identifierNode.GetContainingNode <IUserTypeUsage>();
                if (usage != null)
                {
                    errorElement = usage.NextSibling as IErrorElement;
                }
                else
                {
                    usage = identifierNode.PrevSibling;
                    while (usage != null && !(usage is ITypeUsage))
                    {
                        usage = usage.PrevSibling;
                    }
                    errorElement = identifierNode.NextSibling as IErrorElement;
                }

                using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveIdentifier"))
                    using (new DisableCodeFormatter())
                    {
                        using (WriteLockCookie.Create())
                        {
                            ModificationUtil.DeleteChild(identifierNode);
                            if (usage != null)
                            {
                                ModificationUtil.DeleteChild(usage);
                            }
                            if (errorElement != null)
                            {
                                ModificationUtil.DeleteChild(errorElement);
                            }
                        }

                        cookie.Commit();
                    }
            }

            using (WriteLockCookie.Create())
            {
                textControl.Document.InsertText(rangeMarker.Range.StartOffset, "void Foo(){}");
            }

            psiServices.Files.CommitAllDocuments();

            var methodDeclaration = TextControlToPsi.GetElement <IMethodDeclaration>(solution, textControl);

            if (methodDeclaration == null)
            {
                return;
            }

            var insertionIndex = methodDeclaration.GetTreeStartOffset().Offset;

            string attributeText = null;

            var attributeList = methodDeclaration.FirstChild as IAttributeSectionList;

            if (attributeList != null)
            {
                attributeText = attributeList.GetText();
                var treeNode = attributeList.NextSibling;
                while (treeNode is IWhitespaceNode)
                {
                    attributeText += treeNode.GetText();
                    treeNode       = treeNode.NextSibling;
                }
            }

            using (var cookie = new PsiTransactionCookie(psiServices, DefaultAction.Rollback, "RemoveInsertedDeclaration"))
                using (new DisableCodeFormatter())
                {
                    using (WriteLockCookie.Create())
                        ModificationUtil.DeleteChild(methodDeclaration);

                    cookie.Commit();
                }

            // Get the UnityEventFunction generator to actually insert the methods
            GenerateCodeWorkflowBase.ExecuteNonInteractive(
                GeneratorUnityKinds.UnityEventFunctions, solution, textControl, methodDeclaration.Language,
                configureContext: context =>
            {
                var inputElements = from e in context.ProvidedElements.Cast <GeneratorDeclaredElement <IMethod> >()
                                    where myEventFunction.Match(e.DeclaredElement) != EventFunctionMatch.NoMatch
                                    select e;

                context.InputElements.Clear();
                context.InputElements.AddRange(inputElements);
            });

            if (!string.IsNullOrEmpty(attributeText))
            {
                using (WriteLockCookie.Create())
                    textControl.Document.InsertText(insertionIndex, attributeText);
            }
        }
 public TextRange GetVisualReplaceRange(ITextControl textControl, TextRange nameRange)
 {
     return(myRealItem.GetVisualReplaceRange(textControl, nameRange));
 }
Exemplo n.º 37
0
        protected override IEnumerable <BulbMenuItem> GetActions(IMethodDeclaration methodDeclaration, ITextControl textControl)
        {
            var actions = ShowPerformanceCriticalCallsBulbAction.GetPerformanceCallsActions(methodDeclaration);

            return(actions.ToMenuItems(textControl, Solution));
        }
Exemplo n.º 38
0
 public bool AcceptsFile(IFile file, ITextControl textControl)
 {
     return(this.MatchTokenType(file, textControl, token => token.IsIdentifier || token.IsKeyword));
 }
Exemplo n.º 39
0
 protected virtual void AdditionalWorkflowTestChecks(IRefactoringWorkflow workflow, ITextControl textControl,
                                                     IDataContext context)
 {
 }
Exemplo n.º 40
0
 public virtual IEnumerable <BulbMenuItem> CreateAdditionalMenuItem(IDeclaration declaration, UnityApi api, ITextControl textControl)
 {
     return(EmptyList <BulbMenuItem> .Enumerable);
 }
Exemplo n.º 41
0
 protected override IRefactoringWorkflow CreateRefactoringWorkflow(ITextControl textControl,
                                                                   IDataContext context)
 {
     return(myDrivenTextBase.CreateRefactoringWorkflow(textControl, context));
 }
Exemplo n.º 42
0
 /// <summary>Gets whether a given text control is supported by the assistant.</summary>
 /// <param name="textControl">The text control to check.</param>
 /// <returns><c>true</c> if <paramref name="textControl"/> is a T4 file with C# code behind, <c>false</c> otherwise.</returns>
 protected override bool IsSupported(ITextControl textControl)
 => WebTypingAssistUtil.IsProjectFileSupported <T4ProjectFileType, CSharpLanguage>(textControl, Solution);
Exemplo n.º 43
0
 /// <summary>Returns the offset difference between a text control and a lexer.</summary>
 /// <param name="textControl">The text control.</param>
 /// <param name="offset">The original offset.</param>
 /// <returns>Always <paramref name="offset"/>.</returns>
 public override int TextControlToLexer(ITextControl textControl, int offset)
 => offset;
Exemplo n.º 44
0
 /// <summary>Returns the offset difference between a lexer and a text control.</summary>
 /// <param name="textControl">The text control.</param>
 /// <param name="offset">The original offset.</param>
 /// <returns>Always <paramref name="offset"/>.</returns>
 public override int LexerToTextControl(ITextControl textControl, int offset)
 => offset;
Exemplo n.º 45
0
 protected override void AdditionalTestChecks(ITextControl textControl, IProject testProject)
 {
     myDrivenTextBase.AdditionalTestChecks(textControl, testProject);
 }
Exemplo n.º 46
0
 public bool ProcessSubsequentTyping(char c, ITextControl textControl)
 {
     return(IsIdentStart(c) || char.IsDigit(c) || c == '_');
 }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpFile file = Utils.GetCSharpFile(solution, textControl);

            new DocumentationRules().InsertCopyrightText(file);
        }
Exemplo n.º 48
0
 public override bool QuickCheckAvailability(ITextControl textControl, IPsiSourceFile projectFile)
 => projectFile.LanguageType.Is <T4ProjectFileType>();
Exemplo n.º 49
0
 public override CachingLexer GetCachingLexer(ITextControl textControl)
 {
     return(myShaderLabDummyFormatter.ComposeKeywordResolvingLexer(textControl));
 }
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ITreeNode element = Utils.GetElementAtCaret(solution, textControl);

            Utils.RemoveNewLineBefore(element);
        }
Exemplo n.º 51
0
 public bool QuickCheckAvailability(ITextControl textControl, IPsiSourceFile projectFile)
 {
     return(projectFile.LanguageType.Is <ShaderLabProjectFileType>());
 }
Exemplo n.º 52
0
 public static int GetOffset(this ITextControl textControl) =>
 textControl.Selection.OneDocRangeWithCaret().GetMinOffset();
Exemplo n.º 53
0
 protected override void DoAdditionalTyping(ITextControl textControl, TestOptionsIterator.TestData data)
 {
     textControl.EmulateTyping('%');
     textControl.EmulateTyping('%');
 }
Exemplo n.º 54
0
        private IEnumerable <IClrDeclaredElement> FindReferencesWithinAssociatedAssembly(IDataContext context,
                                                                                         ISolution solution, ITextControl textControl, IClrTypeName clrTypeClassName,
                                                                                         IEnumerable <TestCopProjectItem> targetProjects)
        {
            if (clrTypeClassName == null)
            {
                ResharperHelper.AppendLineToOutputWindow(solution.Locks,
                                                         "FindReferencesWithinAssociatedAssembly() - clrTypeClassName was null");
                return(new List <IClrDeclaredElement>());
            }

            IPsiServices services = solution.GetPsiServices();

            ISearchDomain searchDomain;

            if (this.Settings.FindAnyUsageInTestAssembly)
            {
                searchDomain = PsiShared.GetComponent <SearchDomainFactory>().CreateSearchDomain(
                    targetProjects.SelectMany(proj => proj.Project.GetAllProjectFiles().Select(p => p.GetPsiModule())));
            }
            else
            {
                // look for similar named files that also have references to this code
                List <ProjectFileFinder.Match> items = new List <ProjectFileFinder.Match>();

                foreach (TestCopProjectItem projectItem in targetProjects)
                {
                    projectItem.Project.Accept(new ProjectFileFinder(items, projectItem.FilePattern));
                }

                searchDomain = PsiShared.GetComponent <SearchDomainFactory>()
                               .CreateSearchDomain(items.Select(p => p.ProjectFile.ToSourceFile()));
            }

            ISymbolScope declarationsCache = solution.GetPsiServices().Symbols
                                             .GetSymbolScope(LibrarySymbolScope.NONE, false); //, currentProject.GetResolveContext());

            ITypeElement declaredElement = declarationsCache.GetTypeElementByCLRName(clrTypeClassName);

            IReference[] findReferences =
                services.Finder.FindReferences(declaredElement, searchDomain, new ProgressIndicator(textControl.Lifetime));

            List <IClassDeclaration> findReferencesWithinAssociatedAssembly =
                findReferences.Select(p => p.GetTreeNode().GetContainingNode <IClassDeclaration>(true)).ToList();

            return(findReferencesWithinAssociatedAssembly
                   .Select(p => p.DeclaredElement).ToList()
                   .Select(p => p as IClrDeclaredElement).ToList());
        }
Exemplo n.º 55
0
 protected virtual IPsiSourceFile GetPsiSourceFile(ITextControl textControl)
 {
     return(textControl.Document.GetPsiSourceFile(Solution));
 }
Exemplo n.º 56
0
        /// <summary>
        /// The execute transaction inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            IDeclaration declaration = Utils.GetTypeClosestToTextControl <IDeclaration>(solution, textControl);

            new DocumentationRules().EnsureDocumentationTextEndsWithAPeriod(declaration);
        }
Exemplo n.º 57
0
 protected virtual void AdditionalTestChecks(ITextControl textControl, IProject project)
 {
 }
Exemplo n.º 58
0
        void IExecutableAction.Execute(IDataContext context, DelegateExecute nextExecute)
        {
            ITextControl textControl = context.GetData(TextControlDataConstants.TEXT_CONTROL);

            if (textControl == null)
            {
                MessageBox.ShowError("Text control unavailable.");
                return;
            }

            ISolution solution = context.GetData(ProjectModelDataConstants.SOLUTION);

            if (solution == null)
            {
                return;
            }

            IClrTypeName clrTypeClassName = ResharperHelper.GetClassNameAppropriateToLocation(solution, textControl);

            if (clrTypeClassName == null)
            {
                return;
            }

            ICSharpTypeDeclaration typeDeclaration =
                ResharperHelper.FindFirstCharpTypeDeclarationInDocument(solution, textControl.Document);

            if (typeDeclaration == null)
            {
                return;
            }

            IProject currentProject = context.GetData(ProjectModelDataConstants.PROJECT);

            if (currentProject == null)
            {
                ResharperHelper.AppendLineToOutputWindow(solution.Locks, "Internal Error: No current project");
                return;
            }

            IList <TestCopProjectItem> targetProjects = currentProject.GetAssociatedProjects(textControl.ToProjectFile(solution));

            if (targetProjects.IsEmpty())
            {
                ResharperHelper.AppendLineToOutputWindow(solution.Locks,
                                                         "Unable to locate associated assembly - check project namespaces and testcop Regex");

                //ProjectMappingHelper.GetProjectMappingHeper().DumpDebug(solution);
                return;
            }

            TestFileAnalysisSettings settings = solution.GetPsiServices().SettingsStore
                                                .BindToContextTransient(ContextRange.Smart(textControl.ToDataContext()))
                                                .GetKey <TestFileAnalysisSettings>(SettingsOptimization.OptimizeDefault);

            string baseFileName = ResharperHelper.GetBaseFileName(context, solution);

            bool isTestFile = baseFileName.EndsWith(settings.TestClassSuffixes());

            if (isTestFile != currentProject.IsTestProject())
            {
                ResharperHelper.AppendLineToOutputWindow(solution.Locks,
                                                         string.Format(
                                                             "Don't know how to navigate with '{0}' within project '{1}'. It is a {2} file within a {3} project"
                                                             , baseFileName, currentProject.Name, isTestFile
                            ? "test"
                            : "code", currentProject.IsTestProject()
                            ? "test"
                            : "code"));
                return;
            }

            List <IClrDeclaredElement> elementsFoundInTarget   = new List <IClrDeclaredElement>();
            List <IClrDeclaredElement> elementsFoundInSolution = new List <IClrDeclaredElement>();

            foreach (TestCopProjectItem singleTargetProject in targetProjects)
            {
                foreach (TestCopProjectItem.FilePatternMatcher patternMatcher in singleTargetProject.FilePattern)
                {
                    // FindByClassName
                    elementsFoundInSolution.AddRangeIfMissing(
                        ResharperHelper.FindClass(solution, patternMatcher.RegEx.ToString()), this._declElementMatcher);
                    elementsFoundInTarget.AddRangeIfMissing(
                        ResharperHelper.FindClass(solution, patternMatcher.RegEx.ToString(),
                                                  new List <IProject> {
                        singleTargetProject.Project
                    }), this._declElementMatcher);

                    if (!isTestFile)
                    {
                        //Find via filename (for when we switch to test files)
                        IEnumerable <ITypeElement> otherMatches =
                            ResharperHelper.FindFirstTypeWithinCodeFiles(solution, patternMatcher.RegEx,
                                                                         singleTargetProject.Project);
                        elementsFoundInTarget.AddRangeIfMissing(otherMatches, this._declElementMatcher);
                    }
                }
            }

            if (!isTestFile)
            {
                IEnumerable <IClrDeclaredElement> references =
                    this.FindReferencesWithinAssociatedAssembly(context, solution, textControl, clrTypeClassName, targetProjects);
                elementsFoundInTarget.AddRangeIfMissing(references, this._declElementMatcher);
            }

            JumpToTestMenuHelper.PromptToOpenOrCreateClassFiles(this._menuDisplayer, textControl.Lifetime, context,
                                                                solution
                                                                , currentProject, clrTypeClassName, targetProjects
                                                                , elementsFoundInTarget, elementsFoundInSolution);
        }
 public MatchingResult Match(PrefixMatcher prefixMatcher, ITextControl textControl)
 {
     return(prefixMatcher.Matcher(myFakeText));
 }
Exemplo n.º 60
0
            private static PostfixTemplateContext TryReparseWith([NotNull] ISolution solution, [NotNull] ITextControl textControl, [NotNull] string reparseString)
            {
                var offset   = textControl.Caret.Offset();
                var document = textControl.Document;

                try
                {
                    document.InsertText(offset, reparseString);

                    solution.GetPsiServices().Files.CommitAllDocuments();

                    foreach (var position in TextControlToPsi.GetElements <ITreeNode>(solution, document, offset))
                    {
                        var templateContextFactory = LanguageManager.Instance.TryGetService <IPostfixTemplateContextFactory>(position.Language);
                        if (templateContextFactory != null)
                        {
                            var executionContext = new PostfixTemplateExecutionContext(
                                solution, textControl, position.GetSettingsStore(), reparseString, false);

                            return(templateContextFactory.TryCreate(position, executionContext));
                        }
                    }

                    return(null);
                }
                finally
                {
                    var reparseRange = TextRange.FromLength(offset, reparseString.Length);
                    document.DeleteText(reparseRange);
                }
            }