コード例 #1
0
        public void Then_RegistrationWithInstancesIsSerialized()
        {
            var loadedSection = SerializeAndLoadSection("SerializeInstances.config", s =>
            {
                var inst0 = new InstanceElement
                {
                    TypeName = "int",
                    Value    = "42"
                };

                var inst1 = new InstanceElement
                {
                    TypeName = "DateTime",
                    Value    = "today",
                    TypeConverterTypeName = "RelativeDateTextConverter"
                };

                var inst2 = new InstanceElement
                {
                    TypeName = "string",
                    Value    = "hello",
                    Name     = "AString"
                };

                var containerElement = new ContainerElement();
                containerElement.Instances.Add(inst0);
                containerElement.Instances.Add(inst1);
                containerElement.Instances.Add(inst2);

                s.Containers.Add(containerElement);
            });

            var instances = loadedSection.Containers.Default.Instances;

            instances.Select(i => i.TypeName)
            .AssertContainsExactly("int", "DateTime", "string");
            instances.Select(i => i.Value)
            .AssertContainsExactly("42", "today", "hello");
            instances.Select(i => i.TypeConverterTypeName)
            .AssertContainsExactly(String.Empty, "RelativeDateTextConverter", String.Empty);
            instances.Select(i => i.Name)
            .AssertContainsExactly(String.Empty, String.Empty, "AString");
        }
コード例 #2
0
        protected override void Arrange()
        {
            base.Arrange();

            var ctor = new ConstructorElement();
            ctor.Parameters.Add(
                new ParameterElement
                {
                    Name = "dependencyParameter",
                    Value = new DependencyElement {Name = "dep1"}
                });

            ctor.Parameters.Add(
                new ParameterElement
                {
                    Name = "valueParameter",
                    Value = new ValueElement
                    {
                        Value = "123",
                        TypeConverterTypeName = "IntConverter"
                    }
                });

            ctor.Parameters.Add(
                new ParameterElement
                {
                    Name = "optionalParameter",
                    Value = new OptionalElement()
                });

            var registration = new RegisterElement
            {
                TypeName = "MyType"
            };

            registration.InjectionMembers.Add(ctor);

            var container = new ContainerElement();
            container.Registrations.Add(registration);

            Section = new UnityConfigurationSection();
            Section.Containers.Add(container);
        }
コード例 #3
0
        public void Then_SectionWithExtendedContainerConfiguringElementsIsSerialized()
        {
            var loadedSection = SerializeAndLoadSection("SerializingExtensionElements.config", s =>
            {
                var extensionElement = new ContainerConfigElementTwo();
                var container        = new ContainerElement();
                container.ConfiguringElements.Add(extensionElement);
                s.Containers.Add(container);
                s.SectionExtensions.Add(new SectionExtensionElement
                {
                    TypeName = typeof(TestSectionExtension).AssemblyQualifiedName,
                    Prefix   = "pre1"
                });
            });

            loadedSection.Containers.Default.ConfiguringElements
            .Select(e => e.GetType())
            .AssertContainsExactly(typeof(ContainerConfigElementTwo));
        }
コード例 #4
0
        protected UnityConfigurationSection SerializeAndLoadConfig(string filename, Action <ContainerElement> containerInitializer)
        {
            var serializer = new ConfigSerializer(filename);
            var section    = new UnityConfigurationSection();

            section.SectionExtensions.Add(new SectionExtensionElement()
            {
                TypeName = typeof(InterceptionConfigurationExtension).AssemblyQualifiedName
            });

            var container = new ContainerElement();

            section.Containers.Add(container);

            containerInitializer(container);

            serializer.Save("unity", section);

            return((UnityConfigurationSection)serializer.Load().GetSection("unity"));
        }
コード例 #5
0
        public async Task SemanticErrorReported()
        {
            using var workspace = TestWorkspace.CreateCSharp(
                      "class C : Bar { }",
                      composition: SquiggleUtilities.CompositionWithSolutionCrawler
                      );

            var spans =
                await TestDiagnosticTagProducer <DiagnosticsSquiggleTaggerProvider> .GetDiagnosticsAndErrorSpans(
                    workspace
                    );

            Assert.Equal(1, spans.Item2.Count());

            var firstDiagnostic = spans.Item1.First();
            var firstSpan       = spans.Item2.First();

            Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType);

            var expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(
                        ClassificationTypeNames.Text,
                        "CS0246",
                        QuickInfoHyperLink.TestAccessor.CreateNavigationAction(
                            new Uri(
                                "https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0246)",
                                UriKind.Absolute
                                )
                            ),
                        "https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0246)"
                        ),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, firstDiagnostic.Message)
                    )
                );

            ToolTipAssert.EqualContent(expectedToolTip, firstSpan.Tag.ToolTipContent);
        }
