示例#1
0
        public static void DependencyPropertyRegisterAttachedReadOnly()
        {
            var code = @"
namespace N
{
    using System.Windows;

    public static class Foo
    {
        private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterAttachedReadOnly(
            ""Bar"",
            typeof(int),
            typeof(Foo),
            new PropertyMetadata(default(int)));

        public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty;

        /// <summary>Helper for setting <see cref=""BarPropertyKey""/> on <paramref name=""element""/>.</summary>
        /// <param name=""element""><see cref=""FrameworkElement""/> to set <see cref=""BarPropertyKey""/> on.</param>
        /// <param name=""value"">Bar property value.</param>
        public static void SetBar(this FrameworkElement element, int value)
        {
            element.SetValue(BarPropertyKey, value);
        }

        /// <summary>Helper for getting <see cref=""BarProperty""/> from <paramref name=""element""/>.</summary>
        /// <param name=""element""><see cref=""FrameworkElement""/> to read <see cref=""BarProperty""/> from.</param>
        /// <returns>Bar property value.</returns>
        [AttachedPropertyBrowsableForType(typeof(FrameworkElement))]
        public static int GetBar(this FrameworkElement element)
        {
            return (int) element.GetValue(BarProperty);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#2
0
        public static void OnPropertyChangedCallerMemberNameCopyLocalNullCheckInvoke()
        {
            var code = @"
namespace N
{
    using System.ComponentModel;
    using System.Runtime.CompilerServices;

    public class C : INotifyPropertyChanged
    {
        private int p;

        public event PropertyChangedEventHandler PropertyChanged;

        public int P
        {
            get { return this.p; }
            set
            {
                if (value == this.p) return;
                this.p = value;
                this.OnPropertyChanged();
            }
        }

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var handler = this.PropertyChanged;
            if (handler != null)
            {
                handler.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#3
0
        public static void DependencyPropertyRegisterWithMetadata(string metadata)
        {
            var code = @"
namespace N
{
    using System.Windows;
    using System.Windows.Controls;

    public class FooControl : Control
    {
        public static readonly DependencyProperty BarProperty = DependencyProperty.Register(
            nameof(Bar),
            typeof(int),
            typeof(FooControl),
            new PropertyMetadata(default(int), OnBarChanged));

        public int Bar
        {
            get { return (int)this.GetValue(BarProperty); }
            set { this.SetValue(BarProperty, value); }
        }

        private static void OnBarChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var control = (FooControl)d;
            var oldValue = (int)e.OldValue;
            var newValue = (int)e.NewValue;
        }

        private static object CoerceBar(DependencyObject d, object baseValue)
        {
            return baseValue;
        }
    }
}".AssertReplace("new PropertyMetadata(default(int), OnBarChanged)", metadata);

            RoslynAssert.Valid(Analyzer, code);
        }
示例#4
0
        public static void WhenOverriddenIsNotVirtualDispose()
        {
            var baseClass = @"
namespace N
{
    using System;
    using System.IO;

    abstract class BaseClass : IDisposable
    {
        public void Dispose()
        {
            this.M();
        }

        protected abstract void M();
    }
}";

            var code = @"
namespace N
{
    using System;
    using System.IO;

    class C : BaseClass
    {
        private readonly Stream stream = File.OpenRead(string.Empty);

        protected override void M()
        {
            this.stream.Dispose();
        }
    }
}";

            RoslynAssert.Valid(Analyzer, baseClass, code);
        }
示例#5
0
        public static void DependencyPropertyPartial(string setValueCall)
        {
            var part1 = @"
namespace N
{
    using System.Windows;
    using System.Windows.Controls;

    public partial class FooControl : Control
    {
        public static readonly DependencyProperty BarProperty = DependencyProperty.Register(
            ""Bar"",
            typeof(int),
            typeof(FooControl),
            new PropertyMetadata(default(int)));

        public int Bar
        {
            get { return (int)GetValue(BarProperty); }
            set { SetValue(BarProperty, value); }
        }
    }
}";

            var part2 = @"
namespace N
{
    public partial class FooControl
    {
        public void Meh()
        {
            this.SetValue(BarProperty, 1);
        }
    }
}".AssertReplace("this.SetValue(BarProperty, 1);", setValueCall);

            RoslynAssert.Valid(Analyzer, part1, part2);
        }
示例#6
0
        public static void WhenExplicitAndExplicit(string call)
        {
            var interfaceCode = @"
namespace RoslynSandbox
{
    using System;

    public interface IC
    {
        event EventHandler Bar;
    }
}";

            var code = @"
namespace RoslynSandbox
{
    using System;
    using System.Reflection;

    public sealed class C : IC
    {
        public C()
        {
            var member = typeof(C).GetEvent(nameof(this.Bar), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        }

        internal event EventHandler Bar;

        event EventHandler IC.Bar
        {
            add => this.Bar += value;
            remove => this.Bar -= value;
        }
    }
}".AssertReplace("typeof(C).GetEvent(nameof(this.Bar), BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)", call);

            RoslynAssert.Valid(Analyzer, Descriptor, interfaceCode, code);
        }
        public static void GetNestedType(string call)
        {
            var code = @"
namespace RoslynSandbox
{
    using System.Reflection;

    class C
    {
        public C()
        {
            var methodInfo = typeof(C).GetNestedType(nameof(Public), BindingFlags.Public);
        }

        public static class PublicStatic
        {
        }

        public class Generic<T>
        {
        }

        public class Public
        {
        }

        private static class PrivateStatic
        {
        }

        private class Private
        {
        }
    }
}".AssertReplace("GetNestedType(nameof(Public), BindingFlags.Public)", call);

            RoslynAssert.Valid(Analyzer, Descriptor, code);
        }
示例#8
0
        public static void ChainedCtors()
        {
            var code = @"
namespace N
{
    using System;

    public sealed class C : IDisposable
    {
        private readonly int n;

        public C()
            : this(new Disposable())
        {
        }

        private C(IDisposable disposable)
            : this(disposable, 1)
        {
        }

        private C(IDisposable disposable, int n)
        {
            this.n = n;
            this.Disposable = disposable;
        }

        public IDisposable Disposable { get; }

        public void Dispose()
        {
            this.Disposable.Dispose();
        }
    }
}";

            RoslynAssert.Valid(Analyzer, DisposableCode, code);
        }
示例#9
0
        public void DependencyPropertyPartial()
        {
            var part1 = @"
namespace RoslynSandbox
{
    using System.Windows;
    using System.Windows.Controls;

    public partial class FooControl : Control
    {
        private static readonly DependencyPropertyKey BarPropertyKey = DependencyProperty.RegisterReadOnly(
            ""Bar"",
            typeof(int),
            typeof(FooControl),
            new PropertyMetadata(default(int)));
    }
}";

            var part2 = @"
namespace RoslynSandbox
{
    using System.Windows;
    using System.Windows.Controls;

    public partial class FooControl
    {
        public static readonly DependencyProperty BarProperty = BarPropertyKey.DependencyProperty;

        public int Bar
        {
            get { return (int)GetValue(BarProperty); }
            set { SetValue(BarPropertyKey, value); }
        }
    }
}";

            RoslynAssert.Valid(Analyzer, part1, part2);
        }
示例#10
0
        public static void WhenOneValid()
        {
            var code = @"
namespace N
{
    using Gu.Roslyn.Asserts;
    using NUnit.Framework;

    public static class Valid
    {
        private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer();

        [Test]
        public static void M()
        {
            var c = ""class C { }"";
            RoslynAssert.Valid(Analyzer, c);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, Code.PlaceholderAnalyzer, code);
        }
        public static void DontUseUsingWhenAssigningAFieldTernary()
        {
            var code = @"
namespace N
{
    using System.IO;

    public class C
    {
        private readonly Stream stream;

        public C(bool flag)
        {
            var temp = File.OpenRead(string.Empty);
            this.stream = flag 
                ? null
                : temp;
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#12
0
        public void DependencyPropertyRegisterBackingField()
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System.Windows;
    using System.Windows.Controls;

    public class FooControl : Control
    {
        /// <summary>Identifies the <see cref=""Bar""/> dependency property.</summary>
        public static readonly DependencyProperty BarProperty = DependencyProperty.Register(nameof(Bar), typeof(int), typeof(FooControl), new PropertyMetadata(default(int)));

        public int Bar
        {
            get { return (int)GetValue(BarProperty); }
            set { SetValue(BarProperty, value); }
        }
    }
}";

            RoslynAssert.Valid(Analyzer, testCode);
        }
示例#13
0
        public static void IgnoresTypeName()
        {
            var code = @"
namespace N
{
    using System;

    public class C
    {
        public void M1()
        {
            this.M2(""Exception"");
        }

        public void M2(string value)
        {
            throw new ArgumentException(nameof(value), value);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#14
0
        public void IgnoreOverrideMetadataWhenContainingTypeIsNotSubclassOfOwningType()
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System.Globalization;
    using System.Windows;
    using System.Windows.Markup;

    public partial class App : Application
    {
        static App()
        {
            // Ensure that we are using the right culture
            FrameworkElement.LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }
    }
}";

            RoslynAssert.Valid(Analyzer, testCode);
        }
示例#15
0
        public void IgnoredWhenCreatedInScopeWithIf(string setCall)
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System.Windows;
    using System.Windows.Controls;

    public static class Foo
    {
        public static void MethodName()
        {
            var textBox = new TextBox();
            if (true)
            {
                textBox.Visibility = Visibility.Hidden;
            }
        }
    }
}".AssertReplace("textBox.Visibility = Visibility.Hidden;", setCall);

            RoslynAssert.Valid(Analyzer, testCode);
        }
示例#16
0
        public void NoDiagnosticWhenCustomComparerProvided()
        {
            var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@"
    class A { }
    class B { }
    class ABComparer : IComparer
    {
        public int Compare(object x, object y) => 0;
    }

    public class Tests
    {
        [Test]
        public void TestMethod()
        {
            var actual = new A();
            var expected = new B();
            Assert.That(actual, Is.GreaterThan(expected).Using(new ABComparer()));
        }
    }", "using System.Collections;");

            RoslynAssert.Valid(analyzer, testCode);
        }
示例#17
0
        public void DependencyPropertyRegisterAttached()
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System.Windows;

    public static class Foo
    {
        public static readonly DependencyProperty BarProperty = DependencyProperty.RegisterAttached(
            ""Bar"",
            typeof(int),
            typeof(Foo),
            new PropertyMetadata(default(int)));

        public static void SetBar(this FrameworkElement element, int value) => element.SetValue(BarProperty, value);

        public static int GetBar(this FrameworkElement element) => (int)element.GetValue(BarProperty);
    }
}";

            RoslynAssert.Valid(Analyzer, testCode);
        }
示例#18
0
            public static void ReassignAfterDispose()
            {
                var code = @"
namespace N
{
    using System.IO;

    public sealed class C
    {
        public void M()
        {
            var stream = File.OpenRead(string.Empty);
            var b = stream.ReadByte();
            stream.Dispose();
            stream = File.OpenRead(string.Empty);
            b = stream.ReadByte();
            stream.Dispose();
        }
    }
}";

                RoslynAssert.Valid(Analyzer, Descriptor, code);
            }
示例#19
0
        public static void DiagnosticsOneParamWithPositionAssertReplace()
        {
            var code = @"
namespace N
{
    using Gu.Roslyn.Asserts;
    using NUnit.Framework;

    public static class C
    {
        private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer();

        [TestCase(""C { }"")]
        public static void M(string declaration)
        {
            var code = ""↓class C { }"".AssertReplace(""C { }"", declaration);
            RoslynAssert.Diagnostics(Analyzer, code);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, Descriptor, Code.PlaceholderAnalyzer, code);
        }
        public void NoDiagnosticWhenExpectedHasIEquatableOfActual()
        {
            var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@"
                class A { }

                class B : IEquatable<A>
                {
                    public bool Equals(A? other) => true;
                }

                public class Tests
                {
                    [Test]
                    public void TestMethod()
                    {
                        var actual = new A();
                        var expected = new B();
                        Assert.That(actual, Is.EqualTo(expected));
                    }
                }");

            RoslynAssert.Valid(analyzer, testCode);
        }
示例#21
0
        public static void ILoggerFactoryAddApplicationInsights()
        {
            var code = @"
namespace N
{
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Logging;

    public class Foo
    {
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory)
        {
            loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Warning);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#22
0
        public static void DoNotWarnOnConfigureAwait()
        {
            var code = @"
namespace N
{
    using System.Threading.Tasks;

    public class C
    {
        public void M()
        {
            Task<int> a = null;
            Task b = null;
            a.ConfigureAwait(false);
            a.ConfigureAwait(true);
            b.ConfigureAwait(false);
            b.ConfigureAwait(true);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
示例#23
0
        public static void IgnoresVariableDeclaredAfter()
        {
            var code = @"
namespace N
{
    using System;

    public class C
    {
        public void M1()
        {
            var text = this.M2(""text"");
        }

        public string M2(string value)
        {
            throw new ArgumentException(nameof(value), value);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, code);
        }
        // Not-nested name
        public void Valid_Code_01()
        {
            var before = @"
namespace ExtendedAnalyzers
{
using System.IO;
using System.Threading.Tasks;

public class C
{
    public async Task MyMethod()
    {
        using (var fileStream = File.OpenRead(""filename""))
        {
                var reader = new StreamReader(fileStream);
                var text = await reader.ReadToEndAsync();
            }
        }
    }
}";

            RoslynAssert.Valid(Analyzer, before);
        }
示例#25
0
        public void AnalyzeWhenAllInformationIsProvidedByAttribute()
        {
            var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@"
    public class AnalyzeWhenAllInformationIsProvidedByAttribute
    {
        [Test]
        public void ShortName([ValueSource(typeof(AnotherClass), ""TestStrings"")] string name)
        {
            Assert.That(name.Length, Is.LessThan(15));
        }
    }

    class AnotherClass
    {
        static IEnumerable<string> TestStrings()
        {
            yield return ""SomeName"";
            yield return ""YetAnotherName"";
        }
    }", additionalUsings: "using System.Collections.Generic;");

            RoslynAssert.Valid(analyzer, testCode);
        }
示例#26
0
        public void WhenNoAttribute()
        {
            var testCode = @"
namespace RoslynSandbox
{
    using System;
    using System.Windows.Markup;

    [MarkupExtensionReturnType(typeof(string))]
    public class FooExtension : MarkupExtension
    {
        public string Text { get; set; }

        /// <inheritdoc />
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Text;
        }
    }
}";

            RoslynAssert.Valid(Analyzer, testCode);
        }
示例#27
0
        public static void WhenNoAsserts()
        {
            var code = @"
namespace N
{
    using System;
    using NUnit.Framework;

    public static class C
    {
        private static readonly PlaceholderAnalyzer Analyzer = new PlaceholderAnalyzer();

        [Test]
        public static void M()
        {
            var c = ""class C { }"";
            Console.WriteLine(c);
        }
    }
}";

            RoslynAssert.Valid(Analyzer, Code.PlaceholderAnalyzer, code);
        }
            public static void FactoryMethodCallingPrivateCtorWithCachedDisposable()
            {
                var code = @"
namespace N
{
    using System;

    public sealed class C
    {
        private static readonly IDisposable Cached = new Disposable();
        private readonly IDisposable value;

        private C(IDisposable value)
        {
            this.value = value;
        }

        public static C Create() => new C(Cached);
    }
}";

                RoslynAssert.Valid(Analyzer, DisposableCode, code);
            }
示例#29
0
        public static void DependencyPropertyRegisterBackingProperty(string nameof)
        {
            var code = @"
namespace N
{
    using System.Windows;
    using System.Windows.Controls;

    public class FooControl : Control
    {
        /// <summary>Identifies the <see cref=""Bar""/> dependency property.</summary>
        public static DependencyProperty BarProperty { get; } = DependencyProperty.Register(nameof(Bar), typeof(int), typeof(FooControl), new PropertyMetadata(default(int)));

        public int Bar
        {
            get { return (int)GetValue(BarProperty); }
            set { SetValue(BarProperty, value); }
        }
    }
}".AssertReplace("nameof(Bar)", nameof);

            RoslynAssert.Valid(Analyzer, code);
        }
示例#30
0
        public void NoDiagnosticWhenExpectedHasIComparableOfActual()
        {
            var testCode = TestUtility.WrapClassInNamespaceAndAddUsing(@"
                class A { }

                class B : IComparable<A>
                {
                    public int CompareTo(A other) => 0;
                }

                class Tests
                {
                    [Test]
                    public void TestMethod()
                    {
                        var actual = new A();
                        var expected = new B();
                        Assert.That(actual, Is.LessThanOrEqualTo(expected));
                    }
                }");

            RoslynAssert.Valid(analyzer, testCode);
        }