コード例 #6
0
        /// <summary>
        /// Creates <see cref="IServiceContainer"/> by its configuration.
        /// </summary>
        /// <param name="section">IoC configuration section.</param>
        /// <param name="name">The name of container configuration to create container for.</param>
        /// <param name="parent">The parent container.</param>
        /// <returns>
        /// <see cref="IServiceContainer"/> for the specified named configuration.
        /// </returns>
        public static IServiceContainer Create(ConfigurationSection section, string name, IServiceContainer parent)
        {
            if (name.IsNullOrEmpty())
            {
                name = string.Empty;
            }

            ContainerElement configuration = section == null ? null : section.Containers[name];

            if (configuration == null)
            {
                configuration = new ContainerElement();
            }

            var registrations = new List <ServiceRegistration>();
            var typeRegistry  = new TypeRegistry(new ServiceTypeRegistrationProcessor());

            foreach (var typeRegistrationElement in configuration.Auto)
            {
                typeRegistry.Register(typeRegistrationElement.ToNative());
            }
            foreach (var type in typeRegistry)
            {
                registrations.AddRange(ServiceRegistration.CreateAll(type));
            }
            foreach (var serviceRegistrationElement in configuration.Explicit)
            {
                registrations.Add(serviceRegistrationElement.ToNative());
            }

            var currentParent = configuration.Parent.IsNullOrEmpty()
        ? parent
        : Create(section, configuration.Parent, parent);

            var containerType = configuration.Type.IsNullOrEmpty() ?
                                typeof(ServiceContainer) :
                                Type.GetType(configuration.Type);

            return(Create(containerType, registrations, currentParent));
        }
コード例 #7
0
        private void SwitchSubViews(CharacterSubViewBase _newView)
        {
            if (_newView == null)
            {
                Debug.LogWarning("You tried to switch to a vew that is null");
                return;
            }
            if (m_currentSubView == _newView)
            {
                return;
            }

            if (m_currentSubView != null)
            {
                m_currentSubView.OnViewLostFocus();
                ContainerElement.Q <VisualElement>("workflow-area").Remove(m_currentSubView.ContainerElement);
            }

            m_currentSubView = _newView;
            m_currentSubView.OnViewFocused();
            ContainerElement.Q <VisualElement>("workflow-area").Add(m_currentSubView.ContainerElement);
        }
コード例 #8
0
        protected override void HandleViewLostFocus()
        {
            RemoveCallbacksFromListView(ref m_actionListView);
            RemoveCallbacksFromListView(ref m_transitionListView);
            RemoveCallbacksFromListView(ref m_availabeStatesListView);
            RemoveCallbacksFromListView(ref m_animationListView);

            m_actionListView.onSelectionChange     -= OnActionListItemSelected;
            m_transitionListView.onSelectionChange -= OnActionListItemSelected;

            m_animationListView.onSelectionChange -= OnAnimationListItemSelected;

            if (m_availabeStatesListView != null)
            {
                m_availabeStatesListView.onSelectionChange -= OnActionListItemSelected;
            }
            ContainerElement.Q <VisualElement>("state-details-area").Clear();
            CleanupGraph();
            UnSubscribeFromButtonCallBacks();
            CleanupControls();

            m_animFilterField.UnregisterValueChangedCallback(OnTextChanged);
        }
コード例 #9
0
ファイル: MaterialNode.cs プロジェクト: JasonL663/RMDEditor
        public MaterialNode(ContainerElement elem)
            : base(elem)
        {
            if (RmdNodes.Length > 0 && RmdNodes.First().ElementType == 0x1)
            {
                RmdNodes.First().Text = "Material Data";
            }

            _TextureRefNode = Nodes[1] as TextureRefNode;
            if (_TextureRefNode != null)
            {
                _TextureRefNode.Text = "Texture Reference";
            }

            if (RmdNodes.Length > 1 && RmdNodes.Last().ElementType == 0x3)
            {
                RmdNodes.Last().Text = "Ex Data";
            }


            Text             = string.Format("Material [{0}]", _TextureRefNode.TextureName);
            _SurrogateObject = new SurrogateDataObject(this);
        }
コード例 #10
0
        public async Task GetDescriptionAsync_DescriptionData_AsksFactoryForDescription()
        {
            // Arrange
            var expectedResult     = new ContainerElement(ContainerElementStyle.Wrapped);
            var description        = new AttributeCompletionDescription(Array.Empty <AttributeDescriptionInfo>());
            var descriptionFactory = Mock.Of <VisualStudioDescriptionFactory>(factory => factory.CreateClassifiedDescription(description) == expectedResult);
            var source             = new RazorDirectiveAttributeCompletionSource(
                Dispatcher,
                Mock.Of <VisualStudioRazorParser>(),
                Mock.Of <RazorCompletionFactsService>(),
                Mock.Of <ICompletionBroker>(),
                descriptionFactory);
            var completionSessionSource = Mock.Of <IAsyncCompletionSource>();
            var completionItem          = new CompletionItem("@random", completionSessionSource);

            completionItem.Properties.AddProperty(RazorDirectiveAttributeCompletionSource.DescriptionKey, description);

            // Act
            var result = await source.GetDescriptionAsync(session : null, completionItem, CancellationToken.None);

            // Assert
            Assert.Equal(expectedResult, result);
        }
コード例 #11
0
ファイル: TextureNode.cs プロジェクト: JasonL663/RMDEditor
        public TextureNode(ContainerElement elem)
            : base(elem)
        {
            Text = GetTextureName();

            if (!elem.Elements.Select(x => x.Type).SequenceEqual(new uint[] { 0x1, 0x2, 0x2, 0x1, 0x3 }))
            {
                throw new ArgumentException();
            }

            RmdNode oldNode = RmdNodes[3];

            _TextureImageNode = new TextureImageNode(oldNode.Element as ContainerElement);
            Nodes.Insert(3, _TextureImageNode);
            Nodes.Remove(oldNode);

            Nodes[0].Text = "Usage Data";
            Nodes[1].Text = "Name Data";
            Nodes[2].Text = "Unknown";
            Nodes[4].Text = "Ex Data";

            _SurrogateObject = new SurrogateDataObject(this);
        }
コード例 #12
0
        public async Task <object> GetDescriptionAsync(IAsyncCompletionSession session, CompletionItem item, CancellationToken token)
        {
            var content = new ContainerElement(
                ContainerElementStyle.Wrapped,
                CompletionItemIcon,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, "Hello!"),
                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, " This is a sample item")));
            var lineInfo = new ClassifiedTextElement(
                new ClassifiedTextRun(
                    PredefinedClassificationTypeNames.Comment,
                    "You are on line " + ((int)(session.Properties["LineNumber"]) + 1).ToString()));
            var timeInfo = new ClassifiedTextElement(
                new ClassifiedTextRun(
                    PredefinedClassificationTypeNames.Identifier,
                    "and it is " + DateTime.Now.ToShortTimeString()));

            return(new ContainerElement(
                       ContainerElementStyle.Stacked,
                       content,
                       lineInfo,
                       timeInfo));
        }
コード例 #13
0
        public async Task SemanticErrorReported()
        {
            using var workspace = TestWorkspace.CreateCSharp("class C : Bar { }", composition: SquiggleUtilities.CompositionWithSolutionCrawler);

            var spans = await TestDiagnosticTagProducer <DiagnosticsSquiggleTaggerProvider> .GetDiagnosticsAndErrorSpans(workspace);

            Assert.Equal(1, spans.Item2.Count());

            var firstDiagnostic = spans.Item1.First();
            var firstSpan       = spans.Item2.First();

            Assert.Equal(PredefinedErrorTypeNames.SyntaxError, firstSpan.Tag.ErrorType);

            var expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "CS0246"),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, firstDiagnostic.Message)));

            ToolTipAssert.EqualContent(expectedToolTip, firstSpan.Tag.ToolTipContent);
        }
コード例 #14
0
        // This is called on a background thread.
        public Task <QuickInfoItem> GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellationToken)
        {
            var triggerPoint = session.GetTriggerPoint(_textBuffer.CurrentSnapshot);

            if (triggerPoint?.Snapshot?.ContentType?.TypeName?.ToLower() == "csharp")
            {
                var allLines   = triggerPoint.Value.Snapshot.Lines.Select(x => x.GetText()).ToArray();
                var line       = triggerPoint.Value.GetContainingLine();
                var linesCount = linesCounter.GetCurrentLinesInMethod(allLines, line.LineNumber);
                var lineSpan   = _textBuffer.CurrentSnapshot.CreateTrackingSpan(line.Extent, SpanTrackingMode.EdgeInclusive);

                var lineNumberElm = new ContainerElement(
                    ContainerElementStyle.Wrapped,
                    new ImageElement(_icon),
                    new ClassifiedTextElement(
                        new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, "Lines count in current block: "),
                        new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, $"{linesCount}")
                        ));

                return(Task.FromResult(new QuickInfoItem(lineSpan, lineNumberElm)));
            }

            return(Task.FromResult <QuickInfoItem>(null));
        }
コード例 #15
0
        public void Then_SectionWithExtendedInjectionmemberElementsIsSerialized()
        {
            var loadedSection = SerializeAndLoadSection("SerializingExtensionElements.config", s =>
            {
                var registration = new RegisterElement
                {
                    TypeName = "string"
                };
                registration.InjectionMembers.Add(new TestInjectionMemberElement());

                var container = new ContainerElement();
                container.Registrations.Add(registration);
                s.Containers.Add(container);
                s.SectionExtensions.Add(new SectionExtensionElement
                {
                    TypeName = typeof(TestSectionExtension).AssemblyQualifiedName,
                    Prefix   = "pre1"
                });
            });

            loadedSection.Containers.Default.Registrations[0].InjectionMembers
            .Select(i => i.GetType())
            .AssertContainsExactly(typeof(TestInjectionMemberElement));
        }
コード例 #16
0
        public TextureImageNode(ContainerElement elem)
            : base(elem)
        {
            Text = "Texture Image";

            if (!elem.Elements.Select(x => x.Type).SequenceEqual(new uint[] { 0x1, 0x1 }))
            {
                throw new ArgumentException();
            }

            DataNode oldInfoNode = Nodes[0] as DataNode;

            _ImageInfoNode = new ImageInfoNode(oldInfoNode.DataElement);
            DataNode oldImageNode = Nodes[1] as DataNode;

            _ImageDataNode = new ImageDataNode(oldImageNode.DataElement, _ImageInfoNode.DataElement);

            Nodes.Insert(0, _ImageInfoNode);
            Nodes.Remove(oldInfoNode);
            Nodes.Insert(1, _ImageDataNode);
            Nodes.Remove(oldImageNode);

            _SurrogateObject = new SurrogateDataObject(this);
        }
コード例 #17
0
        private static void FillSectionWithConstructors(UnityConfigurationSection s)
        {
            var zeroArgCtor = new ConstructorElement();
            var intCtor     = new ConstructorElement();

            intCtor.Parameters.Add(new ParameterElement
            {
                Name  = "intParam",
                Value = new ValueElement
                {
                    Value = "23"
                }
            });

            var zeroArgRegistration = new RegisterElement
            {
                TypeName = "SomeType",
                Name     = "zeroArg"
            };

            zeroArgRegistration.InjectionMembers.Add(zeroArgCtor);

            var oneArgRegistration = new RegisterElement
            {
                TypeName = "SomeType",
                Name     = "oneArg"
            };

            oneArgRegistration.InjectionMembers.Add(intCtor);

            var container = new ContainerElement();

            container.Registrations.Add(zeroArgRegistration);
            container.Registrations.Add(oneArgRegistration);
            s.Containers.Add(container);
        }
コード例 #18
0
        private static string SimpleGrid <T>(this HtmlHelper html, IEnumerable <T> listItems, IEnumerable <ColumnOption <T> > options, GridOption <T> gridOption, bool showHeader)
        {
            ContainerElement container = new ContainerElement();

            container.Class("table-container");
            if (gridOption != null && gridOption.Style != null)
            {
                container.Class("table-container").Style(gridOption.Style);
            }
            TagBuilder builder = new TagBuilder("table");

            builder.AddCssClass("table-list maxwidth");
            builder.MergeAttribute("border", "0");
            builder.MergeAttribute("cellpadding", "0");
            builder.MergeAttribute("cellspacing", "0");

            if (showHeader)
            {
                builder.InnerHtml += BuildListDataHeader <T>(html, options, gridOption);
            }
            if (listItems != null && listItems.Count() > 0)
            {
                bool isAltRow = false;
                foreach (var item in listItems)
                {
                    builder.InnerHtml += BuildListDataRow(html, item, options, isAltRow, gridOption);
                    isAltRow           = !isAltRow;
                }
            }
            else if (gridOption == null || gridOption.Style == null || !gridOption.Style.Contains(HtmlStyleAttribute.Height))
            {
                builder.InnerHtml += BuildListEmptyDataRow(html, options);
            }
            container.InnerElement(new TextElement().InnerText(builder.ToString()));
            return(container.ToString());
        }
        public IReadOnlyList <string> FlattenToStrings(ContainerElement element)
        {
            var flattenedList = new List <string>();

            foreach (var child in element.Elements)
            {
                switch (child)
                {
                case ContainerElement childContainer:
                    var flattened = FlattenToStrings(childContainer);
                    flattenedList.AddRange(flattened);
                    break;

                case ClassifiedTextElement textElement:
                    foreach (var run in textElement.Runs)
                    {
                        flattenedList.Add(run.Text);
                    }
                    break;
                }
            }

            return(flattenedList);
        }
コード例 #20
0
ファイル: WebForm.cs プロジェクト: wdstest/SharpJS
 public override void UpdateContent()
 {
     base.UpdateContent();
     ContainerElement.AppendChild(InternalElement);
 }
コード例 #21
0
        internal static async Task <IntellisenseQuickInfoItem> BuildItemAsync(ITrackingSpan trackingSpan,
                                                                              CodeAnalysisQuickInfoItem quickInfoItem,
                                                                              ITextSnapshot snapshot,
                                                                              Document document,
                                                                              Lazy <IStreamingFindUsagesPresenter> streamingPresenter,
                                                                              CancellationToken cancellationToken)
        {
            // Build the first line of QuickInfo item, the images and the Description section should be on the first line with Wrapped style
            var glyphs            = quickInfoItem.Tags.GetGlyphs();
            var symbolGlyph       = glyphs.FirstOrDefault(g => g != Glyph.CompletionWarning);
            var warningGlyph      = glyphs.FirstOrDefault(g => g == Glyph.CompletionWarning);
            var firstLineElements = new List <object>();

            if (symbolGlyph != Glyph.None)
            {
                firstLineElements.Add(new ImageElement(symbolGlyph.GetImageId()));
            }

            if (warningGlyph != Glyph.None)
            {
                firstLineElements.Add(new ImageElement(warningGlyph.GetImageId()));
            }

            var elements    = new List <object>();
            var descSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description);

            if (descSection != null)
            {
                var isFirstElement = true;
                foreach (var element in Helpers.BuildInteractiveTextElements(descSection.TaggedParts, document, streamingPresenter))
                {
                    if (isFirstElement)
                    {
                        isFirstElement = false;
                        firstLineElements.Add(element);
                    }
                    else
                    {
                        // If the description section contains multiple paragraphs, the second and additional paragraphs
                        // are not wrapped in firstLineElements (they are normal paragraphs).
                        elements.Add(element);
                    }
                }
            }

            elements.Insert(0, new ContainerElement(ContainerElementStyle.Wrapped, firstLineElements));

            var documentationCommentSection = quickInfoItem.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.DocumentationComments);

            if (documentationCommentSection != null)
            {
                var isFirstElement = true;
                foreach (var element in Helpers.BuildInteractiveTextElements(documentationCommentSection.TaggedParts, document, streamingPresenter))
                {
                    if (isFirstElement)
                    {
                        isFirstElement = false;

                        // Stack the first paragraph of the documentation comments with the last line of the description
                        // to avoid vertical padding between the two.
                        var lastElement = elements[elements.Count - 1];
                        elements[elements.Count - 1] = new ContainerElement(
                            ContainerElementStyle.Stacked,
                            lastElement,
                            element);
                    }
                    else
                    {
                        elements.Add(element);
                    }
                }
            }

            // Add the remaining sections as Stacked style
            elements.AddRange(
                quickInfoItem.Sections.Where(s => s.Kind != QuickInfoSectionKinds.Description && s.Kind != QuickInfoSectionKinds.DocumentationComments)
                .SelectMany(s => Helpers.BuildInteractiveTextElements(s.TaggedParts, document, streamingPresenter)));

            // build text for RelatedSpan
            if (quickInfoItem.RelatedSpans.Any())
            {
                var classifiedSpanList = new List <ClassifiedSpan>();
                foreach (var span in quickInfoItem.RelatedSpans)
                {
                    var classifiedSpans = await ClassifierHelper.GetClassifiedSpansAsync(document, span, cancellationToken).ConfigureAwait(false);

                    classifiedSpanList.AddRange(classifiedSpans);
                }

                var tabSize = document.Project.Solution.Workspace.Options.GetOption(FormattingOptions.TabSize, document.Project.Language);
                var text    = await document.GetTextAsync().ConfigureAwait(false);

                var spans    = IndentationHelper.GetSpansWithAlignedIndentation(text, classifiedSpanList.ToImmutableArray(), tabSize);
                var textRuns = spans.Select(s => new ClassifiedTextRun(s.ClassificationType, snapshot.GetText(s.TextSpan.ToSpan()), ClassifiedTextRunStyle.UseClassificationFont));

                if (textRuns.Any())
                {
                    elements.Add(new ClassifiedTextElement(textRuns));
                }
            }

            var content = new ContainerElement(
                ContainerElementStyle.Stacked | ContainerElementStyle.VerticalPadding,
                elements);

            return(new IntellisenseQuickInfoItem(trackingSpan, content));
        }
コード例 #22
0
 private void FindDataBox(ref VisualElement _target, string _boxName)
 {
     _target = ContainerElement.Q <VisualElement>(_boxName);
 }
 protected override void Act()
 {
     base.Act();
     this.defaultContainer   = this.section.Containers.Default;
     this.newSchemaContainer = this.section.Containers["newSchema"];
 }
コード例 #24
0
        // This is called on a background thread.
        public async Task <QuickInfoItem> GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellationToken)
        {
            var triggerPoint = session.GetTriggerPoint(textBuffer.CurrentSnapshot);

            if (triggerPoint != null)
            {
                TextExtent   extent     = textStructureNavigator.GetExtentOfWord(triggerPoint.Value);
                SnapshotSpan extentSpan = extent.Span;

                ITextSnapshotLine line     = triggerPoint.Value.GetContainingLine();
                ITrackingSpan     lineSpan = textBuffer.CurrentSnapshot.CreateTrackingSpan(line.Extent, SpanTrackingMode.EdgeInclusive);

                try
                {
                    if (debugger == null)
                    {
                        return(null);
                    }

                    var stackFrame = debugger.CurrentStackFrame;

                    if (stackFrame == null)
                    {
                        return(null);
                    }

                    // Try to extent the span to the potential chain of member accesses on the left
                    int    lineStartPosition = lineSpan.GetStartPoint(textBuffer.CurrentSnapshot).Position;
                    string lineText          = lineSpan.GetText(textBuffer.CurrentSnapshot);

                    int localPosition = extentSpan.Start.Position - lineStartPosition;

                    while (localPosition > 1 && (lineText[localPosition - 1] == '.' || lineText[localPosition - 1] == ':'))
                    {
                        TextExtent   leftExtent     = textStructureNavigator.GetExtentOfWord(new SnapshotPoint(textBuffer.CurrentSnapshot, lineStartPosition + localPosition - 2));
                        SnapshotSpan leftExtentSpan = leftExtent.Span;

                        if (leftExtentSpan.Start.Position >= lineStartPosition)
                        {
                            extentSpan = new SnapshotSpan(leftExtentSpan.Start, extentSpan.End.Position - leftExtentSpan.Start.Position);

                            localPosition = leftExtentSpan.Start.Position - lineStartPosition;
                        }
                    }

                    var expressionText = extentSpan.GetText();

                    // Switch to main thread to access properties
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    var language = stackFrame.Language;

                    if (language != "Lua")
                    {
                        return(null);
                    }

                    var expression = debugger.GetExpression3($"```{expressionText}", stackFrame, false, false, false, 500);

                    if (expression == null)
                    {
                        return(null);
                    }

                    if (!expression.IsValidValue)
                    {
                        return(null);
                    }

                    string value = expression.Value;

                    string type = "";
                    string name = "";

                    if (value.IndexOf("```") >= 0)
                    {
                        type  = value.Substring(0, value.IndexOf("```"));
                        value = value.Substring(value.IndexOf("```") + 3);
                    }

                    if (value.IndexOf("```") >= 0)
                    {
                        name  = value.Substring(0, value.IndexOf("```"));
                        value = value.Substring(value.IndexOf("```") + 3);
                    }

                    var element = new ContainerElement(ContainerElementStyle.Wrapped, new ClassifiedTextElement(new ClassifiedTextRun(PredefinedClassificationTypeNames.Type, $"{type} "), new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, name), new ClassifiedTextRun(PredefinedClassificationTypeNames.String, $" = {value}")));

                    return(new QuickInfoItem(lineSpan, element));
                }
                catch (Exception)
                {
                    return(null);
                }
            }

            return(null);
        }
コード例 #25
0
        // This is called on a background thread.
        public Task <QuickInfoItem> GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellationToken)
        {
            var triggerPoint = session.GetTriggerPoint(_textBuffer.CurrentSnapshot);

            if (triggerPoint != null)
            {
                var line       = triggerPoint.Value.GetContainingLine();
                var lineNumber = triggerPoint.Value.GetContainingLine().LineNumber;
                var lineSpan   = _textBuffer.CurrentSnapshot.CreateTrackingSpan(line.Extent, SpanTrackingMode.EdgeInclusive);

                var    column = triggerPoint.Value.Position - line.Start.Position;
                string info, fmt, links;
                if (!GetQuickInfo(_filename, lineNumber, column, out info, out fmt, out links, cancellationToken))
                {
                    return(System.Threading.Tasks.Task.FromResult <QuickInfoItem>(null));
                }

                SymLink[]        symlinks = stringToSymLinks(links);
                ContainerElement infoElm  = null;
                Application.Current.Dispatcher.Invoke(delegate
                {
                    // back in the UI thread to allow creation of UIElements
                    var rows  = new List <object>();
                    var secs  = new List <object>();
                    bool bold = false;
                    Func <int, string, string, string> addClassifiedTextBlock = (int off, string txt, string type) =>
                    {
                        while (!String.IsNullOrEmpty(txt))
                        {
                            string tag = bold ? "</b>" : "<b>";
                            string sec;
                            bool secbold = bold;
                            var pos      = txt.IndexOf(tag);
                            if (pos >= 0)
                            {
                                bold = !bold;
                                sec  = txt.Substring(0, pos);
                                txt  = txt.Substring(pos + tag.Length);
                            }
                            else
                            {
                                sec = txt;
                                txt = null;
                            }
                            if (!String.IsNullOrEmpty(sec))
                            {
                                var tb     = createClassifiedTextBlock(session.TextView, sec, type, secbold);
                                int symidx = findSymLink(symlinks, off);
                                if (symidx >= 0)
                                {
                                    tb.enableLink(symlinks[symidx]);
                                }
                                secs.Add(tb);
                                off += sec.Length;
                            }
                        }
                        return(txt);
                    };

                    Func <int, string, string, string> addTextSection = (int off, string sec, string type) =>
                    {
                        var nls = sec.Split(new char[1] {
                            '\n'
                        }, StringSplitOptions.None);
                        for (int n = 0; n < nls.Length - 1; n++)
                        {
                            addClassifiedTextBlock(off, nls[n], type);
                            rows.Add(new ContainerElement(ContainerElementStyle.Wrapped, secs));
                            secs = new List <object>();
                            off += nls[n].Length + 1;
                        }
                        addClassifiedTextBlock(off, nls[nls.Length - 1], type);
                        return(sec);
                    };

                    string[] ops = fmt.Split(';');

                    int prevpos     = 0;
                    string prevtype = null;
                    foreach (var op in ops)
                    {
                        if (prevtype == null)
                        {
                            prevtype = op;
                        }
                        else
                        {
                            string[] colname = op.Split(':');
                            if (colname.Length == 2)
                            {
                                int pos;
                                if (Int32.TryParse(colname[0], out pos) && pos > prevpos)
                                {
                                    string sec = info.Substring(prevpos, pos - prevpos);
                                    addTextSection(prevpos, sec, prevtype);
                                    prevtype = colname[1];
                                    prevpos  = pos;
                                }
                            }
                        }
                    }
                    if (prevpos < info.Length)
                    {
                        if (prevtype != null)
                        {
                            string sec = info.Substring(prevpos, info.Length - prevpos);
                            addTextSection(prevpos, sec, prevtype);
                        }
                        else
                        {
                            addClassifiedTextBlock(prevpos, info, PredefinedClassificationTypeNames.SymbolDefinition);
                        }
                    }
                    if (secs.Count > 0)
                    {
                        rows.Add(new ContainerElement(ContainerElementStyle.Wrapped, secs));
                    }

                    // var tb = createClassifiedTextBlock(session.TextView, " Hello again", PredefinedClassificationTypeNames.Keyword);

/*
 *                                      var lineNumberElm = new ContainerElement(
 *                                              ContainerElementStyle.Wrapped,
 *                                              new ClassifiedTextElement(
 *                                                      new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, _filename),
 *                                                      new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, " Line number: "),
 *                                                      new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, $"{lineNumber + 1}"),
 *                                                      new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, " Column: "),
 *                                                      new ClassifiedTextRun(PredefinedClassificationTypeNames.Identifier, $"{column}")));
 *
 *                                      rows.Add(lineNumberElm);
 */

                    infoElm = new ContainerElement(ContainerElementStyle.Stacked, rows);
                });
                return(System.Threading.Tasks.Task.FromResult(new QuickInfoItem(lineSpan, infoElm)));
            }

            return(System.Threading.Tasks.Task.FromResult <QuickInfoItem>(null));
        }
 protected override void Arrange()
 {
     base.Arrange();
     container = Section.Containers.Default;
 }
コード例 #27
0
 public override string OnContainerClose(ContainerElement element)
 {
     return("");
 }
コード例 #28
0
        public async Task CustomizableTagsForUnnecessaryCode()
        {
            var workspaceXml =
                @"<Workspace>
    <Project Language=""C#"" CommonReferences=""true"">
        <Document FilePath = ""Test.cs"" >
// System is used - rest are unused.
using System.Collections;
using System;
using System.Diagnostics;
using System.Collections.Generic;

class Program
{
    void Test()
    {
        Int32 x = 2; // Int32 can be simplified.
        x += 1;
    }
}
        </Document>
    </Project>
</Workspace>";

            using var workspace = TestWorkspace.Create(workspaceXml, composition: SquiggleUtilities.CompositionWithSolutionCrawler);
            var options  = new Dictionary <OptionKey2, object>();
            var language = workspace.Projects.Single().Language;
            var preferIntrinsicPredefinedTypeOption      = new OptionKey2(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, language);
            var preferIntrinsicPredefinedTypeOptionValue = new CodeStyleOption2 <bool>(value: true, notification: NotificationOption2.Error);

            options.Add(preferIntrinsicPredefinedTypeOption, preferIntrinsicPredefinedTypeOptionValue);

            workspace.ApplyOptions(options);

            var analyzerMap = new Dictionary <string, ImmutableArray <DiagnosticAnalyzer> >
            {
                {
                    LanguageNames.CSharp,
                    ImmutableArray.Create <DiagnosticAnalyzer>(
                        new CSharpSimplifyTypeNamesDiagnosticAnalyzer(),
                        new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer(),
                        new ReportOnClassWithLink())
                }
            };

            var diagnosticsAndSpans = await TestDiagnosticTagProducer <DiagnosticsSquiggleTaggerProvider> .GetDiagnosticsAndErrorSpans(workspace, analyzerMap);

            var spans =
                diagnosticsAndSpans.Item1
                .Zip(diagnosticsAndSpans.Item2, (diagnostic, span) => (diagnostic, span))
                .OrderBy(s => s.span.Span.Span.Start).ToImmutableArray();

            Assert.Equal(4, spans.Length);
            var first  = spans[0].span;
            var second = spans[1].span;
            var third  = spans[2].span;
            var fourth = spans[3].span;

            var expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "IDE0005"),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, CSharpAnalyzersResources.Using_directive_is_unnecessary)));

            Assert.Equal(PredefinedErrorTypeNames.Suggestion, first.Tag.ErrorType);
            ToolTipAssert.EqualContent(expectedToolTip, first.Tag.ToolTipContent);
            Assert.Equal(40, first.Span.Start);
            Assert.Equal(25, first.Span.Length);

            expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "IDE0005"),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, CSharpAnalyzersResources.Using_directive_is_unnecessary)));

            Assert.Equal(PredefinedErrorTypeNames.Suggestion, second.Tag.ErrorType);
            ToolTipAssert.EqualContent(expectedToolTip, second.Tag.ToolTipContent);
            Assert.Equal(82, second.Span.Start);
            Assert.Equal(60, second.Span.Length);

            expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "id", QuickInfoHyperLink.TestAccessor.CreateNavigationAction(new Uri("https://github.com/dotnet/roslyn", UriKind.Absolute)), "https://github.com/dotnet/roslyn"),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "messageFormat")));

            Assert.Equal(PredefinedErrorTypeNames.Warning, third.Tag.ErrorType);
            ToolTipAssert.EqualContent(expectedToolTip, third.Tag.ToolTipContent);
            Assert.Equal(152, third.Span.Start);
            Assert.Equal(7, third.Span.Length);

            expectedToolTip = new ContainerElement(
                ContainerElementStyle.Wrapped,
                new ClassifiedTextElement(
                    new ClassifiedTextRun(ClassificationTypeNames.Text, "IDE0049"),
                    new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
                    new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
                    new ClassifiedTextRun(ClassificationTypeNames.Text, WorkspacesResources.Name_can_be_simplified)));

            Assert.Equal(PredefinedErrorTypeNames.SyntaxError, fourth.Tag.ErrorType);
            ToolTipAssert.EqualContent(expectedToolTip, fourth.Tag.ToolTipContent);
            Assert.Equal(196, fourth.Span.Start);
            Assert.Equal(5, fourth.Span.Length);
        }
コード例 #29
0
        // This is called on a background thread.
        public Task <QuickInfoItem> GetQuickInfoItemAsync(IAsyncQuickInfoSession session, CancellationToken cancellationToken)
        {
            if (IsEnabled())
            {
                var triggerPoint = session.GetTriggerPoint(_textBuffer.CurrentSnapshot);
                if (triggerPoint != null)
                {
                    var    line    = triggerPoint.Value.GetContainingLine();
                    string lineStr = line.GetText();

                    Match match = Regex.Match(lineStr, @"#\s*include\s*[<""](.+)[>""]");
                    if (match.Success)
                    {
                        string       file          = match.Groups[1].Value;
                        string       fileName      = Path.GetFileName(file);
                        string       lowerFilename = fileName.ToLower();
                        CompileValue value         = CompilerData.Instance.GetValue(CompilerData.CompileCategory.Include, lowerFilename);

                        Span span         = new Span(line.Extent.Start + match.Index, match.Length);
                        var  trackingSpan = _textBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive);

                        var headerElm = new ContainerElement(
                            ContainerElementStyle.Wrapped,
                            new ImageElement(_icon),
                            new ClassifiedTextElement(
                                new ClassifiedTextRun(PredefinedClassificationTypeNames.PreprocessorKeyword, fileName)
                                ));

                        if (value != null && value.Severity > 0)
                        {
                            var scoreElm = new ContainerElement(
                                ContainerElementStyle.Wrapped,
                                new ClassifiedTextElement(
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, "Compile Score:  ")
                                    ),
                                new ImageElement(value.Severity > 0 ? _severityOnIcon : _severityOffIcon),
                                new ImageElement(value.Severity > 1 ? _severityOnIcon : _severityOffIcon),
                                new ImageElement(value.Severity > 2 ? _severityOnIcon : _severityOffIcon),
                                new ImageElement(value.Severity > 3 ? _severityOnIcon : _severityOffIcon),
                                new ImageElement(value.Severity > 4 ? _severityOnIcon : _severityOffIcon)
                                );

                            //Found tooltip
                            var fullElm = new ContainerElement(
                                ContainerElementStyle.Stacked,
                                headerElm,
                                scoreElm,
                                new ClassifiedTextElement(
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.SymbolDefinition, "Max: "),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Comment, Common.UIConverters.GetTimeStr(value.Max)),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.SymbolDefinition, " Min: "),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Comment, Common.UIConverters.GetTimeStr(value.Min)),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.SymbolDefinition, " Average: "),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Comment, Common.UIConverters.GetTimeStr(value.Mean)),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.SymbolDefinition, " Count: "),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Comment, $"{value.Count}")
                                    ));

                            return(Task.FromResult(new QuickInfoItem(trackingSpan, fullElm)));
                        }
                        else
                        {
                            var fullElm = new ContainerElement(
                                ContainerElementStyle.Stacked,
                                headerElm,
                                new ClassifiedTextElement(
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.Keyword, "Compile Score: "),
                                    new ClassifiedTextRun(PredefinedClassificationTypeNames.ExcludedCode, " - ")
                                    ));

                            return(Task.FromResult(new QuickInfoItem(trackingSpan, fullElm)));
                        }
                    }
                }
            }

            return(Task.FromResult <QuickInfoItem>(null));
        }
コード例 #30
0
 private void UpdateData()
 {
     m_creationData.CharacterName = ContainerElement.Q <TextField>("charcter-name-text").value;
     m_creationData.CharacterType = (e_CombatantType)ContainerElement.Q <EnumField>("character-type-filter").value;
 }
コード例 #31
0
 public override string OnContainerOpen(ContainerElement element)
 {
     return("<span>");
 }