code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.Demos.WPF.VisualBasic.GanttChartDataGrid.ContinuousSchedule.MySettings Get Return Global.Demos.WPF.VisualBasic.GanttChartDataGrid.ContinuousSchedule.MySettings.Default End Get End Property End Module End Namespace
DlhSoftTeam/GanttChartLightLibrary-Demos
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/GanttChartDataGrid/ContinuousSchedule/My Project/Settings.Designer.vb
Visual Basic
mit
2,907
Imports System Imports System.Collections.Generic Imports System.Json Imports System.Linq Imports System.Runtime.Serialization Imports System.Runtime.Serialization.Json Imports System.Windows Imports System.Windows.Controls Imports ESRI.ArcGIS.Client Partial Public Class ArcGISWebClientSimple Inherits UserControl Private _serverUri As Uri Private _webclient As ArcGISWebClient Public Sub New() InitializeComponent() _webclient = New ArcGISWebClient() AddHandler _webclient.OpenReadCompleted, AddressOf webclient_OpenReadCompleted AddHandler _webclient.DownloadStringCompleted, AddressOf webclient_DownloadStringCompleted End Sub ' Get a list of services for an ArcGIS Server site Private Sub Button_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) _serverUri = New Uri(MySvrTextBox.Text) ' Add the parameter f=json to return a response in json format Dim parameters As IDictionary(Of String, String) = New Dictionary(Of String, String)() parameters.Add("f", "json") ' If another request is in progress, cancel it If _webclient.IsBusy Then _webclient.CancelAsync() End If _webclient.OpenReadAsync(_serverUri, parameters) End Sub ' Show a list of map services in the Listbox Private Sub webclient_OpenReadCompleted(ByVal sender As Object, ByVal e As ArcGISWebClient.OpenReadCompletedEventArgs) Try If e.Error IsNot Nothing Then Throw New Exception(e.Error.Message) End If ' Deserialize response using classes defined by a data contract, included in this class definition below Dim serializer As New DataContractJsonSerializer(GetType(MySvcs)) Dim mysvcs As MySvcs = TryCast(serializer.ReadObject(e.Result), MySvcs) If mysvcs.Services.Count = 0 Then Throw New Exception("No services returned") End If ' Use LINQ to return all map services Dim mapSvcs = From s In mysvcs.Services Where s.Type = "MapServer" Select s ' If map services are returned, show the Listbox with items as map services If mapSvcs.Count() > 0 Then MySvcTreeView.ItemsSource = mapSvcs MySvcTreeView.Visibility = System.Windows.Visibility.Visible NoMapServicesTextBlock.Visibility = System.Windows.Visibility.Collapsed Else MySvcTreeView.Visibility = System.Windows.Visibility.Collapsed NoMapServicesTextBlock.Visibility = System.Windows.Visibility.Visible End If Catch ex As Exception MessageBox.Show(ex.Message) Finally If e.Result IsNot Nothing Then e.Result.Close() End If End Try End Sub ' Stores site list of map services <DataContract> Public Class MySvcs <DataMember(Name:="services")> Public Property Services() As IList(Of MySvc) End Class ' Defines service item properties in a site list <DataContract> Public Class MySvc <DataMember(Name:="name")> Public Property Name() As String <DataMember(Name:="type")> Public Property Type() As String End Class ' When item (map service) in Listbox is selected, construct service url Private Sub MySvcTreeView_SelectedItemChanged(ByVal sender As Object, ByVal e As System.Windows.RoutedPropertyChangedEventArgs(Of Object)) If e.NewValue IsNot Nothing Then If _webclient.IsBusy Then _webclient.CancelAsync() End If ' Clear layers and set Extent to null (reset spatial reference) MyMap.Layers.Clear() MyMap.Extent = Nothing ' Get the service item selected Dim svc As MySvc = TryCast(e.NewValue, MySvc) ' Construct the url to the map service Dim svcUrl As String = String.Format("{0}/{1}/{2}", _serverUri, svc.Name, svc.Type) Dim svcParameters As IDictionary(Of String, String) = New Dictionary(Of String, String)() svcParameters.Add("f", "json") ' Pass the map service url as an user object for the handler _webclient.DownloadStringAsync(New Uri(svcUrl), svcParameters, ArcGISWebClient.HttpMethods.Auto, svcUrl) End If End Sub ' When map service item selected in Listbox, choose appropriate type and add to the map Private Sub webclient_DownloadStringCompleted(ByVal sender As Object, ByVal e As ArcGISWebClient.DownloadStringCompletedEventArgs) Try If e.Error IsNot Nothing Then Throw New Exception(e.Error.Message) End If ' Get the service url from the user object Dim svcUrl As String = TryCast(e.UserState, String) ' Abstract JsonValue holds json response Dim serviceInfo As JsonValue = JsonObject.Parse(e.Result) ' Use "singleFusedMapCache" to determine if a tiled or dynamic layer should be added to the map Dim isTiledMapService As Boolean = Boolean.Parse(serviceInfo("singleFusedMapCache").ToString()) Dim lyr As Layer = Nothing If isTiledMapService Then lyr = New ArcGISTiledMapServiceLayer() With {.Url = svcUrl} Else lyr = New ArcGISDynamicMapServiceLayer() With {.Url = svcUrl} End If If lyr IsNot Nothing Then AddHandler lyr.InitializationFailed, Sub(a, b) Throw New Exception(lyr.InitializationFailure.Message) MyMap.Layers.Add(lyr) End If Catch ex As Exception MessageBox.Show(ex.Message) End Try End Sub End Class
MrChen2015/arcgis-samples-silverlight
src/VBNet/ArcGISSilverlightSDK/Extras/ArcGISWebClientSimple.xaml.vb
Visual Basic
apache-2.0
5,932
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.Composition.Analyzers ''' <summary> ''' RS0006: Do not mix attributes from different versions of MEF ''' </summary> <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public NotInheritable Class BasicDoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer Inherits DoNotMixAttributesFromDifferentVersionsOfMEFAnalyzer End Class End Namespace
Anniepoh/roslyn-analyzers
src/Microsoft.Composition.Analyzers/VisualBasic/BasicDoNotMixAttributesFromDifferentVersionsOfMEF.vb
Visual Basic
apache-2.0
717
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Editor.CSharp.GoToDefinition Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.VisualBasic.GoToDefinition Imports Microsoft.CodeAnalysis.Editor.UnitTests.Utilities.GoToHelpers Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.UnitTests.GoToDefinition Public Class GoToDefinitionTests Private Function TestAsync(workspaceDefinition As XElement, Optional expectedResult As Boolean = True) As Tasks.Task Return GoToTestHelpers.TestAsync(workspaceDefinition, expectedResult, Function(document As Document, cursorPosition As Integer, presenters As IEnumerable(Of Lazy(Of INavigableItemsPresenter)), externalDefinitionProviders As IEnumerable(Of Lazy(Of INavigableDefinitionProvider))) Dim goToDefService = If(document.Project.Language = LanguageNames.CSharp, DirectCast(New CSharpGoToDefinitionService(presenters, externalDefinitionProviders), IGoToDefinitionService), New VisualBasicGoToDefinitionService(presenters, externalDefinitionProviders)) Return goToDefService.TryGoToDefinition(document, cursorPosition, CancellationToken.None) End Function) End Function #Region "P2P Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestP2PClassReference() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <Document> using N; class CSharpClass { VBCl$$ass vb } </Document> </Project> <Project Language="Visual Basic" AssemblyName="VBAssembly" CommonReferences="true"> <Document> namespace N public class [|VBClass|] End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region #Region "Normal CSharp Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinition() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionOnAnonymousMember() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class MyClass { public string [|Prop1|] { get; set; } } class Program { static void Main(string[] args) { var instance = new MyClass(); var x = new { instance.$$Prop1 }; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(3589, "https://github.com/dotnet/roslyn/issues/3589")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGoToDefinitionOnAnonymousMember() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> public class MyClass1 public property [|Prop1|] as integer end class class Program sub Main() dim instance = new MyClass1() dim x as new With { instance.$$Prop1 } end sub end class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionSameClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionNestedClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionDifferentFiles() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class OtherClass { SomeClass obj; } </Document> <Document> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> class [|SomeClass|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionPartialClasses() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class nothing { }; </Document> <Document> partial class [|OtherClass|] { int a; } </Document> <Document> partial class [|OtherClass|] { int b; }; </Document> <Document> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { int x; }; </Document> <Document> class ConsumingClass { void foo() { Some$$Class x; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionPartialMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class Test { partial void M(); } </Document> <Document> partial class Test { void Foo() { var t = new Test(); t.M$$(); } partial void [|M|]() { throw new NotImplementedException(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnMethodCall1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnMethodCall2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnMethodCall3() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnMethodCall4() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnConstructor1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { C() { } $$C c = new C(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(3376, "DevDiv_Projects/Roslyn")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnConstructor2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { [|C|]() { } C c = new $$C(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionWithoutExplicitConstruct() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|C|] { void Method() { C c = new $$C(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnLocalVariable1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int [|x|] = 2, y, z = $$x * 2; y = 10; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnLocalVariable2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void method() { int x = 2, [|y|], z = x * 2; $$y = 10; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnLocalField() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { int [|_X|] = 1, _Y; void method() { _$$X = 8; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnAttributeClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> [FlagsAttribute] class [|C|] { $$C c; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionTouchLeft() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { $$SomeClass c; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionTouchRight() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|SomeClass|] { SomeClass$$ c; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionOnGenericTypeParameterInPresenceOfInheritedNestedTypeWithSameName() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class B { public class T { } } class C<[|T|]> : B { $$T x; }]]> </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(538765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538765")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGotoDefinitionThroughOddlyNamedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|dynamic|] { } class C : dy$$namic { } ]]></Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionOnConstructorInitializer1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; using System.Collections.Generic; using System.Linq; class Program { private int v; public Program() : $$this(4) { } public [|Program|](int v) { this.v = v; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionOnExtensionMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class Program { static void Main(string[] args) { "1".$$TestExt(); } } public static class Ex { public static void TestExt<T>(this T ex) { } public static void [|TestExt|](this string ex) { } }]]> </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542004, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542004")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestLambdaParameter() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { delegate int D2(int i, int j); static void Main() { D2 d = (int [|i1|], int i2) => { return $$i1 + i2; }; } }]]> </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestLabel() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { [|Foo|]: int Foo; goto $$Foo; } }]]> </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpGoToDefinitionFromCref() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ /// <see cref="$$SomeClass"/> class [|SomeClass|] { }]]> </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region #Region "CSharp Venus Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpVenusGotoDefinition() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #line 1 "CSForm1.aspx" public class [|_Default|] { _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpFilterGotoDefResultsFromHiddenCodeForUIPresenters() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpDoNotFilterGotoDefResultsFromHiddenCodeForApis() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class [|_Default|] { #line 1 "CSForm1.aspx" _Defa$$ult a; #line default #line hidden } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region #Region "CSharp Script Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGoToDefinition() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } class OtherClass { Some$$Class obj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGoToDefinitionSameClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { Some$$Class someObject; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGoToDefinitionNestedClass() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class Outer { class [|Inner|] { } In$$ner someObj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionDifferentFiles() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class OtherClass { SomeClass obj; } </Document> <Document> <ParseOptions Kind="Script"/> class OtherClass2 { Some$$Class obj2; }; </Document> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionPartialClasses() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> partial class nothing { }; </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int a; } </Document> <Document> <ParseOptions Kind="Script"/> partial class [|OtherClass|] { int b; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { Other$$Class obj; } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionMethod() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class [|SomeClass|] { int x; }; </Document> <Document> <ParseOptions Kind="Script"/> class ConsumingClass { void foo() { Some$$Class x; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionOnMethodCall1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void [|M|]() { } void M(int i) { } void M(int i, string s) { } void M(string s, int i) { } void Call() { $$M(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionOnMethodCall2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void [|M|](int i, string s) { } void M(int i) { } void M(string s, int i) { } void Call() { $$M(0, "text"); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionOnMethodCall3() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void [|M|](int i) { } void M(string s, int i) { } void Call() { $$M(0); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpScriptGotoDefinitionOnMethodCall4() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <ParseOptions Kind="Script"/> class C { void M() { } void M(int i, string s) { } void M(int i) { } void [|M|](string s, int i) { } void Call() { $$M("text", 0); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpPreferNongeneratedSourceLocations() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Nongenerated.cs"> partial class [|C|] { void M() { $$C c; } } </Document> <Document FilePath="Generated.g.i.cs"> partial class C { } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(989476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/989476")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpUseGeneratedSourceLocationsIfNoNongeneratedLocationsAvailable() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document FilePath="Generated.g.i.cs"> class [|C|] { } </Document> <Document FilePath="Nongenerated.g.i.cs"> class D { void M() { $$C c; } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region #Region "Normal Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGoToDefinition() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] End Class Class OtherClass Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(541105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541105")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicPropertyBackingField() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Property [|P|] As Integer Sub M() Me.$$_P = 10 End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGoToDefinitionSameClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim obj As Some$$Class End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGoToDefinitionNestedClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Outer Class [|Inner|] End Class Dim obj as In$$ner End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGotoDefinitionDifferentFiles() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class OtherClass Dim obj As SomeClass End Class </Document> <Document> Class OtherClass2 Dim obj As Some$$Class End Class </Document> <Document> Class [|SomeClass|] End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGotoDefinitionPartialClasses() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> DummyClass End Class </Document> <Document> Partial Class [|OtherClass|] Dim a As Integer End Class </Document> <Document> Partial Class [|OtherClass|] Dim b As Integer End Class </Document> <Document> Class ConsumingClass Dim obj As Other$$Class End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGotoDefinitionMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub foo() Dim obj As Some$$Class End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(900438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/900438")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGotoDefinitionPartialMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Partial Class Customer Private Sub [|OnNameChanged|]() End Sub End Class </Document> <Document> Partial Class Customer Sub New() Dim x As New Customer() x.OnNameChanged$$() End Sub Partial Private Sub OnNameChanged() End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicTouchLeft() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub foo() Dim obj As $$SomeClass End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicTouchRight() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub foo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicMe() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() MyClass.Foo() $$Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Foo() End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicMyClass() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class B Sub New() End Sub End Class Class [|C|] Inherits B Sub New() MyBase.New() $$MyClass.Foo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Foo() End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542872")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicMyBase() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|B|] Sub New() End Sub End Class Class C Inherits B Sub New() $$MyBase.New() MyClass.Foo() Me.Bar() End Sub Private Sub Bar() End Sub Private Sub Foo() End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region #Region "Venus Visual Basic Tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicVenusGotoDefinition() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> #ExternalSource ("Default.aspx", 1) Class [|Program|] Sub Main(args As String()) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicFilterGotoDefResultsFromHiddenCodeForUIPresenters() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(545324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545324")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicDoNotFilterGotoDefResultsFromHiddenCodeForApis() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|Program|] Sub Main(args As String()) #ExternalSource ("Default.aspx", 1) Dim f As New Pro$$gram() End Sub End Class #End ExternalSource </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicTestThroughExecuteCommand() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class [|SomeClass|] Dim x As Integer End Class </Document> <Document> Class ConsumingClass Sub foo() Dim obj As SomeClass$$ End Sub End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGoToDefinitionOnExtensionMethod() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ Class Program Private Shared Sub Main(args As String()) Dim i As String = "1" i.Test$$Ext() End Sub End Class Module Ex <System.Runtime.CompilerServices.Extension()> Public Sub TestExt(Of T)(ex As T) End Sub <System.Runtime.CompilerServices.Extension()> Public Sub [|TestExt|](ex As string) End Sub End Module]]>] </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestAliasAndTarget1() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { $$AliasedSomething x = new AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestAliasAndTarget2() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using [|AliasedSomething|] = X.Something; namespace X { class Something { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new $$AliasedSomething(); X.Something y = new X.Something(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestAliasAndTarget3() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class [|Something|] { public Something() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.$$Something y = new X.Something(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(542220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542220")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCSharpTestAliasAndTarget4() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using AliasedSomething = X.Something; namespace X { class Something { public [|Something|]() { } } } class Program { static void Main(string[] args) { AliasedSomething x = new AliasedSomething(); X.Something y = new X.$$Something(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(543218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543218")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicQueryRangeVariable() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim arr = New Integer() {4, 5} Dim q3 = From [|num|] In arr Select $$num End Sub End Module </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(529060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529060")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestVisualBasicGotoConstant() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module M Sub Main() label1: GoTo $$200 [|200|]: GoTo label1 End Sub End Module </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(10132, "https://github.com/dotnet/roslyn/issues/10132")> <WorkItem(545661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545661")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCrossLanguageParameterizedPropertyOverride() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Class A Public Overridable ReadOnly Property X(y As Integer) As Integer [|Get|] End Get End Property End Class </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class B : A { public override int get_X(int y) { return base.$$get_X(y); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(866094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866094")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestCrossLanguageNavigationToVBModuleMember() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj"> <Document> Public Module A Public Sub [|M|]() End Sub End Module </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>VBProj</ProjectReference> <Document> class C { static void N() { A.$$M(); } } </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #Region "Show notification tests" <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestShowNotificationVB() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class SomeClass End Class Cl$$ass OtherClass Dim obj As SomeClass End Class </Document> </Project> </Workspace> Await TestAsync(workspace, expectedResult:=False) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestShowNotificationCS() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class SomeClass { } cl$$ass OtherClass { SomeClass obj; } </Document> </Project> </Workspace> Await TestAsync(workspace, expectedResult:=False) End Function <WorkItem(546341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546341")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestGoToDefinitionOnGlobalKeyword() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { gl$$obal::System.String s; } </Document> </Project> </Workspace> Await TestAsync(workspace, expectedResult:=False) End Function <WorkItem(902119, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902119")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestGoToDefinitionOnInferredFieldInitializer() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class2 Sub Test() Dim var1 = New With {Key .var2 = "Bob", Class2.va$$r3} End Sub Shared Property [|var3|]() As Integer Get End Get Set(ByVal value As Integer) End Set End Property End Class </Document> </Project> </Workspace> Await TestAsync(workspace) End Function <WorkItem(885151, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/885151")> <WpfFact, Trait(Traits.Feature, Traits.Features.GoToDefinition)> Public Async Function TestGoToDefinitionGlobalImportAlias() As Task Dim workspace = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <ProjectReference>VBAssembly</ProjectReference> <CompilationOptions> <GlobalImport>Foo = Importable.ImportMe</GlobalImport> </CompilationOptions> <Document> Public Class Class2 Sub Test() Dim x as Fo$$o End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly"> <Document> Namespace Importable Public Class [|ImportMe|] End Class End Namespace </Document> </Project> </Workspace> Await TestAsync(workspace) End Function #End Region End Class End Namespace
KevinH-MS/roslyn
src/EditorFeatures/Test2/GoToDefinition/GoToDefinitionTests.vb
Visual Basic
apache-2.0
50,756
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.IO Imports System.Runtime.InteropServices.ComTypes Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Host Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim Partial Friend Class TempPECompiler Private Class TempPEProject Implements IVbCompilerProject Private ReadOnly _tempPECompiler As TempPECompiler Private ReadOnly _compilerHost As IVbCompilerHost Private ReadOnly _references As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private ReadOnly _files As New HashSet(Of String)(StringComparer.OrdinalIgnoreCase) Private _parseOptions As VisualBasicParseOptions Private _compilationOptions As VisualBasicCompilationOptions Private _outputPath As String Private _runtimeLibraries As ImmutableArray(Of String) Public Sub New(tempPECompiler As TempPECompiler, compilerHost As IVbCompilerHost) _tempPECompiler = tempPECompiler _compilerHost = compilerHost End Sub Public Function CompileAndGetErrorCount(metadataService As IMetadataService) As Integer Dim trees = _files.Select(Function(path) Using stream = FileUtilities.OpenRead(path) Return SyntaxFactory.ParseSyntaxTree(SourceText.From(stream), options:=_parseOptions, path:=path) End Using End Function) Dim metadataReferences = _references.Concat(_runtimeLibraries) _ .Distinct(StringComparer.InvariantCultureIgnoreCase) _ .Select(Function(path) metadataService.GetReference(path, MetadataReferenceProperties.Assembly)) Dim c = VisualBasicCompilation.Create( Path.GetFileName(_outputPath), trees, metadataReferences, _compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)) Dim emitResult = c.Emit(_outputPath) Return emitResult.Diagnostics.Where(Function(d) d.Severity = DiagnosticSeverity.Error).Count() End Function Public Sub AddApplicationObjectVariable(wszClassName As String, wszMemberName As String) Implements IVbCompilerProject.AddApplicationObjectVariable Throw New NotImplementedException() End Sub Public Sub AddBuffer(wszBuffer As String, dwLen As Integer, wszMkr As String, itemid As UInteger, fAdvise As Boolean, fShowErrorsInTaskList As Boolean) Implements IVbCompilerProject.AddBuffer Throw New NotImplementedException() End Sub Public Function AddEmbeddedMetaDataReference(wszFileName As String) As Integer Implements IVbCompilerProject.AddEmbeddedMetaDataReference Return VSConstants.E_NOTIMPL End Function Public Sub AddEmbeddedProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddEmbeddedProjectReference Throw New NotImplementedException() End Sub Public Sub AddFile(wszFileName As String, itemid As UInteger, fAddDuringOpen As Boolean) Implements IVbCompilerProject.AddFile ' We are only ever given VSITEMIDs that are Nil because a TempPE project isn't ' associated with a IVsHierarchy. Contract.ThrowIfFalse(itemid = VSConstants.VSITEMID.Nil) _files.Add(wszFileName) End Sub Public Sub AddImport(wszImport As String) Implements IVbCompilerProject.AddImport Throw New NotImplementedException() End Sub Public Function AddMetaDataReference(wszFileName As String, bAssembly As Boolean) As Integer Implements IVbCompilerProject.AddMetaDataReference _references.Add(wszFileName) Return VSConstants.S_OK End Function Public Sub AddProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.AddProjectReference Throw New NotImplementedException() End Sub Public Sub AddResourceReference(wszFileName As String, wszName As String, fPublic As Boolean, fEmbed As Boolean) Implements IVbCompilerProject.AddResourceReference Throw New NotImplementedException() End Sub Public Function AdviseBuildStatusCallback(pIVbBuildStatusCallback As IVbBuildStatusCallback) As UInteger Implements IVbCompilerProject.AdviseBuildStatusCallback Throw New NotImplementedException() End Function Public Function CreateCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pCodeModel As EnvDTE.CodeModel) As Integer Implements IVbCompilerProject.CreateCodeModel Throw New NotImplementedException() End Function Public Function CreateFileCodeModel(pProject As EnvDTE.Project, pProjectItem As EnvDTE.ProjectItem, ByRef pFileCodeModel As EnvDTE.FileCodeModel) As Integer Implements IVbCompilerProject.CreateFileCodeModel Throw New NotImplementedException() End Function Public Sub DeleteAllImports() Implements IVbCompilerProject.DeleteAllImports Throw New NotImplementedException() End Sub Public Sub DeleteAllResourceReferences() Implements IVbCompilerProject.DeleteAllResourceReferences Throw New NotImplementedException() End Sub Public Sub DeleteImport(wszImport As String) Implements IVbCompilerProject.DeleteImport Throw New NotImplementedException() End Sub Public Sub Disconnect() Implements IVbCompilerProject.Disconnect End Sub Public Function ENCRebuild(in_pProgram As Object, ByRef out_ppUpdate As Object) As Integer Implements IVbCompilerProject.ENCRebuild Throw New NotImplementedException() End Function Public Sub FinishEdit() Implements IVbCompilerProject.FinishEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Function GetDefaultReferences(cElements As Integer, ByRef rgbstrReferences() As String, ByVal cActualReferences As IntPtr) As Integer Implements IVbCompilerProject.GetDefaultReferences Throw New NotImplementedException() End Function Public Sub GetEntryPointsList(cItems As Integer, strList() As String, ByVal pcActualItems As IntPtr) Implements IVbCompilerProject.GetEntryPointsList Throw New NotImplementedException() End Sub Public Sub GetMethodFromLine(itemid As UInteger, iLine As Integer, ByRef pBstrProcName As String, ByRef pBstrClassName As String) Implements IVbCompilerProject.GetMethodFromLine Throw New NotImplementedException() End Sub Public Sub GetPEImage(ByRef ppImage As IntPtr) Implements IVbCompilerProject.GetPEImage Throw New NotImplementedException() End Sub Public Sub RemoveAllApplicationObjectVariables() Implements IVbCompilerProject.RemoveAllApplicationObjectVariables Throw New NotImplementedException() End Sub Public Sub RemoveAllReferences() Implements IVbCompilerProject.RemoveAllReferences Throw New NotImplementedException() End Sub Public Sub RemoveFile(wszFileName As String, itemid As UInteger) Implements IVbCompilerProject.RemoveFile Throw New NotImplementedException() End Sub Public Sub RemoveFileByName(wszPath As String) Implements IVbCompilerProject.RemoveFileByName Throw New NotImplementedException() End Sub Public Sub RemoveMetaDataReference(wszFileName As String) Implements IVbCompilerProject.RemoveMetaDataReference Throw New NotImplementedException() End Sub Public Sub RemoveProjectReference(pReferencedCompilerProject As IVbCompilerProject) Implements IVbCompilerProject.RemoveProjectReference Throw New NotImplementedException() End Sub Public Sub RenameDefaultNamespace(bstrDefaultNamespace As String) Implements IVbCompilerProject.RenameDefaultNamespace Throw New NotImplementedException() End Sub Public Sub RenameFile(wszOldFileName As String, wszNewFileName As String, itemid As UInteger) Implements IVbCompilerProject.RenameFile Throw New NotImplementedException() End Sub Public Sub RenameProject(wszNewProjectName As String) Implements IVbCompilerProject.RenameProject Throw New NotImplementedException() End Sub Public Sub ResumePostedNotifications() Implements IVbCompilerProject.ResumePostedNotifications Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityLow() Implements IVbCompilerProject.SetBackgroundCompilerPriorityLow Throw New NotImplementedException() End Sub Public Sub SetBackgroundCompilerPriorityNormal() Implements IVbCompilerProject.SetBackgroundCompilerPriorityNormal Throw New NotImplementedException() End Sub Public Sub SetCompilerOptions(ByRef pCompilerOptions As VBCompilerOptions) Implements IVbCompilerProject.SetCompilerOptions _runtimeLibraries = VisualBasicProject.OptionsProcessor.GetRuntimeLibraries(_compilerHost, pCompilerOptions) _outputPath = PathUtilities.CombinePathsUnchecked(pCompilerOptions.wszOutputPath, pCompilerOptions.wszExeName) _parseOptions = VisualBasicProject.OptionsProcessor.ApplyVisualBasicParseOptionsFromCompilerOptions(VisualBasicParseOptions.Default, pCompilerOptions) ' Note that we pass a "default" compilation options with DLL set as output kind; the Apply method will figure out what the right one is and fix it up _compilationOptions = VisualBasicProject.OptionsProcessor.ApplyCompilationOptionsFromVBCompilerOptions( New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, parseOptions:=_parseOptions), pCompilerOptions) End Sub Public Sub SetModuleAssemblyName(wszName As String) Implements IVbCompilerProject.SetModuleAssemblyName Throw New NotImplementedException() End Sub Public Sub SetStreamForPDB(pStreamPDB As IStream) Implements IVbCompilerProject.SetStreamForPDB Throw New NotImplementedException() End Sub Public Sub StartBuild(pVsOutputWindowPane As IVsOutputWindowPane, fRebuildAll As Boolean) Implements IVbCompilerProject.StartBuild Throw New NotImplementedException() End Sub Public Sub StartDebugging() Implements IVbCompilerProject.StartDebugging Throw New NotImplementedException() End Sub Public Sub StartEdit() Implements IVbCompilerProject.StartEdit ' The project system calls BeginEdit/FinishEdit so we can batch and avoid doing ' expensive things between each call to one of the Add* methods. But since we're not ' doing anything expensive, this can be a no-op. End Sub Public Sub StopBuild() Implements IVbCompilerProject.StopBuild Throw New NotImplementedException() End Sub Public Sub StopDebugging() Implements IVbCompilerProject.StopDebugging Throw New NotImplementedException() End Sub Public Sub SuspendPostedNotifications() Implements IVbCompilerProject.SuspendPostedNotifications Throw New NotImplementedException() End Sub Public Sub UnadviseBuildStatusCallback(dwCookie As UInteger) Implements IVbCompilerProject.UnadviseBuildStatusCallback Throw New NotImplementedException() End Sub Public Sub WaitUntilBound() Implements IVbCompilerProject.WaitUntilBound Throw New NotImplementedException() End Sub End Class End Class End Namespace
abock/roslyn
src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/TempPECompiler.TempPEProject.vb
Visual Basic
mit
13,486
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.261 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.EntityFramework.My.MySettings Get Return Global.EntityFramework.My.MySettings.Default End Get End Property End Module End Namespace
RocketSoftware/multivalue-lab
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniVerse/EntityFramework/My Project/Settings.Designer.vb
Visual Basic
mit
2,934
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests ' This class tests binding of various expressions; i.e., the code in Binder_Expressions.vb ' ' Tests should be added here for every construct that can be bound ' correctly, with a test that compiles, verifies, and runs code for that construct. ' Tests should also be added here for every diagnostic that can be generated. Public Class Binder_Expressions_Tests Inherits BasicTestBase ' Test that BC30157 is generated for a member access off With when there is no containing With. <Fact> Public Sub MemberAccessNoContainingWith() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MemberAccessNoContainingWith"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x as Integer x = .goo End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30157: Leading '.' or '!' can only appear inside a 'With' statement. x = .goo ~~~~ </expected>) End Sub ' Test field access off a local variable of structure type. <Fact> Public Sub FieldAccessInLocalStruct() CompileAndVerify( <compilation name="FieldAccessInLocalStruct"> <file name="a.vb"> Imports System Module M1 Structure S1 Public Field1 As Integer End Structure Sub Main() Dim x as S1 x.Field1 = 123 Console.WriteLine(x.Field1) End Sub End Module </file> </compilation>, expectedOutput:="123") End Sub <WorkItem(679765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679765")> <NoIOperationValidationFact> Public Sub Bug679765() CompileAndVerify( <compilation> <file name="a.vb"> <%= SemanticResourceUtil.T_68086 %> </file> </compilation>, references:={MsvbRef}) End Sub <WorkItem(707924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/707924")> <Fact()> Public Sub Bug707924a() Dim source = SemanticResourceUtil.T_1247520 Dim result = VisualBasicSyntaxTree.ParseText(source).ToString() Assert.Equal(source, result) End Sub ' Test access to a local variable and assignment of them.. <Fact> Public Sub LocalVariable1() CompileAndVerify( <compilation name="LocalVariable1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x as Integer Dim y as Long x = 143 y = x Console.WriteLine(y) End Sub End Module </file> </compilation>, expectedOutput:="143") End Sub ' Test access to a local variable, parameter, type parameter, namespace with arity. <Fact> Public Sub LocalVariableWrongArity() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="LocalVariable1"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x, y as Integer x = 143 y = x(Of Integer) x = System.Collections(Of Decimal) End Sub Sub goo(y as string) dim z as string z = y(of Boolean) End Sub End Module Class Q(Of T, U) Sub a() dim x as integer = U(Of T) End Sub End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC32045: 'x' has no type parameters and so cannot have type arguments. y = x(Of Integer) ~~~~~~~~~~~~ BC32045: 'System.Collections' has no type parameters and so cannot have type arguments. x = System.Collections(Of Decimal) ~~~~~~~~~~~~ BC32045: 'y As String' has no type parameters and so cannot have type arguments. z = y(of Boolean) ~~~~~~~~~~~~ BC32045: 'U' has no type parameters and so cannot have type arguments. dim x as integer = U(Of T) ~~~~~~ </expected>) End Sub ' Test access to a local variable and assignment of them.. <Fact> Public Sub ArrayAssignment1() CompileAndVerify( <compilation name="ArrayAssignment1"> <file name="a.vb"> Imports System Module M1 Sub Main() dim z(10) as string dim i as integer i = 2 z(i) = "hello" Console.WriteLine(z(i)) End Sub End Module </file> </compilation>, expectedOutput:="hello") End Sub ' Test access to a local variable and assignment of them.. <Fact> Public Sub ArrayAssignmentError1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayAssignmentError1"> <file name="a.vb"> Imports System Module M1 Sub Main() dim z(10) as string z(1,1) = "world" z() = "world" End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30106: Number of indices exceeds the number of dimensions of the indexed array. z(1,1) = "world" ~~~~~ BC30105: Number of indices is less than the number of dimensions of the indexed array. z() = "world" ~~ </expected>) End Sub ' Test array upper bound is correct <WorkItem(4225, "DevDiv_Projects/Roslyn")> <Fact> Public Sub CheckArrayUpperBound() Dim compilation = CompileAndVerify( <compilation name="ArrayAssignmentError1"> <file name="a.vb"> Imports System Module M Sub Main() dim a as integer() = New Integer(1) {} Console.WriteLine(a.GetLength(0)) Console.WriteLine(New Integer(-1) {}.GetLength(0)) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 2 0 ]]>) End Sub ' Test access to a local variable and assignment of them.. <Fact()> Public Sub ArrayAssignmentError2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="ArrayAssignmentErrors2"> <file name="a.vb"> Option strict on Imports System Module M1 Sub Main() dim z(10) as string dim i as uinteger ' Should report an implicit conversion error, uinteger can't be converted to integer z(i) = "world" End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30512: Option Strict On disallows implicit conversions from 'UInteger' to 'Integer'. z(i) = "world" ~ </expected>) End Sub ' Test access to a parameter (both simple and byref) <Fact> Public Sub Parameter1() CompileAndVerify( <compilation name="Parameter1"> <file name="a.vb"> Imports System Module M1 Sub Goo(xParam as Integer, ByRef yParam As Long) Console.WriteLine("xParam = {0}", xParam) Console.WriteLine("yParam = {0}", yParam) xParam = 17 yParam = 189 Console.WriteLine("xParam = {0}", xParam) Console.WriteLine("yParam = {0}", yParam) End Sub Sub Main() Dim x as Integer Dim y as Long x = 143 y = 16442 Console.WriteLine("x = {0}", x) Console.WriteLine("y = {0}", y) Goo(x,y) Console.WriteLine("x = {0}", x) Console.WriteLine("y = {0}", y) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ x = 143 y = 16442 xParam = 143 yParam = 16442 xParam = 17 yParam = 189 x = 143 y = 189 ]]>) End Sub ' Test object creation expression <Fact> Public Sub SimpleObjectCreation1() CompileAndVerify( <compilation name="SimpleObjectCreation"> <file name="a.vb"> Imports System Class C1 Public Sub New() End Sub Sub Goo() Console.WriteLine("Called C1.Goo") End Sub End Class Module M1 Sub Main() dim c as C1 c = new C1() c.Goo() End Sub End Module </file> </compilation>, expectedOutput:="Called C1.Goo") End Sub ' Test object creation expression <Fact> Public Sub MeReference() CompileAndVerify( <compilation name="MeReference"> <file name="a.vb"> Imports System Class C1 private _i as integer Public Sub New(i as integer) Me._i = i Console.WriteLine(Me._i) End Sub End Class Module M1 Sub Main() dim c as C1 c = new C1(1) End Sub End Module </file> </compilation>, expectedOutput:="1") End Sub ' Test access to simple identifier that isn't found anywhere. <Fact> Public Sub SimpleNameNotFound() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="SimpleNameNotFound"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x as Integer x = goo End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30451: 'goo' is not declared. It may be inaccessible due to its protection level. x = goo ~~~ </expected>) End Sub <WorkItem(538871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538871")> <Fact> Public Sub QualifiedNameBeforeDotNotFound() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="QualifiedNameBeforeDotNotFound"> <file name="a.vb"> Imports System Module MainModule Class A End Class Sub Main() Rdim123.Rdim456() A.B.Rdim456() End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30451: 'Rdim123' is not declared. It may be inaccessible due to its protection level. Rdim123.Rdim456() ~~~~~~~ BC30456: 'B' is not a member of 'MainModule.A'. A.B.Rdim456() ~~~ </expected>) End Sub ' Test access to qualified identifier not found, in various scopes <Fact> Public Sub QualifiedNameNotFound() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="QualifiedNameNotFound"> <file name="a.vb"> Imports System Namespace N End Namespace Class C Public y as Integer End Class Module M1 Sub Main() Dim x as Integer Dim cInstance as C cInstance = Nothing x = N.goo x = C.goo x = cInstance.goo x = M1.goo End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30456: 'goo' is not a member of 'N'. x = N.goo ~~~~~ BC30456: 'goo' is not a member of 'C'. x = C.goo ~~~~~ BC30456: 'goo' is not a member of 'C'. x = cInstance.goo ~~~~~~~~~~~~~ BC30456: 'goo' is not a member of 'M1'. x = M1.goo ~~~~~~ </expected>) End Sub ' Test access qualified identifier off of type parameter <Fact> Public Sub TypeParamCantQualify() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="TypeParamCantQualify"> <file name="a.vb"> Imports System Class C(Of T) Public Sub f() dim x as Integer x = T.goo End Sub End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC32098: Type parameters cannot be used as qualifiers. x = T.goo ~~~~~ </expected>) End Sub ' Test access to simple identifier that can be found, but has an error. <Fact> Public Sub BadSimpleName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadSimpleName"> <file name="a.vb"> Imports System Class Goo(Of T) Shared Public x As Integer End Class Module Module1 Sub Main() Dim y As Integer y = Goo.x End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'Goo(Of T)'. y = Goo.x ~~~ </expected>) End Sub ' Test access to qualified identifier that can be found, but has an error. <Fact> Public Sub BadQualifiedName() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="BadQualifiedName"> <file name="a.vb"> Imports System Namespace N Class Goo(Of T) Shared Public x As Integer End Class End Namespace Class C Class Goo(Of T) Shared Public x As Integer End Class End Class Module Module1 Sub Main() Dim y As Integer Dim cInstance as C cInstance = Nothing y = N.Goo.x y = C.Goo.x y = cInstance.Goo.x y = cInstance.Goo(Of Integer).x End Sub End Module </file> </compilation>) ' Note that we produce different (but I think better) error messages than Dev10. AssertTheseDiagnostics(compilation, <expected> BC32042: Too few type arguments to 'Goo(Of T)'. y = N.Goo.x ~~~~~ BC32042: Too few type arguments to 'C.Goo(Of T)'. y = C.Goo.x ~~~~~ BC32042: Too few type arguments to 'C.Goo(Of T)'. y = cInstance.Goo.x ~~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. y = cInstance.Goo(Of Integer).x ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub ' Test access to instance member in various ways to get various errors. <Fact> Public Sub AccessInstanceFromStatic() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="AccessInstanceFromStatic"> <file name="a.vb"> Class K Public Sub y() End Sub Public x As Integer Class Z Public Sub yy() End Sub Public xx As Integer Public Shared Sub goo() Dim v As Integer Dim zInstance As Z zInstance = Nothing y() v = x yy() v = xx zInstance.yy() v = zInstance.xx Z.yy() v = Z.xx End Sub End Class End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30469: Reference to a non-shared member requires an object reference. y() ~ BC30469: Reference to a non-shared member requires an object reference. v = x ~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. yy() ~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. v = xx ~~ BC30469: Reference to a non-shared member requires an object reference. Z.yy() ~~~~ BC30469: Reference to a non-shared member requires an object reference. v = Z.xx ~~~~ </expected>) End Sub ' Test access to static member in various ways to get various errors. <Fact> Public Sub AccessStaticViaInstance() Dim compilation = CreateCompilationWithMscorlib40( <compilation name="AccessStaticViaInstance"> <file name="a.vb"> Class K Public Shared Sub y() End Sub Public Shared x As Integer Class Z Public Shared Sub yy() End Sub Public Shared xx As Integer Public Sub goo() Dim v As Integer Dim zInstance As Z zInstance = Nothing y() v = x yy() v = xx zInstance.yy() v = zInstance.xx Z.yy() v = Z.xx End Sub End Class End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. zInstance.yy() ~~~~~~~~~~~~ BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated. v = zInstance.xx ~~~~~~~~~~~~ </expected>) End Sub <Fact(), WorkItem(531587, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531587")> Public Sub CircularSharedMemberAccessThroughInstance() Dim source = <compilation name="FieldsConst"> <file name="a.vb"> Option Strict On Option Infer On Class C1 Const i As Integer = j.MaxValue Const j As Integer = i.MaxValue Public shared Sub Main(args() as string) End sub End Class </file> </compilation> Dim c1 = CreateCompilationWithMscorlib40AndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "j.MaxValue"), Diagnostic(ERRID.WRN_SharedMemberThroughInstance, "i.MaxValue")) End Sub <Fact> Public Sub ConstantFields1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="VBConstantFields1"> <file name="a.vb"> Module Module1 Sub Main() System.Console.WriteLine("Int64Field: {0}", ConstFields.Int64Field) System.Console.WriteLine("DateTimeField: {0}", ConstFields.DateTimeField.ToString("M/d/yyyy h:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture)) System.Console.WriteLine("DoubleField: {0}", ConstFields.DoubleField) System.Console.WriteLine("SingleField: {0}", ConstFields.SingleField) System.Console.WriteLine("StringField: {0}", ConstFields.StringField) System.Console.WriteLine("StringNullField: [{0}]", ConstFields.StringNullField) System.Console.WriteLine("ObjectNullField: [{0}]", ConstFields.ObjectNullField) System.Console.WriteLine("ByteValue: {0}", ByteEnum.ByteValue) System.Console.WriteLine("SByteValue: {0}", SByteEnum.SByteValue) System.Console.WriteLine("UInt16Value: {0}", UInt16Enum.UInt16Value) System.Console.WriteLine("Int16Value: {0}", Int16Enum.Int16Value) System.Console.WriteLine("UInt32Value: {0}", UInt32Enum.UInt32Value) System.Console.WriteLine("Int32Value: {0}", Int32Enum.Int32Value) System.Console.WriteLine("UInt64Value: {0}", UInt64Enum.UInt64Value) System.Console.WriteLine("Int64Value: {0}", Int64Enum.Int64Value) End Sub End Module </file> </compilation>, TestOptions.ReleaseExe) compilation = compilation.AddReferences(TestReferences.SymbolsTests.Fields.ConstantFields) CompileAndVerify(compilation, <![CDATA[ Int64Field: 634315546432909307 DateTimeField: 1/25/2011 12:17:23 PM DoubleField: -10 SingleField: 9 StringField: 11 StringNullField: [] ObjectNullField: [] ByteValue: ByteValue SByteValue: SByteValue UInt16Value: UInt16Value Int16Value: Int16Value UInt32Value: UInt32Value Int32Value: Int32Value UInt64Value: UInt64Value Int64Value: Int64Value ]]>) End Sub ' Test member of built in type. <Fact> Public Sub MemberOfBuiltInType() CompileAndVerify( <compilation name="MeReference"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x as Integer x = Integer.Parse("143") Console.WriteLine(x) End Sub End Module </file> </compilation>, expectedOutput:="143") End Sub ' Test member of nullable type. <Fact> Public Sub MemberOfNullableType() CompileAndVerify( <compilation name="MeReference"> <file name="a.vb"> Imports System Module M1 Sub Main() Dim x as boolean x = Integer?.Equals("goo", "g" + "oo") Console.WriteLine(x) End Sub End Module </file> </compilation>, expectedOutput:="True") End Sub <Fact> Public Sub Bug4272() Dim compilationDef = <compilation name="Bug4272"> <file name="a.vb"> Option Strict On Module M Function Goo(x As Integer) As Integer() Goo(1) = Nothing End Function End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC30068: Expression is a value and therefore cannot be the target of an assignment. Goo(1) = Nothing ~~~~~~ BC42105: Function 'Goo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </expected>) compilationDef = <compilation name="Bug4272"> <file name="a.vb"> Module Module1 Sub Main() Goo() End Sub Private val As TestClass Function Goo() As TestClass If val Is Nothing Then System.Console.WriteLine("Nothing") val = New TestClass() val.Field = 2 Else System.Console.WriteLine("val") Return val End If Dim x As TestClass = New TestClass() x.Field = 1 Goo = x System.Console.WriteLine(Goo.Field) System.Console.WriteLine(Goo.GetField()) System.Console.WriteLine(Goo().Field) System.Console.WriteLine(Goo(3)) End Function Function Goo(x As Integer) As Integer Return x End Function End Module Class TestClass Public Field As Integer Public Function GetField() As Integer Return Field End Function End Class </file> </compilation> compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ Nothing 1 1 val 2 3 ]]>) compilationDef = <compilation name="Bug4272"> <file name="a.vb"> Option Strict On Module M Function Goo(x As Integer) As Integer() Dim y As Integer() = Goo(1) End Function End Module Module M1 Function Goo(x As Object) As Integer Return Goo(1) End Function Function Goo(x As Integer) As Integer Return 1 End Function End Module </file> </compilation> compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC42105: Function 'Goo' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function ~~~~~~~~~~~~ </expected>) End Sub <WorkItem(538802, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538802")> <Fact> Public Sub MethodAccessibilityChecking() CompileAndVerify( <compilation name="MeReference"> <file name="a.vb"> Imports System Public Class C1 Private Shared Sub goo(x as String) Console.Writeline("Private") End Sub Public Shared Sub goo(x as Object) Console.Writeline("Public") End Sub End class Module Program Sub Main() 'Below call should bind to public overload that takes object c1.goo("") End Sub End Module </file> </compilation>, expectedOutput:="Public") End Sub <Fact> Public Sub Bug4249() Dim compilationDef = <compilation name="Bug4249"> <file name="a.vb"> Module Program Sub Main() Main().ToString End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC30491: Expression does not produce a value. Main().ToString ~~~~~~ </expected>) End Sub <Fact> Public Sub Bug4250() Dim compilationDef = <compilation name="Bug4250"> <file name="a.vb"> Module Program Sub Main() System.Console.WriteLine(Goo.ToString) System.Console.WriteLine(Bar(Of Integer).ToString) End Sub Function Goo() as Integer return 123 End Function Function Bar(Of T)() as Integer return 231 End Function End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompileAndVerify(compilation, <![CDATA[ 123 231 ]]>) compilationDef = <compilation name="Bug4250"> <file name="a.vb"> Module Program Sub Main() System.Console.WriteLine(Goo.ToString) End Sub Function Goo(x as Integer) as Integer return 321 End Function End Module </file> </compilation> compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef, TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'x' of 'Public Function Goo(x As Integer) As Integer'. System.Console.WriteLine(Goo.ToString) ~~~ </expected>) End Sub <Fact> Public Sub Bug4277() Dim compilationDef = <compilation name="Bug4277"> <file name="a.vb"> Option Strict Off Module M Sub Main() End Sub End Module Class B Sub T() End Sub End Class Class A(Of T) Inherits B Sub Goo() T() End Sub End Class Class C Sub S() End Sub Class A(Of S) Sub Goo() S() End Sub End Class End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC30108: 'S' is a type and cannot be used as an expression. S() ~ </expected>) End Sub <WorkItem(538438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538438")> <Fact> Public Sub TestRangeExpressionAllowableLowerBounds() Dim compilationDef = <compilation name="TestRangeExpressionAllowableLowerBounds"> <file name="a.vb"> Friend Module ExpArrBounds0LowerBound Sub ExpArrBounds0LowerBound() Dim x0(0 To 2&amp;) Dim x1(0&amp; To 2&amp;) Dim x2(0ul To 2&amp;) Dim x3(0l To 2&amp;) Dim x4(0us To 2&amp;) Dim x5(0s To 2&amp;) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) End Sub <WorkItem(537219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537219")> <Fact> Public Sub BC32059ERR_OnlyNullLowerBound() Dim compilationDef = <compilation name="BC32059ERR_OnlyNullLowerBound"> <file name="a.b"> Friend Module ExpArrBounds003Errmod Sub ExpArrBounds003Err() ' COMPILEERROR: BC32059, "0!" Dim x1(0! To 5) as Single Dim x2(0.0 to 5) as Single Dim x3(0d to 5) as Single End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <errors> BC32059: Array lower bounds can be only '0'. Dim x1(0! To 5) as Single ~~ BC32059: Array lower bounds can be only '0'. Dim x2(0.0 to 5) as Single ~~~ BC32059: Array lower bounds can be only '0'. Dim x3(0d to 5) as Single ~~ </errors>) End Sub <Fact> Public Sub LocalShadowsGenericMethod() Dim compilationDef = <compilation name="LocalShadowsGenericMethod"> <file name="a.vb"> Class Y Sub f() Dim goo As Integer goo(Of Integer)() End Sub Public Sub goo(Of T)() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <errors> BC42024: Unused local variable: 'goo'. Dim goo As Integer ~~~ BC32045: 'goo' has no type parameters and so cannot have type arguments. goo(Of Integer)() ~~~~~~~~~~~~ </errors>) End Sub <Fact> Public Sub AccessingMemberOffOfNothing() Dim compilationDef = <compilation name="AccessingMemberOffOfNothing"> <file name="a.vb"> Class Y Sub f() Dim x As System.Type = Nothing.GetType() End Sub End Class </file> </compilation> CompileAndVerify(compilationDef). VerifyIL("Y.f", <![CDATA[ { // Code size 8 (0x8) .maxstack 1 IL_0000: ldnull IL_0001: callvirt "Function Object.GetType() As System.Type" IL_0006: pop IL_0007: ret } ]]>) End Sub <Fact> Public Sub ColorColor() Dim compilationDef = <compilation name="AccessingMemberOffOfNothing"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub main() Dim o As New cls1 End Sub End Module Class cls1 Public Const s As Integer = 123 Shared o As Integer = cls1.s Public ReadOnly Property cls1 As cls1 Get Console.WriteLine("hi") Return Me End Get End Property Sub New() ' cls1 is a type here, no warnings needed, but colorizer should show it as a type cls1.s.ToString() End Sub Shared Sub moo() Console.WriteLine(cls1.s) End Sub End Class Class Color Public Shared Red As Color = Nothing Public Shared Property Green As Color Public Class TypeInColor Public shared c as Color End Class Public Class GenericTypeInColor Public shared c as Color End Class Public Class GenericTypeInColor(of T) Public shared c as Color End Class End Class Class Test ReadOnly Property Color() As Color Get Return Color.Red End Get End Property Shared Function DefaultColor() As Color Dim c as Color = Color.Green ' Binds to the instance property! c= Color.TypeInColor.c c= Color.GenericTypeInColor.c c= Color.GenericTypeInColor(of UShort).c return c End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) End Sub <Fact> Public Sub FalseColorColor() Dim compilationDef = <compilation name="AccessingMemberOffOfNothing"> <file name="a.vb"> Imports Q = B Class B Public Shared Zip As Integer Public ReadOnly Property Q As B Get Return Nothing End Get End Property Shared Sub f() Dim x As Integer = Q.Zip 'this should be an error End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <errors> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Dim x As Integer = Q.Zip 'this should be an error ~ </errors>) End Sub <Fact> Public Sub ColorColor1() Dim compilationDef = <compilation name="AccessingMemberOffOfNothing"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub main() Test.DefaultColor() End Sub End Module Class Color Public Shared Red As Color = Nothing Public Shared Function G(Of T)(x As T) As Color Return Red End Function End Class Class Test ReadOnly Property color(x as integer) As Color Get Console.WriteLine("evaluated") Return Color.Red End Get End Property Shared Function DefaultColor() As Color dim a = color.G(1) ' error, missing parameter to color property Return color.G(of Long)(1) ' error, missing parameter to color property End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'. dim a = color.G(1) ' error, missing parameter to color property ~~~~~ BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property color(x As Integer) As Color'. Return color.G(of Long)(1) ' error, missing parameter to color property ~~~~~ </expected>) End Sub <Fact> Public Sub ColorColor2() Dim compilationDef = <compilation name="AccessingMemberOffOfNothing"> <file name="a.vb"> Option Strict On Imports System Module Module1 Sub main() Test.DefaultColor() End Sub End Module Class Color Public Shared Red As Color = Nothing Public Shared Function G(Of T)(x As T) As Color Return Red End Function End Class Class Test ReadOnly Property color() As Color Get Console.WriteLine("evaluated") Return Color.Red End Get End Property Shared Function DefaultColor() As Color Return color.G(1) ' Binds to the type Return color.G(of Long)(1) ' Binds to the type End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) End Sub <Fact> Public Sub ColorColorOverloaded() Dim compilationDef = <compilation name="ColorColorOverloaded"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o as Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color() As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color c1 = Color.G(1) ' Binds to the type c1 = Color.G() ' Binds to the member Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) CompileAndVerify(compilationDef, expectedOutput:="evaluated"). VerifyIL("Module1.Test.DefaultColor", <![CDATA[ { // Code size 19 (0x13) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color" IL_0006: pop IL_0007: ldarg.0 IL_0008: call "Function Module1.Test.get_Color() As Module1.Color" IL_000d: callvirt "Function Module1.Color.G() As Module1.Color" IL_0012: ret } ]]>) End Sub <Fact()> Public Sub ColorColorOverloadedOptional() Dim compilationDef = <compilation name="ColorColorOverloaded"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o as Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color(optional x as integer = 1) As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color c1 = Color.G(1) ' Binds to the type c1 = Color.G() ' Binds to the member Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) CompileAndVerify(compilationDef, expectedOutput:="evaluated"). VerifyIL("Module1.Test.DefaultColor", <![CDATA[ { // Code size 20 (0x14) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color" IL_0006: pop IL_0007: ldarg.0 IL_0008: ldc.i4.1 IL_0009: call "Function Module1.Test.get_Color(Integer) As Module1.Color" IL_000e: callvirt "Function Module1.Color.G() As Module1.Color" IL_0013: ret } ]]>) End Sub <Fact> Public Sub ColorColorOverloadedErr() Dim compilationDef = <compilation name="ColorColorOverloaded"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o as Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color(x as integer) As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color c1 = Color.G(1) ' missing parameter x c1 = Color.G() ' missing parameter x Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <errors> BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'. c1 = Color.G(1) ' missing parameter x ~~~~~ BC30455: Argument not specified for parameter 'x' of 'Public ReadOnly Property Color(x As Integer) As Module1.Color'. c1 = Color.G() ' missing parameter x ~~~~~ </errors>) End Sub <Fact> Public Sub ColorColorOverloadedErr2() Dim compilationDef = <compilation name="ColorColorOverloaded"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o as Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color c1 = Color.G(1) ' Binds to the type c1 = Color.G() ' Binds to the member Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoDiagnostics(compilation) End Sub <Fact> Public Sub ColorColorOverloadedAddressOf() Dim compilationDef = <compilation name="ColorColorOverloadedAddressOf"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o as Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color() As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color Dim d1 As Func(Of Integer, Color) = AddressOf Color.G ' Binds to the type c1 = d1(1) Dim d2 As Func(Of Color) = AddressOf Color.G ' Binds to the member c1 = d2() Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) CompileAndVerify(compilationDef, expectedOutput:="evaluated"). VerifyIL("Module1.Test.DefaultColor", <![CDATA[ { // Code size 42 (0x2a) .maxstack 2 IL_0000: ldnull IL_0001: ldftn "Function Module1.Color.G(Integer) As Module1.Color" IL_0007: newobj "Sub System.Func(Of Integer, Module1.Color)..ctor(Object, System.IntPtr)" IL_000c: ldc.i4.1 IL_000d: callvirt "Function System.Func(Of Integer, Module1.Color).Invoke(Integer) As Module1.Color" IL_0012: pop IL_0013: ldarg.0 IL_0014: call "Function Module1.Test.get_Color() As Module1.Color" IL_0019: ldftn "Function Module1.Color.G() As Module1.Color" IL_001f: newobj "Sub System.Func(Of Module1.Color)..ctor(Object, System.IntPtr)" IL_0024: callvirt "Function System.Func(Of Module1.Color).Invoke() As Module1.Color" IL_0029: ret } ]]>) End Sub <Fact> Public Sub ColorColorOverloadedAddressOfRelaxed() Dim compilationDef = <compilation name="ColorColorOverloadedAddressOfRelaxed"> <file name="a.vb"> Option Strict On Imports System Module Module1 Public Sub Main() Dim o As Test = New Test o.DefaultColor() End Sub Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function Public Function G() As Color Return Red End Function End Class Class Test ReadOnly Property Color() As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Sub DefaultColor() Dim d1 As Action(Of Integer) = AddressOf Color.G ' Binds to the type d1(1) Dim d2 As Action = AddressOf Color.G ' Binds to the member d2() End Sub End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) CompileAndVerify(compilationDef, expectedOutput:="evaluated"). VerifyIL("Module1.Test.DefaultColor", <![CDATA[ { // Code size 76 (0x4c) .maxstack 3 IL_0000: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)" IL_000c: br.s IL_0024 IL_000e: ldsfld "Module1.Test._Closure$__.$I As Module1.Test._Closure$__" IL_0013: ldftn "Sub Module1.Test._Closure$__._Lambda$__R3-2(Integer)" IL_0019: newobj "Sub System.Action(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Module1.Test._Closure$__.$IR3-2 As System.Action(Of Integer)" IL_0024: ldc.i4.1 IL_0025: callvirt "Sub System.Action(Of Integer).Invoke(Integer)" IL_002a: newobj "Sub Module1.Test._Closure$__R3-0..ctor()" IL_002f: dup IL_0030: ldarg.0 IL_0031: call "Function Module1.Test.get_Color() As Module1.Color" IL_0036: stfld "Module1.Test._Closure$__R3-0.$VB$NonLocal_2 As Module1.Color" IL_003b: ldftn "Sub Module1.Test._Closure$__R3-0._Lambda$__R3()" IL_0041: newobj "Sub System.Action..ctor(Object, System.IntPtr)" IL_0046: callvirt "Sub System.Action.Invoke()" IL_004b: ret } ]]>) End Sub <Fact> Public Sub ColorColorExtension() Dim compilationDef = <compilation name="ColorColorOverloaded"> <file name="a.vb"> Option Strict On Imports System Imports System.Runtime.CompilerServices Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace Module Module1 Public Sub Main() Dim o As Test = New Test o.DefaultColor() End Sub Structure S1 End Structure &lt;Extension()&gt; Public Function G(this As Color) As Color Return Color.Red End Function Class Color Public Shared Red As Color = New Color Public Shared Function G(x As Integer) As Color Return Red End Function End Class Class Test Shared ReadOnly Property Color() As Color Get Console.Write("evaluated") Return Color.Red End Get End Property Function DefaultColor() As Color Dim c1 As Color c1 = Color.G(1) ' Binds to the type c1 = Color.G() ' Binds to the member + extension Return c1 End Function End Class End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoErrors(compilation) CompileAndVerify(compilationDef, expectedOutput:="evaluated"). VerifyIL("Module1.Test.DefaultColor", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.1 IL_0001: call "Function Module1.Color.G(Integer) As Module1.Color" IL_0006: pop IL_0007: call "Function Module1.Test.get_Color() As Module1.Color" IL_000c: call "Function Module1.G(Module1.Color) As Module1.Color" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub ColorColorAlias() Dim compilationDef = <compilation name="ColorColorAlias"> <file name="a.vb"> Option Strict On Imports System Imports Bar = NS1.Bar Module Module1 Public Sub Main() Dim o as Goo = New Goo() Console.WriteLine(o.M()) End Sub End Module Namespace NS1 Public Class Bar Public Shared c as Integer = 48 End Class End Namespace Class Goo ReadOnly Property Bar As Bar Get Console.WriteLine("property called") Return Nothing End Get End Property Function M() As Integer return Bar.c End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertNoDiagnostics(compilation) CompileAndVerify(compilationDef, expectedOutput:="48"). VerifyIL("Goo.M", <![CDATA[ { // Code size 6 (0x6) .maxstack 1 IL_0000: ldsfld "NS1.Bar.c As Integer" IL_0005: ret } ]]>) End Sub <Fact()> Public Sub ColorColorWrongAlias() Dim compilationDef = <compilation name="ColorColorWrongAlias"> <file name="a.vb"> Option Strict On Imports System Imports Bar2 = NS1.Bar Module Module1 Public Sub Main() Dim o As Goo = New Goo() Console.WriteLine(Goo.M()) End Sub End Module Namespace NS1 Public Class Bar Public Shared c As Integer = 48 End Class End Namespace Class Goo ReadOnly Property Bar2 As Bar2 Get Console.WriteLine("property called") Return Nothing End Get End Property Public Shared Function M() As Integer Return Bar2.c End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) AssertTheseDiagnostics(compilation, <expected> BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. Return Bar2.c ~~~~ </expected>) End Sub <Fact> Public Sub ModulesWhereTypesShouldBe() Dim text = <compilation name="ModulesWhereTypesShouldBe"> <file name="a.vb"> Module M Sub GG() Dim y As System.Collections.Generic.List(Of M) Dim z As Object = Nothing Dim q = TryCast(z, M) Dim p = CType(z, M) Dim r As M() End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text) AssertTheseDiagnostics(compilation, <errors> BC42024: Unused local variable: 'y'. Dim y As System.Collections.Generic.List(Of M) ~ BC30371: Module 'M' cannot be used as a type. Dim y As System.Collections.Generic.List(Of M) ~ BC30371: Module 'M' cannot be used as a type. Dim q = TryCast(z, M) ~ BC30371: Module 'M' cannot be used as a type. Dim p = CType(z, M) ~ BC42024: Unused local variable: 'r'. Dim r As M() ~ BC30371: Module 'M' cannot be used as a type. Dim r As M() ~ </errors>) End Sub <Fact> Public Sub GetTypeOnNSAlias() Dim text = <compilation name="GetTypeOnNSAlias"> <file name="a.vb"> Imports NS=System.Collections Module M Sub S() Dim x = GetType(NS) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text) AssertTheseDiagnostics(compilation, <errors> BC30182: Type expected. Dim x = GetType(NS) ~~ </errors>) End Sub <WorkItem(542383, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542383")> <Fact> Public Sub GetTypeOnModuleName() Dim text = <compilation name="GetTypeForModuleName"> <file name="a.vb"> Imports System Namespace AttrUseCust011 Friend Module AttrUseCust011mod Sub GG() Dim x = GetType(AttrUseCust011mod) End Sub End Module End Namespace </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text) AssertNoErrors(compilation) End Sub <Fact> Public Sub GetTypeOnAlias() Dim text = <compilation name="GetTypeOnAlias"> <file name="a.vb"> Imports System Imports Con = System.Console Module M Sub GG() Dim x = GetType(Con) End Sub End Module </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(text) AssertNoErrors(compilation) End Sub <Fact> Public Sub Bug9300_1() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Collections Imports System Module M Sub Main() Goo(Sub(x) x.New()) End Sub Sub Goo(x As Action(Of Object())) System.Console.WriteLine("Action(Of Object())") x(New Object() {}) End Sub &lt;Extension()&gt; Sub [New](Of T)(ByVal x As T) System.Console.WriteLine("[New]") End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30251: Type 'Object()' has no constructors. Goo(Sub(x) x.New()) ~~~~~ </errors> AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub Bug9300_2() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Collections Imports System Module M Sub Main() Goo(Sub(x) x.New()) End Sub Class TC1 End Class Sub Goo(x As Action(Of TC1)) End Sub &lt;Extension()&gt; Sub [New](Of T)(ByVal x As T) System.Console.WriteLine("[New]") End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>) Dim expectedErrors1 = <errors> BC30282: Constructor call is valid only as the first statement in an instance constructor. Goo(Sub(x) x.New()) ~~~~~ </errors> AssertTheseDiagnostics(compilation1, expectedErrors1) End Sub <Fact> Public Sub Bug9300_3() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="NotYetImplementedInRoslyn"> <file name="a.vb"> Imports System.Runtime.CompilerServices Imports System.Collections Imports System Module M Sub Main() Goo(Sub(x) x.New()) End Sub Sub Goo(x As Action(Of IEnumerable)) System.Console.WriteLine("Action(Of IEnumerable)") x(New Object() {}) End Sub Sub Goo(x As Action(Of Object())) System.Console.WriteLine("Action(Of Object())") x(New Object() {}) End Sub &lt;Extension()&gt; Sub [New](Of T)(ByVal x As T) System.Console.WriteLine("[New]") End Sub End Module Namespace System.Runtime.CompilerServices &lt;AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)&gt; Class ExtensionAttribute Inherits Attribute End Class End Namespace </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation1, <![CDATA[ Action(Of IEnumerable) [New] ]]>) End Sub <Fact> Public Sub IllegalTypeExpressionsFromParserShouldNotBlowUpBinding() Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="IllegalTypeExpressionsFromParserShouldNotBlowUpBinding"> <file name="a.vb"> Class Outer(Of T) Public Shared Sub Print() System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected. System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected. End Sub Class Inner(Of U) End Class End Class </file> </compilation>) AssertTheseDiagnostics(compilation1, <expected> BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of ).Inner(Of T))) ' BC32099: Comma or ')' expected. ~ BC32099: Comma or ')' expected. System.Console.WriteLine(GetType(Outer(Of ).Inner(Of Integer))) ' BC32099: Comma or ')' expected. ~~~~~~~ BC30182: Type expected. System.Console.WriteLine(GetType(Outer(Of T).Inner(Of ))) ' BC30182: Type expected. ~ BC30182: Type expected. System.Console.WriteLine(GetType(Outer(Of Integer).Inner(Of ))) ' BC30182: Type expected. ~ </expected>) End Sub <Fact()> Public Sub Bug10335_1() Dim source1_with = <compilation name="Unavailable"> <file name="a.vb"> Public Interface IUnavailable ReadOnly Default Property Item(p as Integer) as Integer End Interface </file> </compilation> Dim c1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_with) Dim baseBuffer = CompileAndVerify(c1).EmittedAssemblyData Dim source2 = <compilation> <file name="a.vb"> Public Class Class1 Implements IUnavailable Public Default ReadOnly Property Item(p as Integer) as Integer implements IUnavailable.Item Get Return p End Get End Property End Class Public Class Class2 Public ReadOnly Property AProperty() as Class1 Get Return new Class1() End Get End Property End Class </file> </compilation> Dim c2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {MetadataReference.CreateFromImage(baseBuffer)}) Dim derivedBuffer = CompileAndVerify(c2).EmittedAssemblyData Dim source3 = <compilation> <file name="a.vb"> Module M1 Sub Main() Dim x as new Class2() dim y = x.AProperty(23) Dim z as Object = x.AProperty() x.AProperty() End Sub End Module </file> </compilation> Dim source1_without = <compilation name="Unavailable"> <file name="a.vb"> Class Unused End Class </file> </compilation> Dim c1_without = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source1_without) Dim image = CompileAndVerify(c1_without).EmittedAssemblyData Dim c3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {MetadataReference.CreateFromImage(derivedBuffer), MetadataReference.CreateFromImage(image)}) AssertTheseDiagnostics(c3, <expected> BC30545: Property access must assign to the property or use its value. x.AProperty() ~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ColorColorOverriddenProperty() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug12687"> <file name="a.vb"> Class TypeSubstitution Shared Function Create() As Integer Return 1 End Function End Class Class InstanceTypeSymbol ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution Get Return Nothing End Get End Property End Class Class Frame Inherits InstanceTypeSymbol Overloads ReadOnly Property TypeSubstitution As TypeSubstitution Get Return Nothing End Get End Property Function Goo() As Integer Return TypeSubstitution.Create() End Function End Class </file> </compilation>) AssertNoDiagnostics(compilation) End Sub <Fact> Public Sub ColorColorPropertyWithParam() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug12687"> <file name="a.vb"> Class TypeSubstitution Shared Function Create() As Integer Return 1 End Function End Class Class InstanceTypeSymbol Overridable ReadOnly Property TypeSubstitution(a as Integer) As TypeSubstitution Get Return Nothing End Get End Property End Class Class Frame Inherits InstanceTypeSymbol Function Goo() As Integer Return TypeSubstitution.Create() End Function End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'a' of 'Public Overridable ReadOnly Property TypeSubstitution(a As Integer) As TypeSubstitution'. Return TypeSubstitution.Create() ~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ColorColorPropertyWithOverloading() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="Bug12687"> <file name="a.vb"> Class TypeSubstitution Shared Function Create() As Integer Return 1 End Function End Class Class InstanceTypeSymbol ReadOnly Property TypeSubstitution(a as Integer) As String Get Return Nothing End Get End Property ReadOnly Property TypeSubstitution As TypeSubstitution Get Return Nothing End Get End Property End Class Class Frame Inherits InstanceTypeSymbol Function Goo() As Integer Return TypeSubstitution.Create() End Function End Class </file> </compilation>) AssertNoDiagnostics(compilation) End Sub ' Tests IsValidAssignmentTarget for PropertyAccess ' and IsLValueFieldAccess for FieldAccess. <Fact> Public Sub IsValidAssignmentTarget() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Structure S Public F As Object Public Property P As Object Sub M() Me.F = Nothing ' IsLValue = False, IsMeReference = True MyClass.F = Nothing ' IsLValue = False, IsMyClassReference = True Me.P = Nothing ' IsLValue = False, IsMeReference = True MyClass.P = Nothing ' IsLValue = False, IsMyClassReference = True End Sub End Structure Class C Private F1 As S Private ReadOnly F2 As S Sub M() F1.F = Nothing ' IsLValue = True F2.F = Nothing ' IsLValue = False F1.P = Nothing ' IsLValue = True F2.P = Nothing ' IsLValue = False End Sub End Class </file> </compilation>) compilation.AssertTheseDiagnostics(<expected> BC30064: 'ReadOnly' variable cannot be the target of an assignment. F2.F = Nothing ' IsLValue = False ~~~~ BC30068: Expression is a value and therefore cannot be the target of an assignment. F2.P = Nothing ' IsLValue = False ~~~~ </expected>) End Sub <Fact> Public Sub Bug12900() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation name="MemberAccessNoContainingWith"> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const local _? As Integer End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30438: Constants must have a value. Const local _? As Integer ~~~~~ BC30203: Identifier expected. Const local _? As Integer ~ </expected>) End Sub <Fact> Public Sub Bug13080() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Program Sub Main(args As String()) Const ' End Sub End Module </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30203: Identifier expected. Const ' ~ BC30438: Constants must have a value. Const ' ~ </expected>) End Sub <WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")> <Fact> Public Sub GetTypeAllowsArrayOfModules() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Imports VoidAlias = System.Void Namespace Bar Module Test Sub Main() ' Array of types Dim x As Type = GetType(Test()) 'ok x = GetType(Void()) ' error ' types direct x = GetType(Test) ' ok x = GetType(Void) ' ok ' nullable x = GetType(Test?) ' error x = GetType(Void?) ' error x = GetType(List(Of Test)) ' error x = GetType(List(Of Void)) ' error x = GetType(Bar.Test) ' ok x = GetType(System.Void) ' ok x = GetType(VoidAlias) ' ok End Sub End Module End Namespace </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC31428: Arrays of type 'System.Void' are not allowed in this expression. x = GetType(Void()) ' error ~~~~~~ BC30371: Module 'Test' cannot be used as a type. x = GetType(Test?) ' error ~~~~ BC33101: Type 'Test' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'. x = GetType(Test?) ' error ~~~~ BC31422: 'System.Void' can only be used in a GetType expression. x = GetType(Void?) ' error ~~~~ BC30371: Module 'Test' cannot be used as a type. x = GetType(List(Of Test)) ' error ~~~~ BC31422: 'System.Void' can only be used in a GetType expression. x = GetType(List(Of Void)) ' error ~~~~ </expected>) End Sub <WorkItem(530438, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530438")> <WorkItem(546469, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546469")> <Fact()> Public Sub GetTypeAllowsModuleAlias() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports ModuleAlias = Bar.Test Imports System Namespace Bar Module Test Sub Main() Dim x As Type = GetType(ModuleAlias) ' ok End Sub End Module End Namespace </file> </compilation>) AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub RangeVariableColorColor() Dim source = _ <compilation> <file name="a.vb"> Imports System.Linq Class Program Shared Sub Main() Dim q = From X As X In New X() { New X() } Where X.S() Where X.I() Select 42 System.Console.Write(q.Single()) End Sub End Class Class X Public Shared Function S() As Boolean Return True End Function Public Shared Function I() As Boolean Return True End Function End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {SystemCoreRef}, options:=TestOptions.ReleaseExe) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub <WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")> <Fact()> Public Sub Bug1108036() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Color Public Shared Sub Cat() End Sub End Class Class Program Shared Sub Main() Color.Cat() End Sub ReadOnly Property Color(Optional x As Integer = 0) As Color Get Return Nothing End Get End Property ReadOnly Property Color(Optional x As String = "") As Integer Get Return 0 End Get End Property End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments: 'Public ReadOnly Property Color([x As Integer = 0]) As Color': Not most specific. 'Public ReadOnly Property Color([x As String = ""]) As Integer': Not most specific. Color.Cat() ~~~~~ </expected>) End Sub <WorkItem(1108036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108036")> <Fact()> Public Sub Bug1108036_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Color Public Shared Sub Cat() End Sub End Class Class Program Shared Sub Main() Color.Cat() End Sub ReadOnly Property Color(Optional x As Integer = 0) As Integer Get Return 0 End Get End Property ReadOnly Property Color(Optional x As String = "") As Color Get Return Nothing End Get End Property End Class </file> </compilation>) AssertTheseDiagnostics(compilation, <expected> BC30521: Overload resolution failed because no accessible 'Color' is most specific for these arguments: 'Public ReadOnly Property Color([x As Integer = 0]) As Integer': Not most specific. 'Public ReadOnly Property Color([x As String = ""]) As Color': Not most specific. Color.Cat() ~~~~~ </expected>) End Sub <WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")> <Fact()> Public Sub Bug969006_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Enum E A End Enum Class C Sub M() Const e As E = E.A Dim z = e End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model1 = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single() Assert.Equal("E.A", node1.ToString()) Assert.Equal("E", node1.Expression.ToString()) Dim symbolInfo = model1.GetSymbolInfo(node1.Expression) Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind) Dim model2 = compilation.GetSemanticModel(tree) Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single() Assert.Equal("= e", node2.Parent.ToString()) symbolInfo = model2.GetSymbolInfo(node2) Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString()) symbolInfo = model2.GetSymbolInfo(node1.Expression) Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind) AssertTheseDiagnostics(compilation) End Sub <WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")> <Fact()> Public Sub Bug969006_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Enum E A End Enum Class C Sub M() Dim e As E = E.A Dim z = e End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model1 = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single() Assert.Equal("E.A", node1.ToString()) Assert.Equal("E", node1.Expression.ToString()) Dim symbolInfo = model1.GetSymbolInfo(node1.Expression) Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind) Dim model2 = compilation.GetSemanticModel(tree) Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single() Assert.Equal("= e", node2.Parent.ToString()) symbolInfo = model2.GetSymbolInfo(node2) Assert.Equal("e As E", symbolInfo.Symbol.ToTestDisplayString()) symbolInfo = model2.GetSymbolInfo(node1.Expression) Assert.Equal("E", symbolInfo.Symbol.ToTestDisplayString()) Assert.Equal(SymbolKind.NamedType, symbolInfo.Symbol.Kind) AssertTheseDiagnostics(compilation) End Sub <WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")> <Fact()> Public Sub Bug969006_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Enum E A End Enum Class C Sub M() Const e = E.A Dim z = e End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model1 = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single() Assert.Equal("E.A", node1.ToString()) Assert.Equal("E", node1.Expression.ToString()) Dim symbolInfo = model1.GetSymbolInfo(node1.Expression) Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString()) Dim model2 = compilation.GetSemanticModel(tree) Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single() Assert.Equal("= e", node2.Parent.ToString()) symbolInfo = model2.GetSymbolInfo(node2) Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString()) symbolInfo = model2.GetSymbolInfo(node1.Expression) Assert.Equal("e As System.Object", symbolInfo.Symbol.ToTestDisplayString()) AssertTheseDiagnostics(compilation, <expected> BC30500: Constant 'e' cannot depend on its own value. Const e = E.A ~ BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime. Const e = E.A ~ </expected>) End Sub <WorkItem(969006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/969006")> <Fact()> Public Sub Bug969006_4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Enum E A End Enum Class C Sub M() Dim e = E.A Dim z = e End Sub End Class </file> </compilation>) Dim tree = compilation.SyntaxTrees(0) Dim model1 = compilation.GetSemanticModel(tree) Dim node1 = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Single() Assert.Equal("E.A", node1.ToString()) Assert.Equal("E", node1.Expression.ToString()) Dim symbolInfo = model1.GetSymbolInfo(node1.Expression) Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString()) Dim model2 = compilation.GetSemanticModel(tree) Dim node2 = tree.GetRoot().DescendantNodes.OfType(Of IdentifierNameSyntax)().Where(Function(n) n.Identifier.ValueText = "e").Single() Assert.Equal("= e", node2.Parent.ToString()) symbolInfo = model2.GetSymbolInfo(node2) Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString()) symbolInfo = model2.GetSymbolInfo(node1.Expression) Assert.Equal("e As ?", symbolInfo.Symbol.ToTestDisplayString()) AssertTheseDiagnostics(compilation, <expected> BC30980: Type of 'e' cannot be inferred from an expression containing 'e'. Dim e = E.A ~ BC42104: Variable 'e' is used before it has been assigned a value. A null reference exception could result at runtime. Dim e = E.A ~ </expected>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_1() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Color Public Shared Sub M(x As Integer) System.Console.WriteLine(x) End Sub Public Sub M(x As String) End Sub End Class Class Program Dim Color As Color Shared Sub Main() Dim x As Object = 42 Color.M(x) End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact> Public Sub Bug1108007_2() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Sub M(x As Integer) Console.WriteLine(x) End Sub Public Sub M(x As String) End Sub End Class Class Program Dim Color As Color Shared Sub Main() Try Dim x As Object = "" Color.M(x) Catch e As Exception Console.WriteLine(e.GetType()) End Try End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_3() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Class MyAttribute Inherits System.Attribute Public ReadOnly I As Integer Public Sub New(i As Integer) Me.I = i End Sub End Class Class Color Public Const I As Integer = 42 End Class Class Program Dim Color As Color <MyAttribute(Color.I)> Shared Sub Main() End Sub End Class ]]> </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_4() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Sub M(x As Integer) Console.WriteLine(x) End Sub Public Sub M(x As String) End Sub Class Program Dim Color As Color Sub M() Try Dim x As Object = "" Color.M(x) Catch e As Exception Console.WriteLine(e.GetType()) End Try End Sub Shared Sub Main() Dim p = New Program() p.M() End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.Field, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_5() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Function M(x As Integer) As Integer Return x End Function Public Function M(x As String) As Integer Return x.Length End Function End Class Class A Public Sub New(x As Integer) Console.WriteLine(x) End Sub End Class Class B Inherits A Dim Color As Color Public Sub New() MyBase.New(Color.M(DirectCast(42, Object))) End Sub Shared Sub Main() Dim b = New B() End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_6() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Function M(x As Integer) As Integer Console.WriteLine(x) Return x End Function Public Function M(x As String) As Integer Return x.Length End Function End Class Class Program Dim Color As Color Dim I As Integer = Color.M(DirectCast(42, Object)) Shared Sub Main() Try Dim p = New Program() Catch e As Exception Console.WriteLine(e.GetType()) End Try End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.Field, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_7() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Function M(x As Integer) As Integer Console.WriteLine(x) Return x End Function Public Function M(x As String) As Integer Return x.Length End Function End Class Class Program Dim Color As Color Shared Dim I As Integer = Color.M(DirectCast(42, Object)) Shared Sub Main() Dim i = Program.I End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact> Public Sub Bug1108007_8() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Imports System Class Color Public Shared Sub M(x As Integer) Console.WriteLine(x) End Sub Public Sub M(x As String) End Sub End Class Class Outer Dim Color As Color Class Program Sub M() Try Dim x As Object = "" Color.M(x) Catch e As Exception Console.WriteLine(e.GetType()) End Try End Sub Shared Sub Main() Dim p = New Program() p.M() End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.NamedType, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:=<![CDATA[System.NullReferenceException]]>) End Sub <WorkItem(1108007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1108007")> <Fact()> Public Sub Bug1108007_9() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Color Public Shared Sub M(x As Integer) System.Console.WriteLine(x) End Sub Public Sub M(x As String) End Sub End Class Class Outer Shared Dim Color As Color = New Color() Class Program Sub M() Dim x As Object = 42 Color.M(x) End Sub Shared Sub Main() Dim p = New Program() p.M() End Sub End Class End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.Field, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub <WorkItem(1114969, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114969")> <Fact()> Public Sub Bug1114969() Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"> Class Color Public Function M() As Integer Return 42 End Function End Class Class Base Protected Dim Color As Color = New Color() End Class Class Derived Inherits Base Sub M() System.Console.WriteLine(Color.M()) End Sub Shared Sub Main() Dim d = New Derived() d.M() End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) Dim tree = compilation.SyntaxTrees(0) Dim model = compilation.GetSemanticModel(tree) Dim node = tree.GetRoot().DescendantNodes.OfType(Of MemberAccessExpressionSyntax)().Select(Function(e) e.Expression).Where(Function(e) e.ToString() = "Color").Single() Dim symbol = model.GetSymbolInfo(node).Symbol Assert.NotNull(symbol) Assert.Equal("Color", symbol.Name) Assert.Equal(SymbolKind.Field, symbol.Kind) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation, expectedOutput:="42") End Sub End Class End Namespace
OmarTawfik/roslyn
src/Compilers/VisualBasic/Test/Semantic/Binding/Binder_Expressions_Tests.vb
Visual Basic
apache-2.0
92,805
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' This class represents a synthesized delegate type derived from an Event declaration ''' </summary> ''' <remarks> ''' <example> ''' Class C ''' Event Name(a As Integer, b As Integer) ''' End Class ''' ''' defines an event and a delegate type: ''' ''' Event Name As NamedEventHandler ''' Delegate Sub NameEventHandler(a As Integer, b As Integer) ''' ''' </example> ''' </remarks> Friend NotInheritable Class SynthesizedEventDelegateSymbol Inherits InstanceTypeSymbol Private ReadOnly _eventName As String Private ReadOnly _name As String Private ReadOnly _containingType As NamedTypeSymbol Private ReadOnly _syntaxRef As SyntaxReference Private _lazyMembers As ImmutableArray(Of Symbol) Private _lazyEventSymbol As EventSymbol Private _reportedAllDeclarationErrors As Integer = 0 ' An integer to be able to do Interlocked operations. Friend Sub New(syntaxRef As SyntaxReference, containingSymbol As NamedTypeSymbol) Me._containingType = containingSymbol Me._syntaxRef = syntaxRef Dim eventName = Me.EventSyntax.Identifier.ValueText Me._eventName = eventName Me._name = _eventName & EVENT_DELEGATE_SUFFIX End Sub Public Overloads Overrides Function GetMembers() As ImmutableArray(Of Symbol) If Not _lazyMembers.IsDefault Then Return _lazyMembers End If Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) Dim binder As binder = BinderBuilder.CreateBinderForType(sourceModule, _syntaxRef.SyntaxTree, Me.ContainingType) Dim diagBag = BindingDiagnosticBag.GetInstance() Dim syntax = Me.EventSyntax Dim paramListOpt = syntax.ParameterList Dim ctor As MethodSymbol = Nothing Dim beginInvoke As MethodSymbol = Nothing Dim endInvoke As MethodSymbol = Nothing Dim invoke As MethodSymbol = Nothing SourceDelegateMethodSymbol.MakeDelegateMembers(Me, Me.EventSyntax, syntax.ParameterList, binder, ctor, beginInvoke, endInvoke, invoke, diagBag) ' We shouldn't need to check if this is a winmd compilation because ' winmd output requires that all events be declared Event ... As ..., ' but we can't add Nothing to the array, even if a diagnostic will be produced later ' Invoke must always be the last member Dim members As ImmutableArray(Of Symbol) If beginInvoke Is Nothing OrElse endInvoke Is Nothing Then members = ImmutableArray.Create(Of Symbol)(ctor, invoke) Else members = ImmutableArray.Create(Of Symbol)(ctor, beginInvoke, endInvoke, invoke) End If sourceModule.AtomicStoreArrayAndDiagnostics(_lazyMembers, members, diagBag) diagBag.Free() Return _lazyMembers End Function Public Overloads Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol) Return (From m In GetMembers() Where IdentifierComparison.Equals(m.Name, name)).AsImmutable End Function Friend Overrides Function GetFieldsToEmit() As IEnumerable(Of FieldSymbol) Return SpecializedCollections.EmptyEnumerable(Of FieldSymbol)() End Function Private ReadOnly Property EventSyntax As EventStatementSyntax Get Return DirectCast(Me._syntaxRef.GetSyntax, EventStatementSyntax) End Get End Property Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get If _lazyEventSymbol Is Nothing Then Dim events = _containingType.GetMembers(_eventName) For Each e In events Dim asEvent = TryCast(e, SourceEventSymbol) If asEvent IsNot Nothing Then Dim evSyntax = asEvent.SyntaxReference.GetSyntax If evSyntax IsNot Nothing AndAlso evSyntax Is EventSyntax Then _lazyEventSymbol = asEvent End If End If Next End If Debug.Assert(_lazyEventSymbol IsNot Nothing, "We should have found our event here") Return _lazyEventSymbol End Get End Property ''' <summary> ''' This property may be called while containing type is still being constructed. ''' Therefore it can take membersInProgress context to ensure that returned symbol ''' is relevant to the current type construction. ''' (there could be several optimistically concurrent sessions) ''' </summary> Friend Overrides ReadOnly Property ImplicitlyDefinedBy(Optional membersInProgress As Dictionary(Of String, ArrayBuilder(Of Symbol)) = Nothing) As Symbol Get If membersInProgress Is Nothing Then Return AssociatedSymbol End If Dim candidates = membersInProgress(_eventName) Dim eventInCurrentContext As SourceEventSymbol = Nothing Debug.Assert(candidates IsNot Nothing, "where is my event?") If candidates IsNot Nothing Then For Each e In candidates Dim asEvent = TryCast(e, SourceEventSymbol) If asEvent IsNot Nothing Then Dim evSyntax = asEvent.SyntaxReference.GetSyntax If evSyntax IsNot Nothing AndAlso evSyntax Is EventSyntax Then eventInCurrentContext = asEvent End If End If Next End If Return eventInCurrentContext End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol Get Return _containingType End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return AssociatedSymbol.DeclaredAccessibility End Get End Property Friend Overrides ReadOnly Property DefaultPropertyName As String Get Return Nothing End Get End Property Public Overloads Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overloads Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overloads Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Public Overrides ReadOnly Property IsMustInherit As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotInheritable As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property ShadowsExplicitly As Boolean Get Return AssociatedSymbol.ShadowsExplicitly End Get End Property Friend Overrides Function GetLexicalSortKey() As LexicalSortKey ' WARNING: this should not allocate memory! Return New LexicalSortKey(_syntaxRef, Me.DeclaringCompilation) End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_syntaxRef.GetLocation()) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return MakeDeclaredBase(Nothing, diagnostics) End Function Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Return _containingType.ContainingAssembly.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_MulticastDelegate) End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Return ImmutableArray(Of NamedTypeSymbol).Empty End Function Friend Overrides ReadOnly Property MangleName As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property MemberNames As System.Collections.Generic.IEnumerable(Of String) Get Return New HashSet(Of String)(From member In GetMembers() Select member.Name) End Get End Property Public Overrides ReadOnly Property MightContainExtensionMethods As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property IsComImport As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get Return Nothing End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Friend Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Throw ExceptionUtilities.Unreachable End Function Friend Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsSerializable As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property Layout As TypeLayout Get Return Nothing End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Return DefaultMarshallingCharSet End Get End Property Public Overrides ReadOnly Property TypeKind As TYPEKIND Get Return TypeKind.Delegate End Get End Property Friend Overrides ReadOnly Property IsInterface As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property ''' <summary> ''' Force all declaration errors to be generated. ''' </summary> Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) If _reportedAllDeclarationErrors <> 0 Then Return End If GetMembers() cancellationToken.ThrowIfCancellationRequested() Dim diagnostics = BindingDiagnosticBag.GetInstance() ' Force parameters and return value of Invoke method to be bound and errors reported. ' Parameters on other delegate methods are derived from Invoke so we don't need to call those. Me.DelegateInvokeMethod.GenerateDeclarationErrors(cancellationToken) Dim container = _containingType Dim outermostVariantInterface As NamedTypeSymbol = Nothing Do If Not container.IsInterfaceType() Then Debug.Assert(Not container.IsDelegateType()) ' Non-interface, non-delegate containers are illegal within variant interfaces. ' An error on the container will be sufficient if we haven't run into an interface already. Exit Do End If If container.TypeParameters.HaveVariance() Then ' We are inside of a variant interface outermostVariantInterface = container End If container = container.ContainingType Loop While container IsNot Nothing If outermostVariantInterface IsNot Nothing Then ' "Event definitions with parameters are not allowed in an interface such as '|1' that has ' 'In' or 'Out' type parameters. Consider declaring the event by using a delegate type which ' is not defined within '|1'. For example, 'Event |2 As Action(Of ...)'." diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_VariancePreventsSynthesizedEvents2, CustomSymbolDisplayFormatter.QualifiedName(outermostVariantInterface), AssociatedSymbol.Name), Locations(0))) End If DirectCast(ContainingModule, SourceModuleSymbol).AtomicStoreIntegerAndDiagnostics(_reportedAllDeclarationErrors, 1, 0, diagnostics) diagnostics.Free() End Sub Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get ' these are always implicitly declared. Return True End Get End Property Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind Get Return Me.ContainingType.EmbeddedSymbolKind End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function End Class End Namespace
physhi/roslyn
src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/SynthesizedEventDelegateSymbol.vb
Visual Basic
apache-2.0
17,303
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Editor Imports Microsoft.CodeAnalysis.FileHeaders Imports Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Imports Microsoft.CodeAnalysis.VisualBasic.FileHeaders Imports Microsoft.VisualStudio.ComponentModelHost Imports Microsoft.VisualStudio.LanguageServices.Implementation Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic <Guid(Guids.VisualBasicEditorFactoryIdString)> Friend Class VisualBasicEditorFactory Inherits AbstractEditorFactory Public Sub New(componentModel As IComponentModel) MyBase.New(componentModel) End Sub Protected Overrides ReadOnly Property ContentTypeName As String = ContentTypeNames.VisualBasicContentType Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic Protected Overrides ReadOnly Property SyntaxGenerator As SyntaxGenerator = VisualBasicSyntaxGenerator.Instance Protected Overrides ReadOnly Property SyntaxGeneratorInternal As SyntaxGeneratorInternal = VisualBasicSyntaxGeneratorInternal.Instance Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper = VisualBasicFileHeaderHelper.Instance End Class End Namespace
shyamnamboodiripad/roslyn
src/VisualStudio/VisualBasic/Impl/LanguageService/VisualBasicEditorFactory.vb
Visual Basic
apache-2.0
1,564
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class ConstructorDeclarationHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function CreateHighlighter() As IHighlighter Return New ConstructorDeclarationHighlighter() End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_1() As Task Await TestAsync(<Text> Class C {|Cursor:[|Public Sub New|]|}() [|Exit Sub|] [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_2() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() {|Cursor:[|Exit Sub|]|} [|End Sub|] End Class</Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestConstructorExample1_3() As Task Await TestAsync(<Text> Class C [|Public Sub New|]() [|Exit Sub|] {|Cursor:[|End Sub|]|} End Class</Text>) End Function End Class End Namespace
Pvlerick/roslyn
src/EditorFeatures/VisualBasicTest/KeywordHighlighting/ConstructorDeclarationHighlighterTests.vb
Visual Basic
apache-2.0
1,464
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class GlobalKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NoneInClassDeclarationTest() As Task Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalInStatementTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterReturnTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Return |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterArgument1Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Foo(|</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterArgument2Test() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Foo(bar, |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterBinaryExpressionTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Foo(bar + |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterNotTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Foo(Not |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterTypeOfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>If TypeOf |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterDoWhileTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Do While |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterDoUntilTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Do Until |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterLoopWhileTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody> Do Loop While |</MethodBody>, "Global") End Function <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterLoopUntilTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody> Do Loop Until |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>If |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterElseIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>ElseIf |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterElseSpaceIfTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Else If |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterErrorTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Error |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterThrowTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Throw |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterInitializerTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterArrayInitializerSquiggleTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterArrayInitializerCommaTest() As Task Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {0, |</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalNotAfterItselfTest() As Task Await VerifyRecommendationsMissingAsync(<MethodBody>Global.|</MethodBody>, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalNotAfterImportsTest() As Task Await VerifyRecommendationsMissingAsync(<File>Imports |</File>, "Global") End Function <WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function NotInDelegateCreationTest() As Task Dim code = <File> Module Program Sub Main(args As String()) Dim f1 As New Foo2( | End Sub Delegate Sub Foo2() Function Bar2() As Object Return Nothing End Function End Module </File> Await VerifyRecommendationsMissingAsync(code, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterInheritsTest() As Task Dim code = <File> Class C Inherits | End Class </File> Await VerifyRecommendationsContainAsync(code, "Global") End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Async Function GlobalAfterImplementsTest() As Task Dim code = <File> Class C Implements | End Class </File> Await VerifyRecommendationsContainAsync(code, "Global") End Function End Class End Namespace
bbarry/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/GlobalKeywordRecommenderTests.vb
Visual Basic
apache-2.0
7,216
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Expressions Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Queries Public Class AscendingDescendingKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AscendingDescendingNotInStatement() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AscendingDescendingNotInQuery() VerifyRecommendationsMissing(<MethodBody>Dim x = From y In z |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AscendingDescendingAfterFirstOrderByClause() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z Order By y |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AscendingDescendingAfterSecondOrderByClause() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z Let w = y Order By y, w |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AscendingDescendingNotAfterAscendingDescending() VerifyRecommendationsMissing(<MethodBody>Dim x = From y In z Order By y Ascending |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> <WorkItem(542930)> Public Sub AscendingDescendingAfterNestedQuery() VerifyRecommendationsContain(<MethodBody>Dim x = From y In z Order By From w In z |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> <WorkItem(543173)> Public Sub AscendingDescendingAfterMultiLineFunctionLambdaExpr() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By Function() Return 5 End Function |</MethodBody>, "Ascending", "Descending") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> <WorkItem(543174)> Public Sub AscendingDescendingAfterAnonymousObjectCreationExpr() VerifyRecommendationsContain(<MethodBody>Dim q2 = From i1 In arr Order By New With {.Key = 10} |</MethodBody>, "Ascending", "Descending") End Sub End Class End Namespace
droyad/roslyn
src/EditorFeatures/VisualBasicTest/Recommendations/Queries/AscendingDescendingKeywordRecommenderTests.vb
Visual Basic
apache-2.0
3,119
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmChannel #Region "Windows Form Designer generated code " <System.Diagnostics.DebuggerNonUserCode()> Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() End Sub 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean) If Disposing Then If Not components Is Nothing Then components.Dispose() End If End If MyBase.Dispose(Disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer Public ToolTip1 As System.Windows.Forms.ToolTip Public WithEvents _txtFields_0 As System.Windows.Forms.TextBox Public WithEvents _optType_1 As System.Windows.Forms.RadioButton Public WithEvents _optType_0 As System.Windows.Forms.RadioButton Public WithEvents cmbChannelPrice As System.Windows.Forms.ComboBox Public WithEvents _chkFields_5 As System.Windows.Forms.CheckBox Public WithEvents _chkFields_4 As System.Windows.Forms.CheckBox Public WithEvents _chkFields_3 As System.Windows.Forms.CheckBox Public WithEvents _txtFields_2 As System.Windows.Forms.TextBox Public WithEvents _txtFields_1 As System.Windows.Forms.TextBox Public WithEvents cmdCancel As System.Windows.Forms.Button Public WithEvents cmdClose As System.Windows.Forms.Button Public WithEvents picButtons As System.Windows.Forms.Panel Public WithEvents _Label1_1 As System.Windows.Forms.Label Public WithEvents _Label1_0 As System.Windows.Forms.Label Public WithEvents _lblLabels_2 As System.Windows.Forms.Label Public WithEvents _lblLabels_1 As System.Windows.Forms.Label Public WithEvents _Shape1_2 As Microsoft.VisualBasic.PowerPacks.RectangleShape Public WithEvents _lbl_5 As System.Windows.Forms.Label 'Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray 'Public WithEvents chkFields As Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray 'Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray 'Public WithEvents lblLabels As Microsoft.VisualBasic.Compatibility.VB6.LabelArray 'Public WithEvents optType As Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray 'Public WithEvents txtFields As Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray Public WithEvents Shape1 As RectangleShapeArray Public WithEvents ShapeContainer1 As Microsoft.VisualBasic.PowerPacks.ShapeContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmChannel)) Me.components = New System.ComponentModel.Container() Me.ToolTip1 = New System.Windows.Forms.ToolTip(components) Me.ShapeContainer1 = New Microsoft.VisualBasic.PowerPacks.ShapeContainer Me._txtFields_0 = New System.Windows.Forms.TextBox Me._optType_1 = New System.Windows.Forms.RadioButton Me._optType_0 = New System.Windows.Forms.RadioButton Me.cmbChannelPrice = New System.Windows.Forms.ComboBox Me._chkFields_5 = New System.Windows.Forms.CheckBox Me._chkFields_4 = New System.Windows.Forms.CheckBox Me._chkFields_3 = New System.Windows.Forms.CheckBox Me._txtFields_2 = New System.Windows.Forms.TextBox Me._txtFields_1 = New System.Windows.Forms.TextBox Me.picButtons = New System.Windows.Forms.Panel Me.cmdCancel = New System.Windows.Forms.Button Me.cmdClose = New System.Windows.Forms.Button Me._Label1_1 = New System.Windows.Forms.Label Me._Label1_0 = New System.Windows.Forms.Label Me._lblLabels_2 = New System.Windows.Forms.Label Me._lblLabels_1 = New System.Windows.Forms.Label Me._Shape1_2 = New Microsoft.VisualBasic.PowerPacks.RectangleShape Me._lbl_5 = New System.Windows.Forms.Label 'Me.Label1 = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) 'Me.chkFields = New Microsoft.VisualBasic.Compatibility.VB6.CheckBoxArray(components) 'Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) 'Me.lblLabels = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) 'Me.optType = New Microsoft.VisualBasic.Compatibility.VB6.RadioButtonArray(components) 'Me.txtFields = New Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components) Me.Shape1 = New RectangleShapeArray(components) Me.picButtons.SuspendLayout() Me.SuspendLayout() Me.ToolTip1.Active = True 'CType(Me.Label1, System.ComponentModel.ISupportInitialize).BeginInit() 'CType(Me.chkFields, System.ComponentModel.ISupportInitialize).BeginInit() 'CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() 'CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).BeginInit() 'CType(Me.optType, System.ComponentModel.ISupportInitialize).BeginInit() 'CType(Me.txtFields, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.Shape1, System.ComponentModel.ISupportInitialize).BeginInit() Me.BackColor = System.Drawing.Color.FromARGB(224, 224, 224) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Text = "Edit Sale Channel Details" Me.ClientSize = New System.Drawing.Size(432, 298) Me.Location = New System.Drawing.Point(73, 22) Me.ControlBox = False Me.KeyPreview = True Me.MaximizeBox = False Me.MinimizeBox = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Enabled = True Me.Cursor = System.Windows.Forms.Cursors.Default Me.RightToLeft = System.Windows.Forms.RightToLeft.No Me.ShowInTaskbar = True Me.HelpButton = False Me.WindowState = System.Windows.Forms.FormWindowState.Normal Me.Name = "frmChannel" Me._txtFields_0.AutoSize = False Me._txtFields_0.Size = New System.Drawing.Size(67, 19) Me._txtFields_0.Location = New System.Drawing.Point(264, 234) Me._txtFields_0.Maxlength = 5 Me._txtFields_0.TabIndex = 16 Me._txtFields_0.Visible = False Me._txtFields_0.AcceptsReturn = True Me._txtFields_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me._txtFields_0.BackColor = System.Drawing.SystemColors.Window Me._txtFields_0.CausesValidation = True Me._txtFields_0.Enabled = True Me._txtFields_0.ForeColor = System.Drawing.SystemColors.WindowText Me._txtFields_0.HideSelection = True Me._txtFields_0.ReadOnly = False Me._txtFields_0.Cursor = System.Windows.Forms.Cursors.IBeam Me._txtFields_0.MultiLine = False Me._txtFields_0.RightToLeft = System.Windows.Forms.RightToLeft.No Me._txtFields_0.ScrollBars = System.Windows.Forms.ScrollBars.None Me._txtFields_0.TabStop = True Me._txtFields_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me._txtFields_0.Name = "_txtFields_0" Me._optType_1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft Me._optType_1.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._optType_1.Text = "Price of default sales channel plus pricing group percentage" Me._optType_1.Size = New System.Drawing.Size(346, 16) Me._optType_1.Location = New System.Drawing.Point(54, 252) Me._optType_1.TabIndex = 15 Me._optType_1.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft Me._optType_1.CausesValidation = True Me._optType_1.Enabled = True Me._optType_1.ForeColor = System.Drawing.SystemColors.ControlText Me._optType_1.Cursor = System.Windows.Forms.Cursors.Default Me._optType_1.RightToLeft = System.Windows.Forms.RightToLeft.No Me._optType_1.Appearance = System.Windows.Forms.Appearance.Normal Me._optType_1.TabStop = True Me._optType_1.Checked = False Me._optType_1.Visible = True Me._optType_1.Name = "_optType_1" Me._optType_0.TextAlign = System.Drawing.ContentAlignment.MiddleLeft Me._optType_0.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._optType_0.Text = "Cost plus pricing group percentage" Me._optType_0.Size = New System.Drawing.Size(346, 16) Me._optType_0.Location = New System.Drawing.Point(54, 234) Me._optType_0.TabIndex = 13 Me._optType_0.CheckAlign = System.Drawing.ContentAlignment.MiddleLeft Me._optType_0.CausesValidation = True Me._optType_0.Enabled = True Me._optType_0.ForeColor = System.Drawing.SystemColors.ControlText Me._optType_0.Cursor = System.Windows.Forms.Cursors.Default Me._optType_0.RightToLeft = System.Windows.Forms.RightToLeft.No Me._optType_0.Appearance = System.Windows.Forms.Appearance.Normal Me._optType_0.TabStop = True Me._optType_0.Checked = False Me._optType_0.Visible = True Me._optType_0.Name = "_optType_0" Me.cmbChannelPrice.Size = New System.Drawing.Size(196, 21) Me.cmbChannelPrice.Location = New System.Drawing.Point(78, 174) Me.cmbChannelPrice.Items.AddRange(New Object(){"No relationship", "Always the same or cheaper", "Always the same or more expensive"}) Me.cmbChannelPrice.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList Me.cmbChannelPrice.TabIndex = 11 Me.cmbChannelPrice.BackColor = System.Drawing.SystemColors.Window Me.cmbChannelPrice.CausesValidation = True Me.cmbChannelPrice.Enabled = True Me.cmbChannelPrice.ForeColor = System.Drawing.SystemColors.WindowText Me.cmbChannelPrice.IntegralHeight = True Me.cmbChannelPrice.Cursor = System.Windows.Forms.Cursors.Default Me.cmbChannelPrice.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmbChannelPrice.Sorted = False Me.cmbChannelPrice.TabStop = True Me.cmbChannelPrice.Visible = True Me.cmbChannelPrice.Name = "cmbChannelPrice" Me._chkFields_5.CheckAlign = System.Drawing.ContentAlignment.MiddleRight Me._chkFields_5.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me._chkFields_5.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._chkFields_5.Text = "Treat a case/carton price as the unit price when doing the pricing update:" Me._chkFields_5.ForeColor = System.Drawing.SystemColors.WindowText Me._chkFields_5.Size = New System.Drawing.Size(373, 19) Me._chkFields_5.Location = New System.Drawing.Point(33, 135) Me._chkFields_5.TabIndex = 10 Me._chkFields_5.CausesValidation = True Me._chkFields_5.Enabled = True Me._chkFields_5.Cursor = System.Windows.Forms.Cursors.Default Me._chkFields_5.RightToLeft = System.Windows.Forms.RightToLeft.No Me._chkFields_5.Appearance = System.Windows.Forms.Appearance.Normal Me._chkFields_5.TabStop = True Me._chkFields_5.CheckState = System.Windows.Forms.CheckState.Unchecked Me._chkFields_5.Visible = True Me._chkFields_5.Name = "_chkFields_5" Me._chkFields_4.CheckAlign = System.Drawing.ContentAlignment.MiddleRight Me._chkFields_4.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me._chkFields_4.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._chkFields_4.Text = "Do not use Pricing Strategy when doing pricing update:" Me._chkFields_4.ForeColor = System.Drawing.SystemColors.WindowText Me._chkFields_4.Size = New System.Drawing.Size(283, 19) Me._chkFields_4.Location = New System.Drawing.Point(123, 114) Me._chkFields_4.TabIndex = 9 Me._chkFields_4.CausesValidation = True Me._chkFields_4.Enabled = True Me._chkFields_4.Cursor = System.Windows.Forms.Cursors.Default Me._chkFields_4.RightToLeft = System.Windows.Forms.RightToLeft.No Me._chkFields_4.Appearance = System.Windows.Forms.Appearance.Normal Me._chkFields_4.TabStop = True Me._chkFields_4.CheckState = System.Windows.Forms.CheckState.Unchecked Me._chkFields_4.Visible = True Me._chkFields_4.Name = "_chkFields_4" Me._chkFields_3.CheckAlign = System.Drawing.ContentAlignment.MiddleRight Me._chkFields_3.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me._chkFields_3.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._chkFields_3.Text = "Disable this sale channel on the POS:" Me._chkFields_3.ForeColor = System.Drawing.SystemColors.WindowText Me._chkFields_3.Size = New System.Drawing.Size(202, 19) Me._chkFields_3.Location = New System.Drawing.Point(204, 93) Me._chkFields_3.TabIndex = 8 Me._chkFields_3.CausesValidation = True Me._chkFields_3.Enabled = True Me._chkFields_3.Cursor = System.Windows.Forms.Cursors.Default Me._chkFields_3.RightToLeft = System.Windows.Forms.RightToLeft.No Me._chkFields_3.Appearance = System.Windows.Forms.Appearance.Normal Me._chkFields_3.TabStop = True Me._chkFields_3.CheckState = System.Windows.Forms.CheckState.Unchecked Me._chkFields_3.Visible = True Me._chkFields_3.Name = "_chkFields_3" Me._txtFields_2.AutoSize = False Me._txtFields_2.Size = New System.Drawing.Size(49, 19) Me._txtFields_2.Location = New System.Drawing.Point(357, 69) Me._txtFields_2.Maxlength = 5 Me._txtFields_2.TabIndex = 7 Me._txtFields_2.AcceptsReturn = True Me._txtFields_2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me._txtFields_2.BackColor = System.Drawing.SystemColors.Window Me._txtFields_2.CausesValidation = True Me._txtFields_2.Enabled = True Me._txtFields_2.ForeColor = System.Drawing.SystemColors.WindowText Me._txtFields_2.HideSelection = True Me._txtFields_2.ReadOnly = False Me._txtFields_2.Cursor = System.Windows.Forms.Cursors.IBeam Me._txtFields_2.MultiLine = False Me._txtFields_2.RightToLeft = System.Windows.Forms.RightToLeft.No Me._txtFields_2.ScrollBars = System.Windows.Forms.ScrollBars.None Me._txtFields_2.TabStop = True Me._txtFields_2.Visible = True Me._txtFields_2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me._txtFields_2.Name = "_txtFields_2" Me._txtFields_1.AutoSize = False Me._txtFields_1.Size = New System.Drawing.Size(217, 19) Me._txtFields_1.Location = New System.Drawing.Point(66, 69) Me._txtFields_1.TabIndex = 5 Me._txtFields_1.AcceptsReturn = True Me._txtFields_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me._txtFields_1.BackColor = System.Drawing.SystemColors.Window Me._txtFields_1.CausesValidation = True Me._txtFields_1.Enabled = True Me._txtFields_1.ForeColor = System.Drawing.SystemColors.WindowText Me._txtFields_1.HideSelection = True Me._txtFields_1.ReadOnly = False Me._txtFields_1.Maxlength = 0 Me._txtFields_1.Cursor = System.Windows.Forms.Cursors.IBeam Me._txtFields_1.MultiLine = False Me._txtFields_1.RightToLeft = System.Windows.Forms.RightToLeft.No Me._txtFields_1.ScrollBars = System.Windows.Forms.ScrollBars.None Me._txtFields_1.TabStop = True Me._txtFields_1.Visible = True Me._txtFields_1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me._txtFields_1.Name = "_txtFields_1" Me.picButtons.Dock = System.Windows.Forms.DockStyle.Top Me.picButtons.BackColor = System.Drawing.Color.Blue Me.picButtons.Size = New System.Drawing.Size(432, 39) Me.picButtons.Location = New System.Drawing.Point(0, 0) Me.picButtons.TabIndex = 2 Me.picButtons.TabStop = False Me.picButtons.CausesValidation = True Me.picButtons.Enabled = True Me.picButtons.ForeColor = System.Drawing.SystemColors.ControlText Me.picButtons.Cursor = System.Windows.Forms.Cursors.Default Me.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No Me.picButtons.Visible = True Me.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.picButtons.Name = "picButtons" Me.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdCancel.Text = "&Undo" Me.cmdCancel.Size = New System.Drawing.Size(73, 29) Me.cmdCancel.Location = New System.Drawing.Point(5, 3) Me.cmdCancel.TabIndex = 1 Me.cmdCancel.TabStop = False Me.cmdCancel.BackColor = System.Drawing.SystemColors.Control Me.cmdCancel.CausesValidation = True Me.cmdCancel.Enabled = True Me.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default Me.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdCancel.Name = "cmdCancel" Me.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdClose.Text = "E&xit" Me.cmdClose.Size = New System.Drawing.Size(73, 29) Me.cmdClose.Location = New System.Drawing.Point(351, 3) Me.cmdClose.TabIndex = 0 Me.cmdClose.TabStop = False Me.cmdClose.BackColor = System.Drawing.SystemColors.Control Me.cmdClose.CausesValidation = True Me.cmdClose.Enabled = True Me.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdClose.Cursor = System.Windows.Forms.Cursors.Default Me.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdClose.Name = "cmdClose" Me._Label1_1.Text = "When calculating exit price percentages, prices are calculated as," Me._Label1_1.Size = New System.Drawing.Size(388, 16) Me._Label1_1.Location = New System.Drawing.Point(21, 216) Me._Label1_1.TabIndex = 14 Me._Label1_1.TextAlign = System.Drawing.ContentAlignment.TopLeft Me._Label1_1.BackColor = System.Drawing.Color.Transparent Me._Label1_1.Enabled = True Me._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText Me._Label1_1.Cursor = System.Windows.Forms.Cursors.Default Me._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No Me._Label1_1.UseMnemonic = True Me._Label1_1.Visible = True Me._Label1_1.AutoSize = False Me._Label1_1.BorderStyle = System.Windows.Forms.BorderStyle.None Me._Label1_1.Name = "_Label1_1" Me._Label1_0.Text = "When doing the pricing calculation this Sale Channel relationship to the First Sale Channel is," Me._Label1_0.Size = New System.Drawing.Size(388, 43) Me._Label1_0.Location = New System.Drawing.Point(21, 159) Me._Label1_0.TabIndex = 12 Me._Label1_0.TextAlign = System.Drawing.ContentAlignment.TopLeft Me._Label1_0.BackColor = System.Drawing.Color.Transparent Me._Label1_0.Enabled = True Me._Label1_0.ForeColor = System.Drawing.SystemColors.ControlText Me._Label1_0.Cursor = System.Windows.Forms.Cursors.Default Me._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No Me._Label1_0.UseMnemonic = True Me._Label1_0.Visible = True Me._Label1_0.AutoSize = False Me._Label1_0.BorderStyle = System.Windows.Forms.BorderStyle.None Me._Label1_0.Name = "_Label1_0" Me._lblLabels_2.TextAlign = System.Drawing.ContentAlignment.TopRight Me._lblLabels_2.BackColor = System.Drawing.Color.Transparent Me._lblLabels_2.Text = "Short Name:" Me._lblLabels_2.ForeColor = System.Drawing.SystemColors.WindowText Me._lblLabels_2.Size = New System.Drawing.Size(61, 13) Me._lblLabels_2.Location = New System.Drawing.Point(291, 72) Me._lblLabels_2.TabIndex = 6 Me._lblLabels_2.Enabled = True Me._lblLabels_2.Cursor = System.Windows.Forms.Cursors.Default Me._lblLabels_2.RightToLeft = System.Windows.Forms.RightToLeft.No Me._lblLabels_2.UseMnemonic = True Me._lblLabels_2.Visible = True Me._lblLabels_2.AutoSize = True Me._lblLabels_2.BorderStyle = System.Windows.Forms.BorderStyle.None Me._lblLabels_2.Name = "_lblLabels_2" Me._lblLabels_1.TextAlign = System.Drawing.ContentAlignment.TopRight Me._lblLabels_1.BackColor = System.Drawing.Color.Transparent Me._lblLabels_1.Text = "Name:" Me._lblLabels_1.ForeColor = System.Drawing.SystemColors.WindowText Me._lblLabels_1.Size = New System.Drawing.Size(31, 13) Me._lblLabels_1.Location = New System.Drawing.Point(27, 72) Me._lblLabels_1.TabIndex = 4 Me._lblLabels_1.Enabled = True Me._lblLabels_1.Cursor = System.Windows.Forms.Cursors.Default Me._lblLabels_1.RightToLeft = System.Windows.Forms.RightToLeft.No Me._lblLabels_1.UseMnemonic = True Me._lblLabels_1.Visible = True Me._lblLabels_1.AutoSize = True Me._lblLabels_1.BorderStyle = System.Windows.Forms.BorderStyle.None Me._lblLabels_1.Name = "_lblLabels_1" Me._Shape1_2.BackColor = System.Drawing.Color.FromARGB(192, 192, 255) Me._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque Me._Shape1_2.Size = New System.Drawing.Size(403, 220) Me._Shape1_2.Location = New System.Drawing.Point(15, 60) Me._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText Me._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid Me._Shape1_2.BorderWidth = 1 Me._Shape1_2.FillColor = System.Drawing.Color.Black Me._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent Me._Shape1_2.Visible = True Me._Shape1_2.Name = "_Shape1_2" Me._lbl_5.BackColor = System.Drawing.Color.Transparent Me._lbl_5.Text = "&1. General" Me._lbl_5.Size = New System.Drawing.Size(60, 13) Me._lbl_5.Location = New System.Drawing.Point(15, 45) Me._lbl_5.TabIndex = 3 Me._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft Me._lbl_5.Enabled = True Me._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText Me._lbl_5.Cursor = System.Windows.Forms.Cursors.Default Me._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No Me._lbl_5.UseMnemonic = True Me._lbl_5.Visible = True Me._lbl_5.AutoSize = True Me._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None Me._lbl_5.Name = "_lbl_5" Me.Controls.Add(_txtFields_0) Me.Controls.Add(_optType_1) Me.Controls.Add(_optType_0) Me.Controls.Add(cmbChannelPrice) Me.Controls.Add(_chkFields_5) Me.Controls.Add(_chkFields_4) Me.Controls.Add(_chkFields_3) Me.Controls.Add(_txtFields_2) Me.Controls.Add(_txtFields_1) Me.Controls.Add(picButtons) Me.Controls.Add(_Label1_1) Me.Controls.Add(_Label1_0) Me.Controls.Add(_lblLabels_2) Me.Controls.Add(_lblLabels_1) Me.ShapeContainer1.Shapes.Add(_Shape1_2) Me.Controls.Add(_lbl_5) Me.Controls.Add(ShapeContainer1) Me.picButtons.Controls.Add(cmdCancel) Me.picButtons.Controls.Add(cmdClose) 'Me.Label1.SetIndex(_Label1_1, CType(1, Short)) 'Me.Label1.SetIndex(_Label1_0, CType(0, Short)) 'Me.chkFields.SetIndex(_chkFields_5, CType(5, Short)) 'Me.chkFields.SetIndex(_chkFields_4, CType(4, Short)) 'Me.chkFields.SetIndex(_chkFields_3, CType(3, Short)) 'Me.lbl.SetIndex(_lbl_5, CType(5, Short)) 'Me.lblLabels.SetIndex(_lblLabels_2, CType(2, Short)) 'Me.lblLabels.SetIndex(_lblLabels_1, CType(1, Short)) 'Me.optType.SetIndex(_optType_1, CType(1, Short)) 'Me.optType.SetIndex(_optType_0, CType(0, Short)) 'Me.txtFields.SetIndex(_txtFields_0, CType(0, Short)) 'Me.txtFields.SetIndex(_txtFields_2, CType(2, Short)) 'Me.txtFields.SetIndex(_txtFields_1, CType(1, Short)) 'Me.Shape1.SetIndex(_Shape1_2, CType(2, Short)) CType(Me.Shape1, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.txtFields, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.optType, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.lblLabels, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.chkFields, System.ComponentModel.ISupportInitialize).EndInit() 'CType(Me.Label1, System.ComponentModel.ISupportInitialize).EndInit() Me.picButtons.ResumeLayout(False) Me.ResumeLayout(False) Me.PerformLayout() End Sub #End Region End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmChannel.Designer.vb
Visual Basic
mit
23,769
Public Class EstadoRequerimiento 'IdEstadoRequerimiento, IdRequerimiento, IdPersonal, FechaApruebaAnula, IdRol Public Property IdEstadoRequerimiento As Int32 Public Property IdRequerimiento As Int32 Public Property IdPersonal As Int32 Public Property FechaApruebaAnula As System.Nullable(Of Date) Public Property IdRol As Int32 Public Property persona As Personal Public ReadOnly Property NombrePersona As String Get Return persona.nombreCompleto End Get End Property End Class
crackper/SistFoncreagro
SistFoncreagro.BussinessEntities/EstadoRequerimiento.vb
Visual Basic
mit
545
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("WindowsApplication1")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("Microsoft")> <Assembly: AssemblyProduct("WindowsApplication1")> <Assembly: AssemblyCopyright("Copyright © Microsoft 2011")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("1d730863-67d4-4063-9002-1414f44085c9")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
Edinboro/CSCI-207
programs/LinearRegression/LinearRegression/LinearRegression/My Project/AssemblyInfo.vb
Visual Basic
mit
1,209
Imports Microsoft.VisualBasic Imports System Namespace DocumentExplorerExample ''' <summary> ''' Shows an About form for this application. ''' </summary> Public Class AboutForm Inherits System.Windows.Forms.Form #Region "Windows Form Designer generated code" Private components As System.ComponentModel.Container = Nothing Private pictureBox1 As System.Windows.Forms.PictureBox Private label1 As System.Windows.Forms.Label Private textBox1 As System.Windows.Forms.TextBox Private button1 As System.Windows.Forms.Button Private label2 As System.Windows.Forms.Label Private Sub InitializeComponent() Dim resources As New System.ComponentModel.ComponentResourceManager(GetType(AboutForm)) Me.pictureBox1 = New System.Windows.Forms.PictureBox() Me.label1 = New System.Windows.Forms.Label() Me.label2 = New System.Windows.Forms.Label() Me.textBox1 = New System.Windows.Forms.TextBox() Me.button1 = New System.Windows.Forms.Button() Me.SuspendLayout() ' ' pictureBox1 ' Me.pictureBox1.BackColor = System.Drawing.Color.Transparent Me.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle Me.pictureBox1.Image = (CType(resources.GetObject("pictureBox1.Image"), System.Drawing.Image)) Me.pictureBox1.Location = New System.Drawing.Point(8, 8) Me.pictureBox1.Name = "pictureBox1" Me.pictureBox1.Size = New System.Drawing.Size(128, 132) Me.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage Me.pictureBox1.TabIndex = 0 Me.pictureBox1.TabStop = False ' ' label1 ' Me.label1.Font = New System.Drawing.Font("Times New Roman", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte(204))) Me.label1.ForeColor = System.Drawing.Color.Black Me.label1.Location = New System.Drawing.Point(144, 4) Me.label1.Name = "label1" Me.label1.Size = New System.Drawing.Size(404, 32) Me.label1.TabIndex = 1 Me.label1.Text = "Document Explorer Demo for Aspose.Words " Me.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' ' label2 ' Me.label2.FlatStyle = System.Windows.Forms.FlatStyle.Flat Me.label2.Font = New System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, (CByte(204))) Me.label2.ForeColor = System.Drawing.Color.Black Me.label2.Location = New System.Drawing.Point(144, 120) Me.label2.Name = "label2" Me.label2.Size = New System.Drawing.Size(364, 20) Me.label2.TabIndex = 2 Me.label2.Text = "Copyright © 2002-2010 Aspose Pty Ltd. All Rights Reserved. " Me.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter ' ' textBox1 ' Me.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None Me.textBox1.Location = New System.Drawing.Point(144, 40) Me.textBox1.Multiline = True Me.textBox1.Name = "textBox1" Me.textBox1.ReadOnly = True Me.textBox1.Size = New System.Drawing.Size(428, 68) Me.textBox1.TabIndex = 3 Me.textBox1.TabStop = False Me.textBox1.Text = resources.GetString("textBox1.Text") ' ' button1 ' Me.button1.DialogResult = System.Windows.Forms.DialogResult.OK Me.button1.ForeColor = System.Drawing.SystemColors.ControlText Me.button1.Location = New System.Drawing.Point(508, 120) Me.button1.Name = "button1" Me.button1.Size = New System.Drawing.Size(75, 23) Me.button1.TabIndex = 4 Me.button1.Text = "OK" ' ' AboutForm ' Me.AcceptButton = Me.button1 Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.BackColor = System.Drawing.SystemColors.Control Me.ClientSize = New System.Drawing.Size(590, 150) Me.ControlBox = False Me.Controls.Add(Me.button1) Me.Controls.Add(Me.textBox1) Me.Controls.Add(Me.label2) Me.Controls.Add(Me.label1) Me.Controls.Add(Me.pictureBox1) Me.ForeColor = System.Drawing.SystemColors.Window Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog Me.Name = "AboutForm" Me.ShowInTaskbar = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent Me.TopMost = True Me.ResumeLayout(False) Me.PerformLayout() End Sub Protected Overrides Overloads Sub Dispose(ByVal disposing As Boolean) If disposing Then If components IsNot Nothing Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub #End Region Public Sub New() InitializeComponent() End Sub End Class End Namespace
assadvirgo/Aspose_Words_NET
Examples/VisualBasic/Viewers-Visualizers/Document-Explorer/AboutForm.vb
Visual Basic
mit
4,519
'------------------------------------------------------------------------------ ' <auto-generated> ' このコードはツールによって生成されました。 ' ランタイム バージョン:4.0.30319.18033 ' ' このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 ' コードが再生成されるときに損失したりします。 ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'このクラスは StronglyTypedResourceBuilder クラスが ResGen 'または Visual Studio のようなツールを使用して自動生成されました。 'メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に 'ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 '''<summary> ''' ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("jp.co.systembase.barcode.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' 厳密に型指定されたこのリソース クラスを使用して、すべての検索リソースに対し、 ''' 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
rapidreport/barcode-dotnet
barcode/My Project/Resources.Designer.vb
Visual Basic
bsd-2-clause
3,182
'' Copyright (c) 2013, Kcchouette and b-dauphin on Github '' All rights reserved. '' '' Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: '' '' Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. '' Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. '' Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. '' '' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class FrmAccueil Inherits System.Windows.Forms.Form 'Form remplace la méthode Dispose pour nettoyer la liste des composants. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Requise par le Concepteur Windows Form Private components As System.ComponentModel.IContainer 'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form 'Elle peut être modifiée à l'aide du Concepteur Windows Form. 'Ne la modifiez pas à l'aide de l'éditeur de code. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.btnInscrire = New System.Windows.Forms.Button() Me.btnModifSuppr = New System.Windows.Forms.Button() Me.btnAff = New System.Windows.Forms.Button() Me.btnBilan = New System.Windows.Forms.Button() Me.btnFin = New System.Windows.Forms.Button() Me.tmrHeureActu = New System.Windows.Forms.Timer(Me.components) Me.SuspendLayout() ' 'btnInscrire ' Me.btnInscrire.Location = New System.Drawing.Point(12, 12) Me.btnInscrire.Name = "btnInscrire" Me.btnInscrire.Size = New System.Drawing.Size(102, 48) Me.btnInscrire.TabIndex = 0 Me.btnInscrire.Text = "Inscrire un candidat" Me.btnInscrire.UseVisualStyleBackColor = True ' 'btnModifSuppr ' Me.btnModifSuppr.Location = New System.Drawing.Point(120, 12) Me.btnModifSuppr.Name = "btnModifSuppr" Me.btnModifSuppr.Size = New System.Drawing.Size(102, 48) Me.btnModifSuppr.TabIndex = 1 Me.btnModifSuppr.Text = "Modifier ou supprimer une inscription" Me.btnModifSuppr.UseVisualStyleBackColor = True ' 'btnAff ' Me.btnAff.Location = New System.Drawing.Point(120, 66) Me.btnAff.Name = "btnAff" Me.btnAff.Size = New System.Drawing.Size(102, 49) Me.btnAff.TabIndex = 3 Me.btnAff.Text = "Afficher l'état des inscriptions" Me.btnAff.UseVisualStyleBackColor = True ' 'btnBilan ' Me.btnBilan.Location = New System.Drawing.Point(12, 66) Me.btnBilan.Name = "btnBilan" Me.btnBilan.Size = New System.Drawing.Size(102, 49) Me.btnBilan.TabIndex = 4 Me.btnBilan.Text = "Établir un bilan provisoire" Me.btnBilan.UseVisualStyleBackColor = True ' 'btnFin ' Me.btnFin.Location = New System.Drawing.Point(127, 138) Me.btnFin.Name = "btnFin" Me.btnFin.Size = New System.Drawing.Size(95, 38) Me.btnFin.TabIndex = 5 Me.btnFin.Text = "Fin des inscriptions" Me.btnFin.UseVisualStyleBackColor = True ' 'tmrHeureActu ' Me.tmrHeureActu.Interval = 2000 ' 'FrmAccueil ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(238, 193) Me.ControlBox = False Me.Controls.Add(Me.btnFin) Me.Controls.Add(Me.btnBilan) Me.Controls.Add(Me.btnAff) Me.Controls.Add(Me.btnModifSuppr) Me.Controls.Add(Me.btnInscrire) Me.Name = "FrmAccueil" Me.Text = "Accueil" Me.ResumeLayout(False) End Sub Friend WithEvents btnInscrire As System.Windows.Forms.Button Friend WithEvents btnModifSuppr As System.Windows.Forms.Button Friend WithEvents btnAff As System.Windows.Forms.Button Friend WithEvents btnBilan As System.Windows.Forms.Button Friend WithEvents btnFin As System.Windows.Forms.Button Friend WithEvents tmrHeureActu As System.Windows.Forms.Timer End Class
Kcchouette/Inscription-au-bac
FrmAccueil.Designer.vb
Visual Basic
bsd-3-clause
5,694
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My 'NOTE: This file is auto-generated; do not modify it directly. To make changes, ' or if you encounter build errors in this file, go to the Project Designer ' (go to Project Properties or double-click the My Project node in ' Solution Explorer), and make changes on the Application tab. ' Partial Friend Class MyApplication <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Public Sub New() MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.ApplicationDefined) Me.IsSingleInstance = true Me.EnableVisualStyles = true Me.SaveMySettingsOnExit = true Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterAllFormsClose End Sub <Global.System.Diagnostics.DebuggerStepThroughAttribute()> _ Protected Overrides Sub OnCreateMainForm() Me.MainForm = Global.HostsX.HostsMain End Sub End Class End Namespace
Laicure/HostsX
HostsX/My Project/Application.Designer.vb
Visual Basic
mit
1,485
Imports System Imports System.ComponentModel.Design Imports System.Globalization Imports Microsoft.VisualStudio.Shell Imports Microsoft.VisualStudio.Shell.Interop ''' <summary> ''' Command handler ''' </summary> Public NotInheritable Class cmdDatabaseFirst ''' <summary> ''' Command ID. ''' </summary> Public Const CommandId As Integer = 256 ''' <summary> ''' Command menu group (command set GUID). ''' </summary> Public Shared ReadOnly CommandSet As New Guid("2b15f8e0-0ca0-4e15-8ae4-2b3236541832") ''' <summary> ''' VS Package that provides this command, not null. ''' </summary> Private ReadOnly package As Package ''' <summary> ''' Initializes a new instance of the <see cref="cmdDatabaseFirst"/> class. ''' Adds our command handlers for menu (the commands must exist in the command table file) ''' </summary> ''' <param name="package">Owner package, not null.</param> Private Sub New(package As Package) If package Is Nothing Then Throw New ArgumentNullException("package") End If Me.package = package Dim commandService As OleMenuCommandService = Me.ServiceProvider.GetService(GetType(IMenuCommandService)) If commandService IsNot Nothing Then Dim menuCommandId = New CommandID(CommandSet, CommandId) Dim menuCommand = New MenuCommand(AddressOf Me.MenuItemCallback, menuCommandId) commandService.AddCommand(menuCommand) End If End Sub ''' <summary> ''' Gets the instance of the command. ''' </summary> Public Shared Property Instance As cmdDatabaseFirst ''' <summary> ''' Get service provider from the owner package. ''' </summary> Private ReadOnly Property ServiceProvider As IServiceProvider Get Return Me.package End Get End Property ''' <summary> ''' Initializes the singleton instance of the command. ''' </summary> ''' <param name="package">Owner package, Not null.</param> Public Shared Sub Initialize(package As Package) Instance = New cmdDatabaseFirst(package) End Sub ''' <summary> ''' This function is the callback used to execute the command when the menu item is clicked. ''' See the constructor to see how the menu item is associated with this function using ''' OleMenuCommandService service and MenuCommand class. ''' </summary> ''' <param name="sender">Event sender.</param> ''' <param name="e">Event args.</param> Private Sub MenuItemCallback(sender As Object, e As EventArgs) Dim message = String.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", Me.GetType().FullName) Dim title = "Command1" ' Show a message box to prove we were here VsShellUtilities.ShowMessageBox( Me.ServiceProvider, message, title, OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST) End Sub End Class
marcermarc/OpenDatabaseFramework
marcermarc.OpenDatabaseFramework.VSExtension/cmdDatabaseFirst.vb
Visual Basic
mit
3,085
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34003 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("SimleDemoVB.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
luiseduardohdbackup/oxyplot-v2
Source/Examples/WPF/SimleDemoVB/My Project/Resources.Designer.vb
Visual Basic
mit
2,780
Imports Windows.UI NotInheritable Class App Inherits Application Protected Overrides Sub OnLaunched(e As LaunchActivatedEventArgs) ApplicationView.GetForCurrentView().SetPreferredMinSize(New Size(150, 250)) ApplicationView.GetForCurrentView.SetDesiredBoundsMode(ApplicationViewBoundsMode.UseCoreWindow) If Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar") Then StatusBar.GetForCurrentView().ForegroundColor = Colors.Black End If Dim rootFrame As Frame = TryCast(Window.Current.Content, Frame) If rootFrame Is Nothing Then rootFrame = New Frame() : Window.Current.Content = rootFrame If rootFrame.Content Is Nothing Then rootFrame.Navigate(GetType(MainPageCPU), e.Arguments) Window.Current.Activate() End Sub End Class
ljw1004/blog
Win2d/GameOfLife/App.xaml.vb
Visual Basic
mit
840
Imports System.Data.SqlClient Imports CrystalDecisions.CrystalReports.Engine Imports CrystalDecisions.Shared Imports System.Configuration Module Module1 Public CONN As SqlConnection Public DA As SqlDataAdapter Public DS As New DataSet Public CMD As SqlCommand Public DR As SqlDataReader Public STR As String Public cryRpt As New ReportDocument Public crtableLogoninfos As New TableLogOnInfos Public crtableLogoninfo As New TableLogOnInfo Public crConnectionInfo As New ConnectionInfo Public CrTables As Tables Public CrTable As Table 'Dim host As String = My.Computer.Name & "\SQLEXPRESS" Public Sub Module_Konfigurasi_laporan() With crConnectionInfo .ServerName = "localhost" .DatabaseName = "Arsip" .UserID = "sa" .Password = "123" End With CrTables = cryRpt.Database.Tables For Each CrTable In CrTables crtableLogoninfo = CrTable.LogOnInfo crtableLogoninfo.ConnectionInfo = crConnectionInfo CrTable.ApplyLogOnInfo(crtableLogoninfo) Next End Sub Public Sub Koneksi() 'STR = "data source=" & host & "; initial catalog=arsip;user id=sa; password=123" ' CONN = New SqlConnection(ConfigurationManager.AppSettings("DSN")) CONN = New SqlConnection(My.Settings.Connection) If CONN.State = ConnectionState.Closed Then CONN.Open() End If End Sub End Module
anakpantai/busus
SIMARSIP/Module1.vb
Visual Basic
apache-2.0
1,557
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Linq Imports Analyzer.Utilities Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace System.Runtime.Analyzers <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public Class BasicDisposableFieldsShouldBeDisposedAnalyzer Inherits DisposableFieldsShouldBeDisposedAnalyzer Protected Overrides Function GetAnalyzer(context As CompilationStartAnalysisContext, disposableType As INamedTypeSymbol) As AbstractAnalyzer Dim analyzer As New Analyzer(disposableType) context.RegisterSyntaxNodeAction(AddressOf analyzer.AnalyzeNode, SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.UsingStatement) Return analyzer End Function Private NotInheritable Class Analyzer Inherits AbstractAnalyzer Public Sub New(disposableType As INamedTypeSymbol) MyBase.New(disposableType) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) Select Case context.Node.Kind Case SyntaxKind.SimpleMemberAccessExpression ' NOTE: This cannot be optimized based on memberAccess.Name because a given method ' may be an explicit interface implementation of IDisposable.Dispose. ' If the right hand side of the member access binds to IDisposable.Dispose Dim memberAccess = DirectCast(context.Node, MemberAccessExpressionSyntax) Dim methodSymbol = TryCast(context.SemanticModel.GetSymbolInfo(memberAccess.Name).Symbol, IMethodSymbol) If methodSymbol IsNot Nothing AndAlso (methodSymbol.MetadataName = Dispose OrElse methodSymbol.ExplicitInterfaceImplementations.Any(Function(m) m.MetadataName = Dispose)) Then Dim receiverType = context.SemanticModel.GetTypeInfo(memberAccess.Expression).Type If (receiverType.Inherits(_disposableType)) Then Dim exp = RemoveParentheses(memberAccess.Expression) ' this can be simply x.Dispose() where x is the field. Dim fieldSymbol = TryCast(context.SemanticModel.GetSymbolInfo(exp).Symbol, IFieldSymbol) If fieldSymbol IsNot Nothing Then NoteFieldDisposed(fieldSymbol) Else ' Or it can be an explicit interface dispatch like DirectCast(f, IDisposable).Dispose() Dim expression = RemoveParentheses(memberAccess.Expression) If (expression.IsKind(SyntaxKind.DirectCastExpression) OrElse expression.IsKind(SyntaxKind.TryCastExpression)) OrElse expression.IsKind(SyntaxKind.CTypeExpression) Then Dim castExpression = DirectCast(expression, CastExpressionSyntax) fieldSymbol = TryCast(context.SemanticModel.GetSymbolInfo(castExpression.Expression).Symbol, IFieldSymbol) If (fieldSymbol IsNot Nothing) Then NoteFieldDisposed(fieldSymbol) End If End If End If End If End If Case SyntaxKind.UsingStatement Dim usingStatementExpression = RemoveParentheses(DirectCast(context.Node, UsingStatementSyntax).Expression) If usingStatementExpression IsNot Nothing Then Dim fieldSymbol = TryCast(context.SemanticModel.GetSymbolInfo(usingStatementExpression).Symbol, IFieldSymbol) If fieldSymbol IsNot Nothing Then NoteFieldDisposed(fieldSymbol) End If End If End Select End Sub Private Function RemoveParentheses(exp As ExpressionSyntax) As ExpressionSyntax Dim syntax = TryCast(exp, ParenthesizedExpressionSyntax) If syntax IsNot Nothing Then Return RemoveParentheses(syntax.Expression) End If Return exp End Function End Class End Class End Namespace
mattwar/roslyn-analyzers
src/System.Runtime.Analyzers/VisualBasic/BasicDisposableFieldsShouldBeDisposed.vb
Visual Basic
apache-2.0
4,844
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class LoginDetail Inherits bv.common.win.BaseDetailForm 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(LoginDetail)) Me.txtConfirmPassword = New DevExpress.XtraEditors.TextEdit() Me.lbConfirmPassword = New System.Windows.Forms.Label() Me.txtPassword = New DevExpress.XtraEditors.TextEdit() Me.lbPassword = New System.Windows.Forms.Label() Me.txtUserLogin = New DevExpress.XtraEditors.TextEdit() Me.Label7 = New System.Windows.Forms.Label() Me.lbSite = New System.Windows.Forms.Label() Me.LookUpEdit1 = New DevExpress.XtraEditors.LookUpEdit() CType(Me.txtConfirmPassword.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.txtPassword.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.txtUserLogin.Properties, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LookUpEdit1.Properties, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'txtConfirmPassword ' resources.ApplyResources(Me.txtConfirmPassword, "txtConfirmPassword") Me.txtConfirmPassword.Name = "txtConfirmPassword" Me.txtConfirmPassword.Properties.AutoHeight = CType(resources.GetObject("txtConfirmPassword.Properties.AutoHeight"), Boolean) Me.txtConfirmPassword.Properties.Mask.EditMask = resources.GetString("txtConfirmPassword.Properties.Mask.EditMask") Me.txtConfirmPassword.Properties.Mask.IgnoreMaskBlank = CType(resources.GetObject("txtConfirmPassword.Properties.Mask.IgnoreMaskBlank"), Boolean) Me.txtConfirmPassword.Properties.Mask.SaveLiteral = CType(resources.GetObject("txtConfirmPassword.Properties.Mask.SaveLiteral"), Boolean) Me.txtConfirmPassword.Properties.Mask.ShowPlaceHolders = CType(resources.GetObject("txtConfirmPassword.Properties.Mask.ShowPlaceHolders"), Boolean) Me.txtConfirmPassword.Properties.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42) Me.txtConfirmPassword.Tag = "{M}" ' 'lbConfirmPassword ' resources.ApplyResources(Me.lbConfirmPassword, "lbConfirmPassword") Me.lbConfirmPassword.Name = "lbConfirmPassword" ' 'txtPassword ' resources.ApplyResources(Me.txtPassword, "txtPassword") Me.txtPassword.Name = "txtPassword" Me.txtPassword.Properties.AutoHeight = CType(resources.GetObject("txtPassword.Properties.AutoHeight"), Boolean) Me.txtPassword.Properties.Mask.EditMask = resources.GetString("txtPassword.Properties.Mask.EditMask") Me.txtPassword.Properties.Mask.IgnoreMaskBlank = CType(resources.GetObject("txtPassword.Properties.Mask.IgnoreMaskBlank"), Boolean) Me.txtPassword.Properties.Mask.SaveLiteral = CType(resources.GetObject("txtPassword.Properties.Mask.SaveLiteral"), Boolean) Me.txtPassword.Properties.Mask.ShowPlaceHolders = CType(resources.GetObject("txtPassword.Properties.Mask.ShowPlaceHolders"), Boolean) Me.txtPassword.Properties.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42) Me.txtPassword.Tag = "{M}" ' 'lbPassword ' resources.ApplyResources(Me.lbPassword, "lbPassword") Me.lbPassword.Name = "lbPassword" ' 'txtUserLogin ' resources.ApplyResources(Me.txtUserLogin, "txtUserLogin") Me.txtUserLogin.Name = "txtUserLogin" Me.txtUserLogin.Properties.AutoHeight = CType(resources.GetObject("txtUserLogin.Properties.AutoHeight"), Boolean) Me.txtUserLogin.Properties.Mask.EditMask = resources.GetString("txtUserLogin.Properties.Mask.EditMask") Me.txtUserLogin.Properties.Mask.IgnoreMaskBlank = CType(resources.GetObject("txtUserLogin.Properties.Mask.IgnoreMaskBlank"), Boolean) Me.txtUserLogin.Properties.Mask.SaveLiteral = CType(resources.GetObject("txtUserLogin.Properties.Mask.SaveLiteral"), Boolean) Me.txtUserLogin.Properties.Mask.ShowPlaceHolders = CType(resources.GetObject("txtUserLogin.Properties.Mask.ShowPlaceHolders"), Boolean) Me.txtUserLogin.Properties.MaxLength = 200 Me.txtUserLogin.Tag = "{M}" ' 'Label7 ' resources.ApplyResources(Me.Label7, "Label7") Me.Label7.Name = "Label7" ' 'lbSite ' resources.ApplyResources(Me.lbSite, "lbSite") Me.lbSite.Name = "lbSite" ' 'LookUpEdit1 ' resources.ApplyResources(Me.LookUpEdit1, "LookUpEdit1") Me.LookUpEdit1.Name = "LookUpEdit1" Me.LookUpEdit1.Properties.AutoHeight = CType(resources.GetObject("LookUpEdit1.Properties.AutoHeight"), Boolean) Me.LookUpEdit1.Properties.Buttons.AddRange(New DevExpress.XtraEditors.Controls.EditorButton() {New DevExpress.XtraEditors.Controls.EditorButton(CType(resources.GetObject("LookUpEdit1.Properties.Buttons"), DevExpress.XtraEditors.Controls.ButtonPredefines))}) Me.LookUpEdit1.Tag = "{M}" ' 'LoginDetail ' resources.ApplyResources(Me, "$this") Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.LookUpEdit1) Me.Controls.Add(Me.lbSite) Me.Controls.Add(Me.txtConfirmPassword) Me.Controls.Add(Me.lbConfirmPassword) Me.Controls.Add(Me.txtPassword) Me.Controls.Add(Me.lbPassword) Me.Controls.Add(Me.txtUserLogin) Me.Controls.Add(Me.Label7) Me.FormID = "A31" Me.HelpTopicID = " EmployeeDetailForm" Me.LeftIcon = Global.EIDSS.My.Resources.Resources.User_Login_129_1_ Me.Name = "LoginDetail" Me.ShowDeleteButton = False Me.ShowSaveButton = False Me.Controls.SetChildIndex(Me.Label7, 0) Me.Controls.SetChildIndex(Me.txtUserLogin, 0) Me.Controls.SetChildIndex(Me.lbPassword, 0) Me.Controls.SetChildIndex(Me.txtPassword, 0) Me.Controls.SetChildIndex(Me.lbConfirmPassword, 0) Me.Controls.SetChildIndex(Me.txtConfirmPassword, 0) Me.Controls.SetChildIndex(Me.lbSite, 0) Me.Controls.SetChildIndex(Me.LookUpEdit1, 0) CType(Me.txtConfirmPassword.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.txtPassword.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.txtUserLogin.Properties, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LookUpEdit1.Properties, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents txtConfirmPassword As DevExpress.XtraEditors.TextEdit Friend WithEvents lbConfirmPassword As System.Windows.Forms.Label Friend WithEvents txtPassword As DevExpress.XtraEditors.TextEdit Friend WithEvents lbPassword As System.Windows.Forms.Label Friend WithEvents txtUserLogin As DevExpress.XtraEditors.TextEdit Friend WithEvents Label7 As System.Windows.Forms.Label Friend WithEvents lbSite As System.Windows.Forms.Label Friend WithEvents LookUpEdit1 As DevExpress.XtraEditors.LookUpEdit End Class
EIDSS/EIDSS-Legacy
EIDSS v5/vb/EIDSS/EIDSS_Admin/Person/LoginDetail.Designer.vb
Visual Basic
bsd-2-clause
8,206
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic Public Class CodeFunctionTests Inherits AbstractCodeFunctionTests #Region "GetStartPoint() tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_MustOverride1() Dim code = <Code> MustInherit Class C MustOverride Sub $$M() End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=22, absoluteOffset:=42, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24))) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_MustOverride2() Dim code = <Code> MustInherit Class C &lt;System.CLSCompliant(True)&gt; MustOverride Sub $$M() End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=22, absoluteOffset:=74, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_DeclareFunction_WithoutAttribute() Dim code = <Code> Public Class C1 Declare Function $$getUserName Lib "My1.dll" () As String End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=22, absoluteOffset:=38, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_DeclareFunction_WithAttribute() Dim code = <Code> Public Class C1 &lt;System.CLSCompliant(True)&gt; Declare Function $$getUserName Lib "My1.dll" () As String End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=22, absoluteOffset:=70, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_DeclareSub_WithoutAttribute() Dim code = <Code> Public Class C1 Public Declare Sub $$MethodName Lib "My1.dll" End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=24, absoluteOffset:=40, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetStartPoint_DeclareSub_WithAttribute() Dim code = <Code> Public Class C1 &lt;System.CLSCompliant(True)&gt; Public Declare Sub $$MethodName Lib "My1.dll" End Class </Code> TestGetStartPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=24, absoluteOffset:=72, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31))) End Sub #End Region #Region "GetEndPoint() tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_MustOverride1() Dim code = <Code> MustInherit Class C MustOverride Sub $$M() End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=23, absoluteOffset:=43, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24))) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_MustOverride2() Dim code = <Code> MustInherit Class C &lt;System.CLSCompliant(True)&gt; MustOverride Sub $$M() End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=52, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=52, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=23, absoluteOffset:=75, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_DeclareFunction_WithoutAttribute() Dim code = <Code> Public Class C1 Declare Function $$getUserName Lib "My1.dll" () As String End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=33, absoluteOffset:=49, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_DeclareFunction_WithAttribute() Dim code = <Code> Public Class C1 &lt;System.CLSCompliant(True)&gt; Declare Function $$getUserName Lib "My1.dll" () As String End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=33, absoluteOffset:=81, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_DeclareSub_WithoutAttribute() Dim code = <Code> Public Class C1 Declare Sub $$getUserName Lib "My1.dll" () End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, NullTextPoint), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=2, lineOffset:=28, absoluteOffset:=44, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44))) End Sub <WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub GetEndPoint_DeclareSub_WithAttribute() Dim code = <Code> Public Class C1 &lt;System.CLSCompliant(True)&gt; Declare Sub $$getUserName Lib "My1.dll" () End Class </Code> TestGetEndPoint(code, Part(EnvDTE.vsCMPart.vsCMPartAttributes, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter, TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)), Part(EnvDTE.vsCMPart.vsCMPartBody, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartHeader, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartName, TextPoint(line:=3, lineOffset:=28, absoluteOffset:=76, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartNavigate, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartWhole, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)), Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44))) End Sub #End Region #Region "Access tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access1() Dim code = <Code> Class C Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access2() Dim code = <Code> Class C Private Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access3() Dim code = <Code> Class C Protected Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access4() Dim code = <Code> Class C Protected Friend Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access5() Dim code = <Code> Class C Friend Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access6() Dim code = <Code> Class C Public Function $$F() As Integer Throw New NotImplementedException() End Function End Class </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Access7() Dim code = <Code> Interface I Function $$F() As Integer End Interface </Code> TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "CanOverride tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride1() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> TestCanOverride(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride2() Dim code = <Code> Interface I Sub $$Foo() End Interface </Code> TestCanOverride(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride3() Dim code = <Code> Class C Protected Overridable Sub $$Foo() End Sub End Class </Code> TestCanOverride(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride4() Dim code = <Code> Class C Protected Sub $$Foo() End Sub End Class </Code> TestCanOverride(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride5() Dim code = <Code> Class B Protected Overridable Sub Foo() End Sub End Class Class C Inherits B Protected Overrides Sub $$Foo() End Sub End Class </Code> TestCanOverride(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub CanOverride6() Dim code = <Code> Class B Protected Overridable Sub Foo() End Sub End Class Class C Inherits B Protected NotOverridable Overrides Sub $$Foo() End Sub End Class </Code> TestCanOverride(code, False) End Sub #End Region #Region "FunctionKind tests" <WorkItem(1843, "https://github.com/dotnet/roslyn/issues/1843")> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_Constructor() Dim code = <Code> Public Class C1 Public Sub $$New() End Sub End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionConstructor) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_Destructor() Dim code = <Code> Public Class C1 Protected Overrides Sub $$Finalize() MyBase.Finalize() End Sub End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionDestructor) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_Sub() Dim code = <Code> Public Class C1 Private Sub $$M() End Sub End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionSub) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_Function() Dim code = <Code> Public Class C1 Private Function $$M() As Integer End Sub End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_DeclareSub() Dim code = <Code> Public Class C1 Private Declare Sub $$MethodB Lib "MyDll.dll" () End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionSub) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_DeclareFunction() Dim code = <Code> Public Class C1 Private Declare Function $$MethodC Lib "MyDll.dll" () As Integer End Clas </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind__Operator() Dim code = <Code> Imports System Class C Public Shared Operator $$+(x As C, y As C) As C End Operator End Class </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub FunctionKind_Conversion() Dim code = <Code> Imports System Class C Public Shared Operator Widening $$CType(x As Integer) As C End Operator End Class </Code> TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator) End Sub #End Region #Region "MustImplement tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement1() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> TestMustImplement(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement2() Dim code = <Code> Interface I Sub $$Foo() End Interface </Code> TestMustImplement(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement3() Dim code = <Code> Class C Protected Overridable Sub $$Foo() End Sub End Class </Code> TestMustImplement(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement4() Dim code = <Code> Class C Protected Sub $$Foo() End Sub End Class </Code> TestMustImplement(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement5() Dim code = <Code> Class B Protected Overridable Sub Foo() End Sub End Class Class C Inherits B Protected Overrides Sub $$Foo() End Sub End Class </Code> TestMustImplement(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub MustImplement6() Dim code = <Code> Class B Protected Overridable Sub Foo() End Sub End Class Class C Inherits B Protected NotOverridable Overrides Sub $$Foo() End Sub End Class </Code> TestMustImplement(code, False) End Sub #End Region #Region "Name tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name1() Dim code = <Code> Class C MustOverride Sub $$Foo() End Class </Code> TestName(code, "Foo") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_NoParens() Dim code = <Code> Class C Sub $$Foo End Class </Code> TestName(code, "Foo") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_Constructor1() Dim code = <Code> Class C Sub $$New() End Sub End Class </Code> TestName(code, "New") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_Constructor2() Dim code = <Code> Class C Sub $$New() End Class </Code> TestName(code, "New") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_Operator1() Dim code = <Code> Class C Shared Narrowing Operator $$CType(i As Integer) As C End Operator End Class </Code> TestName(code, "CType") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_Operator2() Dim code = <Code> Class C Shared Narrowing Operator $$CType(i As Integer) As C End Class </Code> TestName(code, "CType") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Name_Operator3() Dim code = <Code> Class C Shared Operator $$*(i As Integer, c As C) As C End Operator End Class </Code> TestName(code, "*") End Sub #End Region #Region "OverrideKind tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub OverrideKind_Abstract() Dim code = <Code> MustInherit Class C Protected MustOverride Sub $$Foo() End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub OverrideKind_Virtual() Dim code = <Code> Class C Protected Overridable Sub $$Foo() End Sub End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub OverrideKind_Sealed() Dim code = <Code> Class C Protected NotOverridable Sub $$Foo() End Sub End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub OverrideKind_Override() Dim code = <Code> MustInherit Class B Protected MustOverride Sub Foo() End Class Class C Inherits B Protected Overrides Sub $$Foo() End Sub End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub OverrideKind_New() Dim code = <Code> MustInherit Class B Protected MustOverride Sub Foo() End Class Class C Inherits B Protected Shadows Sub $$Foo() End Sub End Class </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew) End Sub #End Region #Region "Prototype tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Prototype_UniqueSignature() Dim code = <Code> Namespace N Class C Sub $$Foo() End Sub End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "M:N.C.Foo") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Prototype_FullName() Dim code = <Code> Namespace N Class C Sub $$Foo() End Sub End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.Foo()") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Prototype_ClassName() Dim code = <Code> Namespace N Class C Sub $$Foo() End Sub End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.Foo()") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Prototype_Type1() Dim code = <Code> Namespace N Class C Sub $$Foo() End Sub End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Foo()") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Prototype_Type2() Dim code = <Code> Namespace N Class C Function $$Foo() As Integer End Function End Class End Namespace </Code> TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Foo() As Integer") End Sub #End Region #Region "Type tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Type1() Dim code = <Code> Class C Sub $$Foo() End Sub End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "Void", .AsFullName = "System.Void", .CodeTypeFullName = "System.Void", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid }) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Type2() Dim code = <Code> Class C Function $$Foo$() End Function End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "String", .AsFullName = "System.String", .CodeTypeFullName = "System.String", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString }) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Type3() Dim code = <Code> Class C Function $$Foo() As String End Function End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "String", .AsFullName = "System.String", .CodeTypeFullName = "System.String", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString }) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub Type4() Dim code = <Code> MustInherit Class C MustOverride Function $$Foo() As String End Class </Code> TestTypeProp(code, New CodeTypeRefData With { .AsString = "String", .AsFullName = "System.String", .CodeTypeFullName = "System.String", .TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString }) End Sub #End Region #Region "AddAttribute tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Sub() Dim code = <Code> Imports System Class C Sub $$M() End Sub End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Sub M() End Sub End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Function() Dim code = <Code> Imports System Class C Function $$M() As integer End Function End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Function M() As integer End Function End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Sub_MustOverride() Dim code = <Code> Imports System MustInherit Class C MustOverride Sub $$M() End Class </Code> Dim expected = <Code> Imports System MustInherit Class C &lt;Serializable()&gt; MustOverride Sub M() End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Function_MustOverride() Dim code = <Code> Imports System MustInherit Class C MustOverride Function $$M() As integer End Class </Code> Dim expected = <Code> Imports System MustInherit Class C &lt;Serializable()&gt; MustOverride Function M() As integer End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_DeclareSub() Dim code = <Code> Imports System Class C Declare Sub $$M() Lib "MyDll.dll" End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Declare Sub M() Lib "MyDll.dll" End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_DeclareFunction() Dim code = <Code> Imports System Class C Declare Function $$M() Lib "MyDll.dll" As Integer End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Declare Function M() Lib "MyDll.dll" As Integer End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Constructor() Dim code = <Code> Imports System Class C Sub $$New() End Sub End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Sub New() End Sub End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Operator() Dim code = <Code> Imports System Class C Public Shared Operator $$+(x As C, y As C) As C End Operator End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Public Shared Operator +(x As C, y As C) As C End Operator End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddAttribute_Conversion() Dim code = <Code> Imports System Class C Public Shared Operator Widening $$CType(x As Integer) As C End Operator End Class </Code> Dim expected = <Code> Imports System Class C &lt;Serializable()&gt; Public Shared Operator Widening CType(x As Integer) As C End Operator End Class </Code> TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"}) End Sub #End Region #Region "AddParameter tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddParameter1() Dim code = <Code> Class C Sub $$M() End Sub End Class </Code> Dim expected = <Code> Class C Sub M(a As Integer) End Sub End Class </Code> TestAddParameter(code, expected, New ParameterData With {.Name = "a", .Type = "Integer"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddParameter2() Dim code = <Code> Class C Sub $$M(a As Integer) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(b As String, a As Integer) End Sub End Class </Code> TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String"}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddParameter3() Dim code = <Code> Class C Sub $$M(a As Integer, b As String) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(a As Integer, c As Boolean, b As String) End Sub End Class </Code> TestAddParameter(code, expected, New ParameterData With {.Name = "c", .Type = "System.Boolean", .Position = 1}) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub AddParameter4() Dim code = <Code> Class C Sub $$M(a As Integer) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(a As Integer, b As String) End Sub End Class </Code> TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String", .Position = -1}) End Sub #End Region #Region "RemoveParamter tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RemoveParameter1() Dim code = <Code> Class C Sub $$M(a As Integer) End Sub End Class </Code> Dim expected = <Code> Class C Sub M() End Sub End Class </Code> TestRemoveChild(code, expected, "a") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RemoveParameter2() Dim code = <Code> Class C Sub $$M(a As Integer, b As String) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(a As Integer) End Sub End Class </Code> TestRemoveChild(code, expected, "b") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RemoveParameter3() Dim code = <Code> Class C Sub $$M(a As Integer, b As String) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(b As String) End Sub End Class </Code> TestRemoveChild(code, expected, "a") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub RemoveParameter4() Dim code = <Code> Class C Sub $$M(a As Integer, b As String, c As Integer) End Sub End Class </Code> Dim expected = <Code> Class C Sub M(a As Integer, c As Integer) End Sub End Class </Code> TestRemoveChild(code, expected, "b") End Sub #End Region #Region "Set Access tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess1() Dim code = <Code> Class C Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Public Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess2() Dim code = <Code> Class C Public Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Friend Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess3() Dim code = <Code> Class C Protected Friend Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Public Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess4() Dim code = <Code> Class C Public Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Protected Friend Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess5() Dim code = <Code> Class C Public Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess6() Dim code = <Code> Interface C Function $$Foo() As Integer End Class </Code> Dim expected = <Code> Interface C Function Foo() As Integer End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)()) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetAccess7() Dim code = <Code> Interface C Function $$Foo() As Integer End Class </Code> Dim expected = <Code> Interface C Function Foo() As Integer End Class </Code> TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic) End Sub #End Region #Region "Set CanOverride tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetCanOverride1() Dim code = <Code> MustInherit Class C Overridable Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C Overridable Sub Foo() End Sub End Class </Code> TestSetCanOverride(code, expected, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetCanOverride2() Dim code = <Code> MustInherit Class C Overridable Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C Sub Foo() End Sub End Class </Code> TestSetCanOverride(code, expected, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetCanOverride3() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> Dim expected = <Code> MustInherit Class C Overridable Sub Foo() End Sub End Class </Code> TestSetCanOverride(code, expected, True) End Sub #End Region #Region "Set MustImplement tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetMustImplement1() Dim code = <Code> MustInherit Class C Overridable Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C MustOverride Sub Foo() End Class </Code> TestSetMustImplement(code, expected, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetMustImplement2() Dim code = <Code> MustInherit Class C Overridable Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C Sub Foo() End Sub End Class </Code> TestSetMustImplement(code, expected, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetMustImplement3() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> Dim expected = <Code> MustInherit Class C MustOverride Sub Foo() End Class </Code> TestSetMustImplement(code, expected, True) End Sub #End Region #Region "Set IsShared tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetIsShared1() Dim code = <Code> Class C Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Shared Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetIsShared(code, expected, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetIsShared2() Dim code = <Code> Class C Shared Function $$Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> Dim expected = <Code> Class C Function Foo() As Integer Throw New NotImplementedException() End Function End Class </Code> TestSetIsShared(code, expected, False) End Sub #End Region #Region "Set Name tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetName1() Dim code = <Code> Class C Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> Class C Sub Bar() End Sub End Class </Code> TestSetName(code, expected, "Bar", NoThrow(Of String)()) End Sub #End Region #Region "Set OverrideKind tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetOverrideKind1() Dim code = <Code> MustInherit Class C Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C Sub Foo() End Sub End Class </Code> TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetOverrideKind2() Dim code = <Code> MustInherit Class C Sub $$Foo() End Sub End Class </Code> Dim expected = <Code> MustInherit Class C MustOverride Sub Foo() End Class </Code> TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetOverrideKind3() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> Dim expected = <Code> MustInherit Class C Sub Foo() End Sub End Class </Code> TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub #End Region #Region "Set Type tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType1() Dim code = <Code> Class C Sub $$Foo() Dim i As Integer End Sub End Class </Code> Dim expected = <Code> Class C Sub Foo() Dim i As Integer End Sub End Class </Code> TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef)) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType2() Dim code = <Code> Class C Sub $$Foo() Dim i As Integer End Sub End Class </Code> Dim expected = <Code> Class C Function Foo() As Integer Dim i As Integer End Function End Class </Code> TestSetTypeProp(code, expected, "System.Int32") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType3() Dim code = <Code> Class C Function $$Foo() As System.Int32 Dim i As Integer End Function End Class </Code> Dim expected = <Code> Class C Function Foo() As String Dim i As Integer End Function End Class </Code> TestSetTypeProp(code, expected, "System.String") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType4() Dim code = <Code> Class C Function $$Foo() As System.Int32 Dim i As Integer End Function End Class </Code> Dim expected = <Code> Class C Sub Foo() Dim i As Integer End Sub End Class </Code> TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef)) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType5() Dim code = <Code> MustInherit Class C MustOverride Function $$Foo() As System.Int32 End Class </Code> Dim expected = <Code> MustInherit Class C MustOverride Sub Foo() End Class </Code> TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef)) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType6() Dim code = <Code> MustInherit Class C MustOverride Sub $$Foo() End Class </Code> Dim expected = <Code> MustInherit Class C MustOverride Function Foo() As Integer End Class </Code> TestSetTypeProp(code, expected, "System.Int32") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType7() Dim code = <Code> Class C Sub $$New() End Sub End Class </Code> Dim expected = <Code> Class C Sub New() End Sub End Class </Code> TestSetTypeProp(code, expected, "System.Int32") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub SetType8() Dim code = <Code> Class C Shared Narrowing Operator $$CType(i As Integer) As C End Operator End Class </Code> Dim expected = <Code> Class C Shared Narrowing Operator CType(i As Integer) As C End Operator End Class </Code> TestSetTypeProp(code, expected, "System.Int32") End Sub #End Region #Region "PartialMethodExtender" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsPartial1() Dim code = <Code> Partial Public Class Class2 Public Sub $$M(i As Integer) End Sub Partial Private Sub M() End Sub Private Sub M() End Sub End Class </Code> TestPartialMethodExtender_IsPartial(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsPartial2() Dim code = <Code> Partial Public Class Class2 Public Sub M(i As Integer) End Sub Partial Private Sub $$M() End Sub Private Sub M() End Sub End Class </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsPartial3() Dim code = <Code> Partial Public Class Class2 Public Sub M(i As Integer) End Sub Partial Private Sub M() End Sub Private Sub $$M() End Sub End Class </Code> TestPartialMethodExtender_IsPartial(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsDeclaration1() Dim code = <Code> Partial Public Class Class2 Public Sub $$M(i As Integer) End Sub Partial Private Sub M() End Sub Private Sub M() End Sub End Class </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsDeclaration2() Dim code = <Code> Partial Public Class Class2 Public Sub M(i As Integer) End Sub Partial Private Sub $$M() End Sub Private Sub M() End Sub End Class </Code> TestPartialMethodExtender_IsDeclaration(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub PartialMethodExtender_IsDeclaration3() Dim code = <Code> Partial Public Class Class2 Public Sub M(i As Integer) End Sub Partial Private Sub M() End Sub Private Sub $$M() End Sub End Class </Code> TestPartialMethodExtender_IsDeclaration(code, False) End Sub #End Region #Region "Overloads Tests" <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub IsOverloaded1() Dim code = <Code> Class C Sub $$Foo(x As C) End Sub End Class </Code> TestIsOverloaded(code, False) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub IsOverloaded2() Dim code = <Code> Class C Sub Foo() End Sub Sub $$Foo(x As C) End Sub End Class </Code> TestIsOverloaded(code, True) End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads1() Dim code = <Code> Class C Sub $$Foo() End Sub Sub Foo(x As C) End Sub End Class </Code> TestOverloadsUniqueSignatures(code, "M:C.Foo", "M:C.Foo(C)") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads2() Dim code = <Code> Class C Sub $$Foo() End Sub End Class </Code> TestOverloadsUniqueSignatures(code, "M:C.Foo") End Sub <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverloads3() Dim code = <Code> Class C Shared Operator $$*(i As Integer, c As C) As C End Operator End Class </Code> TestOverloadsUniqueSignatures(code, "M:C.op_Multiply(System.Int32,C)") End Sub #End Region #Region "Parameter name tests" <WorkItem(1147885)> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters() Dim code = <Code> Class C Sub $$M1([integer] As Integer) End Sub End Class </Code> TestAllParameterNames(code, "[integer]") End Sub <WorkItem(1147885)> <ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters_2() Dim code = <Code> Class C Sub $$M1([integer] As Integer, [string] as String) End Sub End Class </Code> TestAllParameterNames(code, "[integer]", "[string]") End Sub #End Region Private Function GetPartialMethodExtender(codeElement As EnvDTE80.CodeFunction2) As IVBPartialMethodExtender Return CType(codeElement.Extender(ExtenderNames.VBPartialMethodExtender), IVBPartialMethodExtender) End Function Protected Overrides Function PartialMethodExtender_GetIsPartial(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsPartial End Function Protected Overrides Function PartialMethodExtender_GetIsDeclaration(codeElement As EnvDTE80.CodeFunction2) As Boolean Return GetPartialMethodExtender(codeElement).IsDeclaration End Function Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property End Class End Namespace
dsplaisted/roslyn
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeFunctionTests.vb
Visual Basic
apache-2.0
66,803
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.ReplacePropertyWithMethods Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeRefactorings.ReplaceMethodWithProperty <ExportLanguageService(GetType(IReplacePropertyWithMethodsService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicReplacePropertyWithMethods Inherits AbstractReplacePropertyWithMethodsService(Of IdentifierNameSyntax, ExpressionSyntax, StatementSyntax) Public Overrides Function GetPropertyDeclaration(token As SyntaxToken) As SyntaxNode Dim containingProperty = token.Parent.FirstAncestorOrSelf(Of PropertyStatementSyntax) If containingProperty Is Nothing Then Return Nothing End If ' a parameterized property can be trivially converted to a method. If containingProperty.ParameterList IsNot Nothing Then Return Nothing End If Dim start = If(containingProperty.AttributeLists.Count > 0, containingProperty.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart, containingProperty.SpanStart) ' Offer this refactoring anywhere in the signature of the property. Dim position = token.SpanStart If position < start Then Return Nothing End If If containingProperty.HasReturnType() AndAlso position > containingProperty.GetReturnType().Span.End Then Return Nothing End If Return containingProperty End Function Public Overrides Function GetReplacementMembersAsync( document As Document, [property] As IPropertySymbol, propertyDeclarationNode As SyntaxNode, propertyBackingField As IFieldSymbol, desiredGetMethodName As String, desiredSetMethodName As String, cancellationToken As CancellationToken) As Task(Of IList(Of SyntaxNode)) Dim propertyStatement = TryCast(propertyDeclarationNode, PropertyStatementSyntax) If propertyStatement Is Nothing Then Return Task.FromResult(SpecializedCollections.EmptyList(Of SyntaxNode)) End If Return Task.FromResult(ConvertPropertyToMembers( SyntaxGenerator.GetGenerator(document), [property], propertyStatement, propertyBackingField, desiredGetMethodName, desiredSetMethodName, cancellationToken)) End Function Private Function ConvertPropertyToMembers( generator As SyntaxGenerator, [property] As IPropertySymbol, propertyStatement As PropertyStatementSyntax, propertyBackingField As IFieldSymbol, desiredGetMethodName As String, desiredSetMethodName As String, cancellationToken As CancellationToken) As IList(Of SyntaxNode) Dim result = New List(Of SyntaxNode)() If propertyBackingField IsNot Nothing Then Dim initializer = propertyStatement.Initializer?.Value result.Add(generator.FieldDeclaration(propertyBackingField, initializer)) End If Dim getMethod = [property].GetMethod If getMethod IsNot Nothing Then result.Add(GetGetMethod( generator, propertyStatement, propertyBackingField, getMethod, desiredGetMethodName, copyLeadingTrivia:=True, cancellationToken:=cancellationToken)) End If Dim setMethod = [property].SetMethod If setMethod IsNot Nothing Then result.Add(GetSetMethod( generator, propertyStatement, propertyBackingField, setMethod, desiredSetMethodName, copyLeadingTrivia:=getMethod Is Nothing, cancellationToken:=cancellationToken)) End If Return result End Function Private Function GetGetMethod( generator As SyntaxGenerator, propertyStatement As PropertyStatementSyntax, propertyBackingField As IFieldSymbol, getMethod As IMethodSymbol, desiredGetMethodName As String, copyLeadingTrivia As Boolean, cancellationToken As CancellationToken) As SyntaxNode Dim statements = New List(Of SyntaxNode)() Dim getAccessorDeclaration = If(getMethod.DeclaringSyntaxReferences.Length = 0, Nothing, TryCast(getMethod.DeclaringSyntaxReferences(0).GetSyntax(cancellationToken), AccessorStatementSyntax)) If TypeOf getAccessorDeclaration?.Parent Is AccessorBlockSyntax Then Dim block = DirectCast(getAccessorDeclaration.Parent, AccessorBlockSyntax) statements.AddRange(block.Statements.Select(AddressOf WithFormattingAnnotation)) ElseIf propertyBackingField IsNot Nothing Then Dim fieldReference = GetFieldReference(generator, propertyBackingField) statements.Add(generator.ReturnStatement(fieldReference)) End If Dim methodDeclaration = generator.MethodDeclaration(getMethod, desiredGetMethodName, statements) methodDeclaration = CopyLeadingTriviaOver(propertyStatement, methodDeclaration, copyLeadingTrivia) Return methodDeclaration End Function Private Shared Function WithFormattingAnnotation(statement As StatementSyntax) As StatementSyntax Return statement.WithAdditionalAnnotations(Formatter.Annotation) End Function Private Function GetSetMethod( generator As SyntaxGenerator, propertyStatement As PropertyStatementSyntax, propertyBackingField As IFieldSymbol, setMethod As IMethodSymbol, desiredSetMethodName As String, copyLeadingTrivia As Boolean, cancellationToken As CancellationToken) As SyntaxNode Dim statements = New List(Of SyntaxNode)() Dim setAccessorDeclaration = If(setMethod.DeclaringSyntaxReferences.Length = 0, Nothing, TryCast(setMethod.DeclaringSyntaxReferences(0).GetSyntax(cancellationToken), AccessorStatementSyntax)) If TypeOf setAccessorDeclaration?.Parent Is AccessorBlockSyntax Then Dim block = DirectCast(setAccessorDeclaration.Parent, AccessorBlockSyntax) statements.AddRange(block.Statements.Select(AddressOf WithFormattingAnnotation)) ElseIf propertyBackingField IsNot Nothing Then Dim fieldReference = GetFieldReference(generator, propertyBackingField) statements.Add(generator.AssignmentStatement( fieldReference, generator.IdentifierName(setMethod.Parameters(0).Name))) End If Dim methodDeclaration = generator.MethodDeclaration(setMethod, desiredSetMethodName, statements) methodDeclaration = CopyLeadingTriviaOver(propertyStatement, methodDeclaration, copyLeadingTrivia) Return methodDeclaration End Function Private Function CopyLeadingTriviaOver(propertyStatement As PropertyStatementSyntax, methodDeclaration As SyntaxNode, copyLeadingTrivia As Boolean) As SyntaxNode If copyLeadingTrivia Then Return methodDeclaration.WithLeadingTrivia( propertyStatement.GetLeadingTrivia().Select(AddressOf ConvertTrivia)) End If Return methodDeclaration End Function Private Function ConvertTrivia(trivia As SyntaxTrivia) As SyntaxTrivia If trivia.Kind() = SyntaxKind.DocumentationCommentTrivia Then Dim converted = ConvertValueToReturnsRewriter.instance.Visit(trivia.GetStructure()) Return SyntaxFactory.Trivia(DirectCast(converted, StructuredTriviaSyntax)) End If Return trivia End Function Public Overrides Function GetPropertyNodeToReplace(propertyDeclaration As SyntaxNode) As SyntaxNode ' In VB we'll have the property statement. If that is parented by a ' property block, we'll want to replace that instead. Otherwise we ' just replace the property statement itself Return If(propertyDeclaration.IsParentKind(SyntaxKind.PropertyBlock), propertyDeclaration.Parent, propertyDeclaration) End Function Protected Overrides Function UnwrapCompoundAssignment(compoundAssignment As SyntaxNode, readExpression As ExpressionSyntax) As ExpressionSyntax Throw New InvalidOperationException("Compound assignments don't exist in VB") End Function End Class End Namespace
akrisiun/roslyn
src/Features/VisualBasic/Portable/ReplacePropertyWithMethods/VisualBasicReplacePropertyWithMethods.vb
Visual Basic
apache-2.0
9,555
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.261 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.EntityFramework_CodeFirst2.My.MySettings Get Return Global.EntityFramework_CodeFirst2.My.MySettings.Default End Get End Property End Module End Namespace
RocketSoftware/multivalue-lab
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniVerse/EntityFramework_CodeFirst2/My Project/Settings.Designer.vb
Visual Basic
mit
2,956
Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Refactoring <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Public Class ParameterRefactoryAnalyzer Inherits DiagnosticAnalyzer Friend Const Title = "You should use a class." Friend Const MessageFormat = "When the method has more than three parameters, use a class." Friend Const Category = SupportedCategories.Refactoring Friend Shared Rule As New DiagnosticDescriptor( DiagnosticId.ParameterRefactory.ToDiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Hidden, isEnabledByDefault:=True, helpLinkUri:=HelpLink.ForDiagnostic(DiagnosticId.ParameterRefactory) ) Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) Get Return ImmutableArray.Create(Rule) End Get End Property Public Overrides Sub Initialize(context As AnalysisContext) context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock) End Sub Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext) If (context.IsGenerated()) Then Return Dim method = DirectCast(context.Node, MethodBlockSyntax) If method.SubOrFunctionStatement.Modifiers.Any(SyntaxKind.FriendKeyword) Then Exit Sub ' Check for extension method For Each attributeList In method.SubOrFunctionStatement.AttributeLists For Each attribute In attributeList.Attributes If attribute.Name.ToString().Contains("Extension") Then Exit Sub Next Next Dim contentParameter = method.SubOrFunctionStatement.ParameterList If contentParameter Is Nothing OrElse contentParameter.Parameters.Count <= 3 Then Exit Sub If method.Statements.Any() Then Exit Sub For Each parameter In contentParameter.Parameters For Each modifier In parameter.Modifiers If modifier.IsKind(SyntaxKind.ByRefKeyword) OrElse modifier.IsKind(SyntaxKind.ParamArrayKeyword) Then Exit Sub End If Next Next Dim diag = Diagnostic.Create(Rule, contentParameter.GetLocation()) context.ReportDiagnostic(diag) End Sub End Class End Namespace
thorgeirk11/code-cracker
src/VisualBasic/CodeCracker/Refactoring/ParameterRefactoryAnalyzer.vb
Visual Basic
apache-2.0
2,686
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Classification Imports Microsoft.CodeAnalysis.Classification.Classifiers Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers Namespace Microsoft.CodeAnalysis.VisualBasic.Classification <ExportLanguageService(GetType(ISyntaxClassificationService), LanguageNames.VisualBasic), [Shared]> Partial Friend Class VisualBasicSyntaxClassificationService Inherits AbstractSyntaxClassificationService Private Shared ReadOnly s_defaultSyntaxClassifiers As ImmutableArray(Of ISyntaxClassifier) = ImmutableArray.Create(Of ISyntaxClassifier)( New NameSyntaxClassifier(), New ImportAliasClauseSyntaxClassifier(), New IdentifierNameSyntaxClassifier()) Public Overrides Function GetDefaultSyntaxClassifiers() As ImmutableArray(Of ISyntaxClassifier) Return s_defaultSyntaxClassifiers End Function Public Overrides Sub AddLexicalClassifications(text As SourceText, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) ClassificationHelpers.AddLexicalClassifications(text, textSpan, result, cancellationToken) End Sub Public Overrides Sub AddSyntacticClassifications(syntaxTree As SyntaxTree, textSpan As TextSpan, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken) Dim root = syntaxTree.GetRoot(cancellationToken) Worker.CollectClassifiedSpans(root, textSpan, result, cancellationToken) End Sub Public Overrides Function FixClassification(text As SourceText, classifiedSpan As ClassifiedSpan) As ClassifiedSpan Return ClassificationHelpers.AdjustStaleClassification(text, classifiedSpan) End Function End Class End Namespace
pdelvo/roslyn
src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/VisualBasicSyntaxClassificationService.vb
Visual Basic
apache-2.0
2,230
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Threading Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.DiaSymReader Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class DteeTests Inherits ExpressionCompilerTestBase Private Const s_dteeEntryPointSource = " Imports System.Collections Class HostProc Sub BreakForDebugger() End Sub End Class " Private Const s_dteeEntryPointName = "HostProc.BreakForDebugger" <Fact> Public Sub IsDteeEntryPoint() Const source = " Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class " Dim comp = CreateCompilationWithMscorlib({source}) Dim [global] = comp.GlobalNamespace Dim m1 = [global].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [global].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_Namespace() Const source = " Namespace N Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib({source}) Dim [namespace] = comp.GlobalNamespace.GetMember(Of NamespaceSymbol)("N") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_CaseSensitive() Const source = " Namespace N1 Class HostProc Sub breakfordebugger() End Sub End Class Class AppDomain Sub executeassembly() End Sub End Class End Namespace Namespace N2 Class hostproc Sub BreakForDebugger() End Sub End Class Class appdomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib({source}) Dim [global] = comp.GlobalNamespace Dim [namespace] = [global].GetMember(Of NamespaceSymbol)("N1") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) [namespace] = [global].GetMember(Of NamespaceSymbol)("N2") m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub DteeEntryPointImportsIgnored() Dim comp = CreateCompilationWithMscorlib({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim compModuleInstance = GetModuleInstance(comp) Dim corlibModuleReference = MscorlibRef.ToModuleInstance(Nothing, Nothing) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create(compModuleInstance, corlibModuleReference)) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(MakeDummySyntax()) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.True(typesAndNamespaces.IsDefault) Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub <Fact> Public Sub ImportStrings_DefaultNamespaces() Dim source1 = " Class C1 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim source2 = " Class C2 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim comp1 = CreateCompilationWithMscorlib({source1}, options:=TestOptions.DebugDll.WithRootNamespace("root1"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = GetModuleInstance(comp1) Dim comp2 = CreateCompilationWithMscorlib({source2}, options:=TestOptions.DebugDll.WithRootNamespace("root2"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = GetModuleInstance(comp2) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "root1", "root2") End Sub <Fact> Public Sub ImportStrings_ModuleNamespaces() Dim source1 = " Namespace N1 Module M End Module End Namespace Namespace N2 Namespace N3 Module M End Module End Namespace End Namespace Namespace N4 Class C End Class End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 End Module End Namespace Namespace N5 Namespace N6 Module M End Module End Namespace End Namespace Namespace N7 Class C End Class End Namespace " Dim comp1 = CreateCompilationWithMscorlib({source1}, {MsvbRef}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim compModuleInstance1 = GetModuleInstance(comp1) Dim comp2 = CreateCompilationWithMscorlib({source2}, {MsvbRef}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim compModuleInstance2 = GetModuleInstance(comp2) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N1", "N2.N3", "N5.N6") End Sub <Fact> Public Sub ImportStrings_NoMethods() Dim comp = CreateCompilationWithMscorlib({""}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance = GetModuleInstance(comp) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( compModuleInstance, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) ' Since there are no methods in the assembly, there is no import custom debug info, so we ' have no way to find the root namespace. Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportStrings_IgnoreAssemblyWithoutPdb() Dim source1 = " Namespace N1 Module M End Module End Namespace " Dim source2 = " Namespace N2 Module M End Module End Namespace " Dim comp1 = CreateCompilationWithMscorlib({source1}, {MsvbRef}, options:=TestOptions.ReleaseDll, assemblyName:=GetUniqueName()) Dim compModuleInstance1 = GetModuleInstance(comp1) Dim comp2 = CreateCompilationWithMscorlib({source2}, {MsvbRef}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim compModuleInstance2 = GetModuleInstance(comp2) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N2") End Sub <Fact> Public Sub FalseModule_Nested() ' NOTE: VB only allows top-level module types. Dim ilSource = " .assembly 'IL' {} .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89) .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { } .class public auto ansi N1.Outer extends [mscorlib]System.Object { .class auto ansi nested public sealed Inner extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.Outer " Dim ilModuleInstance = GetModuleInstanceForIL(ilSource) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( ilModuleInstance, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Generic() ' NOTE: VB only allows non-generic module types. Dim ilSource = " .assembly 'IL' {} .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89) .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { } .class public auto ansi sealed N1.M`1<T> extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class M " Dim ilModuleInstance = GetModuleInstanceForIL(ilSource) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( ilModuleInstance, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Interface() ' NOTE: VB only allows non-interface module types. Dim ilSource = " .assembly 'IL' {} .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89) .ver 4:0:0:0 } .assembly extern Microsoft.VisualBasic { } .class interface private abstract auto ansi I { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class I " Dim ilModuleInstance = GetModuleInstanceForIL(ilSource) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( ilModuleInstance, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportSymbols() Dim source1 = " Namespace N1 Module M Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N2 Module M End Module End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N3 Module M End Module End Namespace " Dim dteeComp = CreateCompilationWithMscorlib({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim dteeModuleInstance = GetModuleInstance(dteeComp) Dim comp1 = CreateCompilationWithMscorlib({source1}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = GetModuleInstance(comp1) Dim comp2 = CreateCompilationWithMscorlib({source2}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = GetModuleInstance(comp2) Dim runtimeInstance = CreateRuntimeInstance(ImmutableArray.Create( dteeModuleInstance, compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(Nothing, Nothing), MsvbRef.ToModuleInstance(Nothing, Nothing))) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(MakeDummySyntax()) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.Null(aliases) Assert.Null(xmlNamespaces) AssertEx.SetEqual(typesAndNamespaces.Select(Function(tn) tn.NamespaceOrType.ToTestDisplayString()), "root", "root.N1", "root.N2", "root.N3") End Sub Private Shared Function MakeDummySyntax() As Syntax.ExecutableStatementSyntax Return VisualBasicSyntaxTree.ParseText("?Nothing").GetRoot().DescendantNodes().OfType(Of Syntax.ExecutableStatementSyntax)().Single() End Function Private Shared Function MakeLazyAssemblyReaders(runtimeInstance As RuntimeInstance) As Lazy(Of ImmutableArray(Of AssemblyReaders)) Return New Lazy(Of ImmutableArray(Of AssemblyReaders))( Function() MakeAssemblyReaders(runtimeInstance), LazyThreadSafetyMode.None) End Function Private Shared Function MakeAssemblyReaders(runtimeInstance As RuntimeInstance) As ImmutableArray(Of AssemblyReaders) Return ImmutableArray.CreateRange(runtimeInstance.Modules. Where(Function(instance) instance.SymReader IsNot Nothing). Select(Function(instance) New AssemblyReaders(instance.MetadataReader, instance.SymReader))) End Function Private Shared Function GetModuleInstance(comp As VisualBasicCompilation) As ModuleInstance Dim makePdb = comp.Options.OptimizationLevel = OptimizationLevel.Debug Dim peBytes As Byte() Dim pdbBytes As Byte() Using pdbStream = If(makePdb, New MemoryStream(), Nothing) Using peStream As New MemoryStream() Dim emitResult = comp.Emit(peStream, pdbStream) AssertNoErrors(emitResult.Diagnostics) Assert.True(emitResult.Success) peBytes = peStream.ToArray() pdbBytes = pdbStream?.ToArray() End Using End Using Assert.Equal(makePdb, pdbBytes IsNot Nothing) Dim compRef = AssemblyMetadata.CreateFromImage(peBytes).GetReference() Return compRef.ToModuleInstance(peBytes, If(makePdb, New SymReader(pdbBytes), Nothing)) End Function Private Shared Function GetModuleInstanceForIL(ilSource As String) As ModuleInstance Dim peBytes As ImmutableArray(Of Byte) = Nothing Dim pdbBytes As ImmutableArray(Of Byte) = Nothing EmitILToArray(ilSource, appendDefaultHeader:=False, includePdb:=True, assemblyBytes:=peBytes, pdbBytes:=pdbBytes) Dim compRef = AssemblyMetadata.CreateFromImage(peBytes).GetReference() Return compRef.ToModuleInstance(peBytes.ToArray(), New SymReader(pdbBytes.ToArray())) End Function Private Shared Sub CheckDteeMethodDebugInfo(methodDebugInfo As MethodDebugInfo, ParamArray namespaceNames As String()) Assert.Equal("", methodDebugInfo.DefaultNamespaceName) Dim importRecordGroups = methodDebugInfo.ImportRecordGroups Assert.Equal(2, importRecordGroups.Length) Dim projectLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(0) Dim fileLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(1) Assert.Empty(fileLevelImportRecords) AssertEx.All(projectLevelImportRecords, Function(record) TypeOf record Is NativeImportRecord) AssertEx.All(projectLevelImportRecords, Function(record) DirectCast(record, NativeImportRecord).ExternAlias Is Nothing) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetKind = ImportTargetKind.Namespace) AssertEx.All(projectLevelImportRecords, Function(record) record.Alias Is Nothing) AssertEx.SetEqual(projectLevelImportRecords.Select(Function(record) record.TargetString), namespaceNames) End Sub End Class End Namespace
REALTOBIZ/roslyn
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.vb
Visual Basic
apache-2.0
20,192
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class Lambda_AnonymousDelegateInference Inherits BasicTestBase <Fact> Public Sub Test1() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x = Function(y) y System.Console.WriteLine(x.GetType()) x = Function(y) y ' No inference here, using delegate type from x. System.Console.WriteLine(x.GetType()) Dim x2 As Object = Function(y) y System.Console.WriteLine(x2.GetType()) Dim x3 = Function() Function() "a" System.Console.WriteLine(x3.GetType()) Dim x4 = Function() Return Function() 2.5 End Function System.Console.WriteLine(x4.GetType()) Dim x5 = DirectCast(Function() Date.Now, System.Delegate) System.Console.WriteLine(x5.GetType()) Dim x6 = TryCast(Function() Decimal.MaxValue, System.MulticastDelegate) System.Console.WriteLine(x6.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_0`2[System.Object,System.Object] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.String]] VB$AnonymousDelegate_1`1[VB$AnonymousDelegate_1`1[System.Double]] VB$AnonymousDelegate_1`1[System.DateTime] VB$AnonymousDelegate_1`1[System.Decimal] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x = Function(y) y ~ BC42020: Variable declaration without an 'As' clause; type of Object assumed. Dim x2 As Object = Function(y) y ~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x = Function(y) y ~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x2 As Object = Function(y) y ~ </expected>) End Sub <Fact> Public Sub Test2() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim x1 = Function() Unknown 'BIND1:"x1" Dim x2 = Function() : 'BIND2:"x2" Dim x3 = Function() 'BIND3:"x3" Return Unknown '3 End Function Dim x4 = Function() 'BIND4:"x4" Unknown() End Function '4 Dim x5 = Function() AddressOf Main 'BIND5:"x5" Dim x6 = Function() 'BIND6:"x6" Return AddressOf Main '6 End Function End Sub Delegate Sub D1(x As System.ArgIterator) Sub Test(y As System.ArgIterator) Dim x7 = Function() y 'BIND7:"x7" Dim x8 = Function() 'BIND8:"x8" Return y '8 End Function Dim x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ' The following Dim shouldn't produce any errors. Dim x10 As D1 = Sub(x As System.ArgIterator) System.Console.WriteLine() Dim x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) For Each strict In {OptionStrict.Off, OptionStrict.On, OptionStrict.Custom} compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(strict)) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> <![CDATA[ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Dim x1 = Function() Unknown 'BIND1:"x1" ~~~~~~~ BC30201: Expression expected. Dim x2 = Function() : 'BIND2:"x2" ~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Return Unknown '3 ~~~~~~~ BC30451: 'Unknown' is not declared. It may be inaccessible due to its protection level. Unknown() ~~~~~~~ BC42105: Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. End Function '4 ~~~~~~~~~~~~ BC30581: 'AddressOf' expression cannot be converted to 'Object' because 'Object' is not a delegate type. Dim x5 = Function() AddressOf Main 'BIND5:"x5" ~~~~~~~~~~~~~~ BC36751: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x6 = Function() 'BIND6:"x6" ~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x7 = Function() y 'BIND7:"x7" ~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x8 = Function() 'BIND8:"x8" ~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x9 = Sub(x As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x11 = Sub(x() As System.ArgIterator) System.Console.WriteLine() ~~~~~~~~~~~~~~~~~~ ]]> </expected>) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 1) Dim x1 = DirectCast(semanticModel.GetDeclaredSymbol(node1), LocalSymbol) Assert.Equal("x1", x1.Name) Assert.Equal("Function <generated method>() As ?", x1.Type.ToTestDisplayString) Assert.True(x1.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x1.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node2 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 2) Dim x2 = DirectCast(semanticModel.GetDeclaredSymbol(node2), LocalSymbol) Assert.Equal("x2", x2.Name) Assert.Equal("Function <generated method>() As ?", x2.Type.ToTestDisplayString) Assert.True(x2.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x2.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node3 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 3) Dim x3 = DirectCast(semanticModel.GetDeclaredSymbol(node3), LocalSymbol) Assert.Equal("x3", x3.Name) Assert.Equal("Function <generated method>() As ?", x3.Type.ToTestDisplayString) Assert.True(x3.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x3.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node4 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 4) Dim x4 = DirectCast(semanticModel.GetDeclaredSymbol(node4), LocalSymbol) Assert.Equal("x4", x4.Name) Assert.Equal("Function <generated method>() As ?", x4.Type.ToTestDisplayString) Assert.True(x4.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x4.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node5 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 5) Dim x5 = DirectCast(semanticModel.GetDeclaredSymbol(node5), LocalSymbol) Assert.Equal("x5", x5.Name) Assert.Equal("Function <generated method>() As System.Object", x5.Type.ToTestDisplayString) Assert.True(x5.Type.IsAnonymousType) Assert.True(DirectCast(x5.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType.IsObjectType()) End If If True Then Dim node6 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 6) Dim x6 = DirectCast(semanticModel.GetDeclaredSymbol(node6), LocalSymbol) Assert.Equal("x6", x6.Name) Assert.Equal("Function <generated method>() As ?", x6.Type.ToTestDisplayString) Assert.True(x6.Type.IsAnonymousType) Assert.Same(LambdaSymbol.ReturnTypeIsUnknown, DirectCast(x6.Type, NamedTypeSymbol).DelegateInvokeMethod.ReturnType) End If If True Then Dim node7 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 7) Dim x7 = DirectCast(semanticModel.GetDeclaredSymbol(node7), LocalSymbol) Assert.Equal("x7", x7.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x7.Type.ToTestDisplayString) Assert.True(x7.Type.IsAnonymousType) End If If True Then Dim node8 As ModifiedIdentifierSyntax = CompilationUtils.FindBindingText(Of ModifiedIdentifierSyntax)(compilation, "a.vb", 8) Dim x8 = DirectCast(semanticModel.GetDeclaredSymbol(node8), LocalSymbol) Assert.Equal("x8", x8.Name) Assert.Equal("Function <generated method>() As System.ArgIterator", x8.Type.ToTestDisplayString) Assert.True(x8.Type.IsAnonymousType) End If Next End Sub <Fact> Public Sub Test3() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Interface I1 End Interface Interface I2 End Interface Interface I3 Inherits I2, I1 End Interface Interface I4 Inherits I2, I1 End Interface Module Program Sub Main() Dim x1 = Function(y As Integer) If y > 0 Then Return New System.Collections.Generic.Dictionary(Of Integer, Integer) Else Return New System.Collections.Generic.Dictionary(Of Byte, Byte) End If End Function System.Console.WriteLine(x1.GetType()) Dim x2 = Function(y1 As I3, y2 As I4) If True Then Return y1 Else Return y2 End Function System.Console.WriteLine(x2.GetType()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.Custom)) Assert.Equal(OptionStrict.Custom, compilation.Options.OptionStrict) CompileAndVerify(compilation, <![CDATA[ VB$AnonymousDelegate_0`2[System.Int32,System.Object] VB$AnonymousDelegate_1`3[I3,I4,System.Object] ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC42021: Cannot infer a return type; 'Object' assumed. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC42021: Cannot infer a return type because more than one type is possible; 'Object' assumed. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseExe.WithOptionStrict(OptionStrict.On)) Assert.Equal(OptionStrict.On, compilation.Options.OptionStrict) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC36916: Cannot infer a return type. Consider adding an 'As' clause to specify the return type. Dim x1 = Function(y As Integer) ~~~~~~~~~~~~~~~~~~~~~~ BC36734: Cannot infer a return type because more than one type is possible. Consider adding an 'As' clause to specify the return type. Dim x2 = Function(y1 As I3, y2 As I4) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub Test4() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Option Strict ON Module Program Sub Main() End Sub Sub Test(y As System.ArgIterator) Dim x7 = Function(x) y Dim x8 = Function(x) Return y '8 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x7 = Function(x) y ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x7 = Function(x) y ~ BC31396: 'ArgIterator' cannot be made nullable, and cannot be used as the data type of an array element, field, anonymous type member, type argument, 'ByRef' parameter, or return statement. Dim x8 = Function(x) ~~~~~~~~~~~ BC36642: Option Strict On requires each lambda expression parameter to be declared with an 'As' clause if its type cannot be inferred. Dim x8 = Function(x) ~ </expected>) End Sub <Fact()> Public Sub Test5() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Call (Sub(x As Integer) System.Console.WriteLine(x))(1) 'BIND1:"Sub(x As Integer)" Call Sub(x As Integer) 'BIND2:"Sub(x As Integer)" System.Console.WriteLine(x) End Sub(2) Dim x3 As Integer = Function() As Integer 'BIND3:"Function() As Integer" Return 3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim tree As SyntaxTree = (From t In compilation.SyntaxTrees Where t.FilePath = "a.vb").Single() Dim semanticModel = compilation.GetSemanticModel(tree) If True Then Dim node1 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 1) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node1.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node1.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node2 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 2) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node2.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Sub <generated method>(x As System.Int32)", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node2.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If If True Then Dim node3 As LambdaHeaderSyntax = CompilationUtils.FindBindingText(Of LambdaHeaderSyntax)(compilation, "a.vb", 3) Dim typeInfo As TypeInfo = semanticModel.GetTypeInfo(DirectCast(node3.Parent, LambdaExpressionSyntax)) Assert.Null(typeInfo.Type) Assert.Equal("Function <generated method>() As System.Int32", typeInfo.ConvertedType.ToTestDisplayString()) Dim conv = semanticModel.GetConversion(node3.Parent) Assert.Equal("Widening, Lambda", conv.Kind.ToString()) Assert.True(conv.Exists) End If Dim verifier = CompileAndVerify(compilation, expectedOutput:="1" & vbCrLf & "2" & vbCrLf & "3") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 131 (0x83) .maxstack 2 IL_0000: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "Program._Closure$__.$I0-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0013: ldftn "Sub Program._Closure$__._Lambda$__0-0(Integer)" IL_0019: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "Program._Closure$__.$I0-0 As <generated method>" IL_0024: ldc.i4.1 IL_0025: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_002a: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_002f: brfalse.s IL_0038 IL_0031: ldsfld "Program._Closure$__.$I0-1 As <generated method>" IL_0036: br.s IL_004e IL_0038: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_003d: ldftn "Sub Program._Closure$__._Lambda$__0-1(Integer)" IL_0043: newobj "Sub VB$AnonymousDelegate_0(Of Integer)..ctor(Object, System.IntPtr)" IL_0048: dup IL_0049: stsfld "Program._Closure$__.$I0-1 As <generated method>" IL_004e: ldc.i4.2 IL_004f: callvirt "Sub VB$AnonymousDelegate_0(Of Integer).Invoke(Integer)" IL_0054: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0059: brfalse.s IL_0062 IL_005b: ldsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0060: br.s IL_0078 IL_0062: ldsfld "Program._Closure$__.$I As Program._Closure$__" IL_0067: ldftn "Function Program._Closure$__._Lambda$__0-2() As Integer" IL_006d: newobj "Sub VB$AnonymousDelegate_1(Of Integer)..ctor(Object, System.IntPtr)" IL_0072: dup IL_0073: stsfld "Program._Closure$__.$I0-2 As <generated method>" IL_0078: callvirt "Function VB$AnonymousDelegate_1(Of Integer).Invoke() As Integer" IL_007d: call "Sub System.Console.WriteLine(Integer)" IL_0082: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <Fact()> Public Sub Test6() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Module Program Sub Main() Dim y1 as Integer = 2 Dim y2 as Integer = 3 Dim y3 as Integer = 4 Call (Sub(x As Integer) System.Console.WriteLine(x+y1))(1) Call Sub(x As Integer) System.Console.WriteLine(x+y2) End Sub(2) Dim x3 As Integer = Function() As Integer Return 3+y3 End Function.Invoke() System.Console.WriteLine(x3) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) Assert.Equal(OptionStrict.Off, compilation.Options.OptionStrict) Dim verifier = CompileAndVerify(compilation, expectedOutput:="3" & vbCrLf & "5" & vbCrLf & "7") CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) verifier.VerifyIL("Program.Main", <![CDATA[ { // Code size 51 (0x33) .maxstack 3 IL_0000: newobj "Sub Program._Closure$__0-0..ctor()" IL_0005: dup IL_0006: ldc.i4.2 IL_0007: stfld "Program._Closure$__0-0.$VB$Local_y1 As Integer" IL_000c: dup IL_000d: ldc.i4.3 IL_000e: stfld "Program._Closure$__0-0.$VB$Local_y2 As Integer" IL_0013: dup IL_0014: ldc.i4.4 IL_0015: stfld "Program._Closure$__0-0.$VB$Local_y3 As Integer" IL_001a: dup IL_001b: ldc.i4.1 IL_001c: callvirt "Sub Program._Closure$__0-0._Lambda$__0(Integer)" IL_0021: dup IL_0022: ldc.i4.2 IL_0023: callvirt "Sub Program._Closure$__0-0._Lambda$__1(Integer)" IL_0028: callvirt "Function Program._Closure$__0-0._Lambda$__2() As Integer" IL_002d: call "Sub System.Console.WriteLine(Integer)" IL_0032: ret } ]]>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) End Sub <WorkItem(543286, "DevDiv")> <Fact()> Public Sub AnonDelegateReturningLambdaWithGenericType() Dim compilationDef = <compilation name="LambdaTests1"> <file name="a.vb"> Imports System Module S1 Public Function Foo(Of T)() As System.Func(Of System.Func(Of T)) Dim x2 = Function() Return Function() As T Return Nothing End Function End Function Return x2 End Function Sub Main() Console.WriteLine(Foo(Of Integer)()()()) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected></expected>) Dim verifier = CompileAndVerify(compilation, expectedOutput:="0") End Sub End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/Lambda_AnonymousDelegateInference.vb
Visual Basic
apache-2.0
25,651
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.5.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class End Namespace Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.MiscFeatureTest.My.MySettings Get Return Global.MiscFeatureTest.My.MySettings.Default End Get End Property End Module End Namespace
inthehand/32feet
Legacy/Testing/MiscFeatureTest/My Project/Settings.Designer.vb
Visual Basic
mit
2,908
Imports System Imports System.Collections Imports System.Configuration Imports System.Data Imports System.Linq Imports System.Web Imports System.Web.Security Imports System.Web.UI Imports System.Web.UI.HtmlControls Imports System.Web.UI.WebControls Imports System.Web.UI.WebControls.WebParts Imports System.IO Imports System.Net Imports DotNetNuke Imports DotNetNuke.Security 'Imports AgapeStaff Imports StaffBroker Imports StaffBrokerFunctions Namespace DotNetNuke.Modules.StaffAdvanceRmb Partial Class StaffAdvanceRmb Inherits Entities.Modules.PortalModuleBase Public Property Amount() As Double Get Return Double.Parse(tbAmount.Text, New CultureInfo("en-US").NumberFormat) End Get Set(ByVal value As Double) tbAmount.Text = value.ToString("n2", New CultureInfo("en-US")) End Set End Property Public Property ReqMessage() As String Get Return tbRequestText.Text End Get Set(ByVal value As String) tbRequestText.Text = value End Set End Property Dim dBroke As New StaffBrokerDataContext Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init Dim FileName As String = System.IO.Path.GetFileNameWithoutExtension(Me.AppRelativeVirtualPath) If Not (Me.ID Is Nothing) Then 'this will fix it when its placed as a ChildUserControl Me.LocalResourceFile = Me.LocalResourceFile.Replace(Me.ID, FileName) Else ' this will fix it when its dynamically loaded using LoadControl method Me.LocalResourceFile = Me.LocalResourceFile & FileName & ".ascx.resx" Dim Locale = System.Threading.Thread.CurrentThread.CurrentCulture.Name Dim AppLocRes As New System.IO.DirectoryInfo(Me.LocalResourceFile.Replace(FileName & ".ascx.resx", "")) If Locale = PortalSettings.CultureCode Then 'look for portal varient If AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx") End If Else If AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".Portal-" & PortalId & ".resx").Count > 0 Then 'lookFor a CulturePortalVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".Portal-" & PortalId & ".resx") ElseIf AppLocRes.GetFiles(FileName & ".ascx." & Locale & ".resx").Count > 0 Then 'look for a CultureVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", Locale & ".resx") ElseIf AppLocRes.GetFiles(FileName & ".ascx.Portal-" & PortalId & ".resx").Count > 0 Then 'lookFor a PortalVarient Me.LocalResourceFile = Me.LocalResourceFile.Replace("resx", "Portal-" & PortalId & ".resx") End If End If End If End Sub Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim mc As New DotNetNuke.Entities.Modules.ModuleController Dim x = mc.GetModuleByDefinition(PortalId, "acStaffRmb") If Not x Is Nothing Then Dim RmbSettings = x.TabModuleSettings hfOverAuth.Value = CType(RmbSettings("TeamLeaderLimit"), String) lblNotes2.Text = Translate("lblNotes2") Dim FC = StaffBrokerFunctions.GetFormattedCurrency(PortalId, RmbSettings("TeamLeaderLimit")) lblNotes2.Text = lblNotes2.Text.Replace("[TEAMLEADERLIMIT]", FC) Dim AuthUser As UserInfo If RmbSettings("AuthUser") <> "" Then AuthUser = UserController.GetUserById(PortalId, RmbSettings("AuthUser")) End If Dim AuthAuthUser As UserInfo If RmbSettings("AuthAuthUser") <> "" Then AuthUser = UserController.GetUserById(PortalId, RmbSettings("AuthAuthUser")) End If If Not AuthUser Is Nothing Then If AuthUser.UserID <> UserId Then lblNotes2.Text = lblNotes2.Text.Replace("[AUTHUSER]", AuthUser.DisplayName) End If End If If Not AuthAuthUser Is Nothing Then If AuthAuthUser.UserID <> UserId Then lblNotes2.Text = lblNotes2.Text.Replace("[AUTHUSER]", AuthAuthUser.DisplayName) End If End If End If ' pnlNotes.Height = 0 ' hfCurrentRequest.Value = 0 lblCur.Text = StaffBrokerFunctions.GetSetting("Currency", PortalId) End If End Sub Public Function Translate(ByVal ResourceString As String) As String Return DotNetNuke.Services.Localization.Localization.GetString(ResourceString & ".Text", LocalResourceFile) End Function End Class End Namespace
GlobalTechnology/OpsInABox
DesktopModules/AgapeConnect/StaffRmb/Controls/StaffAdvanceRmb.ascx.vb
Visual Basic
mit
5,653
Public Class Partida Public Sub New() dados.Add(New Dado) dados.Add(New Dado) dados.Add(New Dado) dados.Add(New Dado) dados.Add(New Dado) jugadores.Add(New Jugador("Jugador1")) jugadores.Add(New Jugador("Jugador2")) empezada = True End Sub Private _jugadores As New List(Of Jugador) Public Property jugadores() As List(Of Jugador) Get Return _jugadores End Get Set(ByVal value As List(Of Jugador)) _jugadores = value End Set End Property Private _id As Integer Public Property id() As Integer Get Return _id End Get Set(ByVal value As Integer) _id = value End Set End Property Private _ganador As New Jugador Public Property ganador() As Jugador Get Return _ganador End Get Set(ByVal value As Jugador) _ganador = value End Set End Property Private _cubilete As New Cubilete Public Property cubilete() As Cubilete Get Return _cubilete End Get Set(ByVal value As Cubilete) _cubilete = value End Set End Property Private _dados As New List(Of Dado) Public Property dados() As List(Of Dado) Get Return _dados End Get Set(ByVal value As List(Of Dado)) _dados = value End Set End Property Private _empezada As Boolean Public Property empezada() As Boolean Get Return _empezada End Get Set(ByVal value As Boolean) _empezada = value End Set End Property Private _tiempo As Integer Public Property tiempo() As Integer Get Return _tiempo End Get Set(ByVal value As Integer) _tiempo = value End Set End Property Private _empate As Boolean Public Property empate() As Boolean Get Return _empate End Get Set(ByVal value As Boolean) _empate = value End Set End Property End Class
crisnieto/generala
BE/PARTIDA.vb
Visual Basic
mit
2,195
Imports System.Data.SqlServerCe Imports System.Data Public Class frmActivityShiftLog Public mlngSelectedTableKeyID As Long Public mstrOeeUserLogInformation As String Public mstrOeeUserShiftLogInformation As String Private Sub frmActivityShiftLog_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Me.Width = frmOEEMain.Width Me.Height = frmOEEMain.pnlDetails.Height lblLogView.Width = Me.Width - lblLogView.Location.X - 10 txtLogEdit.Width = Me.Width - txtLogEdit.Location.X - 10 txtLogEdit.Height = Me.Height - txtLogEdit.Location.Y - 10 lstActivity.Width = Me.Width - lstActivity.Location.X - 10 lstActivity.Height = Me.Height - lstActivity.Location.Y - 10 grpUndefined.Height = Me.Height - grpUndefined.Location.Y - 10 mfblnShowActivities(gintSelectedMach) End Sub Public Function mfblnShowActivities(ByVal intSelMach As Integer) As Boolean Dim strSqlQuery As String Dim strSqlQueryAdd As String Dim rstActivities As ADODB.Recordset Dim intX As Integer lstActivity.Visible = True txtLogEdit.Visible = False lblLogView.Visible = False chkActivityLog.Checked = True If chkInclShortbreaks.Checked Then strSqlQueryAdd = "" Else strSqlQueryAdd = "AND (fldOEEMachineStatusID <> 3) " 'strSqlQueryAdd = "" End If strSqlQuery = "SELECT fldOeeRegTableKeyID, " & _ " fldOeeStartDateTime, " & _ " fldOeeEndDateTime, " & _ " fldOeeShiftStartDateTime, " & _ " fldOeeShiftEndDateTime, " & _ " fldOeeActivityDuration, " & _ " fldOeeActivityID, " & _ " fldOeeActivityDescription, " & _ " fldOeeActivityGroupID, " & _ " fldOeeActivityGroupDescription, " & _ " fldOeeArticleNr, " & _ " fldOeeArticleDescription, " & _ " fldOeeOrderNr, " & _ " fldOeeOrderDescription " & _ "FROM tblOee_Reg " & _ "WHERE (fldOeeShiftStartDateTime = '" & gfstrDatToStr(garrTeamShift.datStartShift) & "') " & _ "AND (fldOeeShiftEndDateTime = '" & gfstrDatToStr(garrTeamShift.datEndShift) & "') " & _ "AND (fldOeeCountryID = '" & garrMachine(gintSelectedMach).intCountryNr & "') " & _ "AND (fldOeePlantID = '" & garrMachine(gintSelectedMach).intPlantNr & "') " & _ "AND (fldOeeSubPlantID = '" & garrMachine(gintSelectedMach).intSubPlantNr & "') " & _ "AND (fldOeeDepartmentID = '" & garrMachine(gintSelectedMach).intDepartmentNr & "') " & _ "AND (fldOeeMachineID = '" & garrMachine(gintSelectedMach).intMachineNr & "') " & _ strSqlQueryAdd & _ "ORDER BY fldOeeStartDateTime DESC;" rstActivities = gfconvertToADODB(gdtaSqlCeTable(strSqlQuery)) Dim lstItem As ListViewItem Dim strRecords(4) As String lstActivity.Clear() lstActivity.Columns.Add("RecordIndex", 0, HorizontalAlignment.Left) lstActivity.Columns.Add("Start date", 188, HorizontalAlignment.Left) lstActivity.Columns.Add("End date", 188, HorizontalAlignment.Left) lstActivity.Columns.Add("Activitygroup", 150, HorizontalAlignment.Left) lstActivity.Columns.Add("Activity", 340, HorizontalAlignment.Left) If Not rstActivities.EOF Then rstActivities.MoveFirst() For intX = 0 To rstActivities.RecordCount - 1 strRecords(0) = rstActivities.Fields("fldOeeRegTableKeyID").Value strRecords(1) = rstActivities.Fields("fldOeeStartDateTime").Value strRecords(2) = IIf(IsDBNull(rstActivities.Fields("fldOeeEndDateTime").Value), Date.Now, rstActivities.Fields("fldOeeEndDateTime").Value) strRecords(3) = rstActivities.Fields("fldOeeActivityGroupDescription").Value strRecords(4) = rstActivities.Fields("fldOeeActivityDescription").Value lstItem = New ListViewItem(strRecords) lstActivity.Items.Add(lstItem) rstActivities.MoveNext() Next End If End Function Private Sub lstActivity_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lstActivity.MouseDoubleClick Dim lstItem As ListViewItem = lstActivity.HitTest(e.Location).Item If lstItem IsNot Nothing Then If chkActivityLog.Checked Then mlngSelectedTableKeyID = lstItem.SubItems(0).Text picBack.Visible = True cmdSubmitLog.Visible = True lstActivity.Visible = False chkInclShortbreaks.Visible = False lblLogView.Visible = True txtLogEdit.Visible = True lblActiLogs.Text = "Activities - Write activity log:" txtLogEdit.Text = "" lblLogView.Text = gfstrSelectedLogs(gintSelectedMach, mlngSelectedTableKeyID, False) End If End If End Sub Public Function gfstrSelectedLogs(ByVal intSelMach As Integer, ByVal lngSelTabelID As Long, ByVal blnGetShiftLog As Boolean) As String Dim strSqlQuery As String Dim rstCurrentLogs As ADODB.Recordset Dim intX As Integer Dim strShiftLogBuilder As String Dim strRecordLog As String 'Shiftlog collect all shiftlog info NOT the last one gfstrSelectedLogs = "" If blnGetShiftLog Then strSqlQuery = "SELECT fldOeeRegTableKeyID, " & _ " fldOeeUserShiftLogInformation " & _ "FROM tblOee_Reg " & _ "WHERE (fldOeeShiftStartDateTime = '" & gfstrDatToStr(garrTeamShift.datStartShift) & "') " & _ "AND (fldOeeShiftEndDateTime = '" & gfstrDatToStr(garrTeamShift.datEndShift) & "') " & _ "AND (fldOeeCountryID = '" & garrMachine(gintSelectedMach).intCountryNr & "') " & _ "AND (fldOeePlantID = '" & garrMachine(gintSelectedMach).intPlantNr & "') " & _ "AND (fldOeeSubPlantID = '" & garrMachine(gintSelectedMach).intSubPlantNr & "') " & _ "AND (fldOeeDepartmentID = '" & garrMachine(gintSelectedMach).intDepartmentNr & "') " & _ "AND (fldOeeMachineID = '" & garrMachine(gintSelectedMach).intMachineNr & "') " & _ "ORDER BY fldOeeRegTableKeyID DESC;" rstCurrentLogs = gfconvertToADODB(gdtaSqlCeTable(strSqlQuery)) strShiftLogBuilder = "" rstCurrentLogs.MoveFirst() If Not rstCurrentLogs.EOF Then For intX = 0 To rstCurrentLogs.RecordCount - 1 strRecordLog = IIf(IsDBNull(rstCurrentLogs.Fields("fldOeeUserShiftLogInformation").Value), "", _ rstCurrentLogs.Fields("fldOeeUserShiftLogInformation").Value) If mlngSelectedTableKeyID = 0 Then mlngSelectedTableKeyID = rstCurrentLogs.Fields("fldOeeRegTableKeyID").Value End If If Len(strRecordLog) > 0 Then strShiftLogBuilder = strShiftLogBuilder & vbCrLf & strRecordLog End If rstCurrentLogs.MoveNext() Next gfstrSelectedLogs = strShiftLogBuilder End If Else strSqlQuery = "SELECT fldOeeRegTableKeyID, " & _ " fldOeeUserLogInformation, " & _ " fldOeeUserShiftLogInformation " & _ "FROM tblOee_Reg " & _ "WHERE (fldOeeRegTableKeyID = '" & mlngSelectedTableKeyID & "');" rstCurrentLogs = gfconvertToADODB(gdtaSqlCeTable(strSqlQuery)) If Not rstCurrentLogs.EOF Then gfstrSelectedLogs = IIf(IsDBNull(rstCurrentLogs.Fields("fldOeeUserLogInformation").Value), 1, _ rstCurrentLogs.Fields("fldOeeUserLogInformation").Value) End If End If End Function Private Sub cmdSubmitLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmitLog.Click Dim strSqlQuery As String = "" Dim strTotalShiftLog As String Dim rstRegLastKey As ADODB.Recordset Dim strRecordLog As String 'first get te last tablekey 'then check if there is an active log in that record 'yes then update 'no then update without first reader active log If Len(txtLogEdit.Text) > 0 Then If chkActivityLog.Checked Then If Len(lblLogView.Text) > 0 Then strTotalShiftLog = lblLogView.Text & vbCrLf & Date.Now & " - " & txtLogEdit.Text Else strTotalShiftLog = Date.Now & " - " & txtLogEdit.Text End If strSqlQuery = "UPDATE tblOee_Reg " & _ "SET fldOeeUserLogInformation = '" & strTotalShiftLog & "' " & _ "WHERE (fldOeeRegTableKeyID = '" & mlngSelectedTableKeyID & "');" End If If chkShiftlog.Checked Then strSqlQuery = "SELECT fldOeeRegTableKeyID, " & _ " fldOeeUserShiftLogInformation " & _ "FROM tblOee_Reg " & _ "WHERE (fldOeeShiftStartDateTime = '" & gfstrDatToStr(garrTeamShift.datStartShift) & "') " & _ "AND (fldOeeShiftEndDateTime = '" & gfstrDatToStr(garrTeamShift.datEndShift) & "') " & _ "AND (fldOeeCountryID = '" & garrMachine(gintSelectedMach).intCountryNr & "') " & _ "AND (fldOeePlantID = '" & garrMachine(gintSelectedMach).intPlantNr & "') " & _ "AND (fldOeeSubPlantID = '" & garrMachine(gintSelectedMach).intSubPlantNr & "') " & _ "AND (fldOeeDepartmentID = '" & garrMachine(gintSelectedMach).intDepartmentNr & "') " & _ "AND (fldOeeMachineID = '" & garrMachine(gintSelectedMach).intMachineNr & "') " & _ "ORDER BY fldOeeShiftStartDateTime DESC;" rstRegLastKey = gfconvertToADODB(gdtaSqlCeTable(strSqlQuery)) If Not rstRegLastKey.EOF Then mlngSelectedTableKeyID = rstRegLastKey.Fields("fldOeeRegTableKeyID").Value strRecordLog = rstRegLastKey.Fields("fldOeeUserShiftLogInformation").Value Else strRecordLog = "" End If If Len(strRecordLog) > 0 Then strTotalShiftLog = Date.Now & " - " & txtLogEdit.Text & vbCrLf & strRecordLog Else strTotalShiftLog = Date.Now & " - " & txtLogEdit.Text End If strSqlQuery = "UPDATE tblOee_Reg " & _ "SET fldOeeUserShiftLogInformation = '" & strTotalShiftLog & "' " & _ "WHERE (fldOeeRegTableKeyID = '" & mlngSelectedTableKeyID & "');" End If gintSqlCeExecuteNonQuery(strSqlQuery) txtLogEdit.Text = "" If chkShiftlog.Checked Then lblLogView.Text = gfstrSelectedLogs(gintSelectedMach, mlngSelectedTableKeyID, True) Else lblLogView.Text = gfstrSelectedLogs(gintSelectedMach, mlngSelectedTableKeyID, False) End If End If lblLogView.Refresh() End Sub Private Sub chkActivityLog_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkActivityLog.CheckedChanged If chkActivityLog.Checked Then lblLogView.Visible = True chkInclShortbreaks.Visible = True cmdSubmitLog.Visible = False picBack.Visible = False mfblnShowAllActivities(gintSelectedMach) End If End Sub Private Function mfblnShowAllActivities(ByVal intSelMach As Integer) As Boolean chkShiftlog.Checked = False chkInclShortbreaks.Enabled = True lblActiLogs.Text = "Activities:" mfblnShowActivities(intSelMach) End Function Private Sub chkShiftlog_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkShiftlog.CheckedChanged If chkShiftlog.Checked Then picBack.Visible = False chkActivityLog.Checked = False chkInclShortbreaks.Visible = False lblLogView.Visible = True lstActivity.Visible = False txtLogEdit.Visible = True lblActiLogs.Text = "Shift - Write shift log:" txtLogEdit.Text = "" lblLogView.Text = gfstrSelectedLogs(gintSelectedMach, mlngSelectedTableKeyID, True) cmdSubmitLog.Visible = True End If End Sub Private Sub chkInclShortbreaks_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkInclShortbreaks.CheckedChanged mfblnShowActivities(gintSelectedMach) End Sub Private Sub picBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picBack.Click If chkActivityLog.Checked Then picBack.Visible = False cmdSubmitLog.Visible = False lblLogView.Visible = True chkInclShortbreaks.Visible = True mfblnShowAllActivities(gintSelectedMach) End If End Sub End Class
twister077/OEECollectorAndOEEWeb
VB.NET/OEECollector/frmActivityShiftLog.vb
Visual Basic
mit
14,175
Imports SistFoncreagro.Report Public Class ReporteActivo Inherits System.Web.UI.Page Dim Tipo As String Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Tipo = Request.QueryString("Tipo") Me.ReportViewer1.Report = New RepActivo Me.ReportViewer1.Report.ReportParameters(0).Value = Tipo End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.WebSite/Contabilidad/Formularios/ReporteActivo.aspx.vb
Visual Basic
mit
390
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.1 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("BaseBall.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set(ByVal value As Global.System.Globalization.CultureInfo) resourceCulture = value End Set End Property End Module End Namespace
gumgl/VB.NET
BaseBall/My Project/Resources.Designer.vb
Visual Basic
mit
2,713
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("GitHub backup")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("")> <Assembly: AssemblyCopyright("")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("ae4a95b9-43bc-4b83-ad76-4974f5917184")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("0.9.0.0")> <Assembly: AssemblyFileVersion("0.9.0.0")>
jesperhoy/GitHubBackup
GitHubBackup/My Project/AssemblyInfo.vb
Visual Basic
mit
1,100
 Imports System Imports System.IO Imports System.Linq Imports System.Collections.Generic Imports System.Globalization Imports System.Threading Namespace Apps ''' <summary> Static properties and utility methods for dealing with (external) Applications. </summary> Public NotInheritable Class AppUtils #Region "Private Fields" Private Shared ReadOnly Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger("Rstyx.Utilities.Apps.AppUtils") Private Shared ReadOnly SyncHandle As New Object() Private Shared _Instance As AppUtils = Nothing Private Shared _AppPathUltraEdit As String = Nothing Private Shared _AppPathCrimsonEditor As String = Nothing Private Shared _AppPathJava As String = Nothing Private Shared _AppPathJEdit As String = Nothing Private Shared _JAVA_HOME As String = Nothing Private Shared _JEDIT_HOME As String = Nothing Private Shared _JEDIT_SETTINGS As String = Nothing Private Shared _AvailableEditors As Dictionary(Of SupportedEditors, EditorInfo) = Nothing Private Shared _CurrentEditor As SupportedEditors Private Shared ReadOnly ClassInitialized As Boolean = InitializeStaticVariables() #End Region #Region "Constructor" Private Sub New() Logger.logDebug("New(): Instantiation starts.") End Sub Private Shared Function InitializeStaticVariables() As Boolean Logger.logDebug("initializeStaticVariables(): Initialization of static variables starts ...") _CurrentEditor = InitCurrentEditor() Return True End Function #End Region #Region "Enums" ''' <summary> Editors supported by <see cref="AppUtils" /> class. </summary> Public Enum SupportedEditors As Integer ''' <summary> No editor determined or available. </summary> None = 0 ''' <summary> UltraEdit </summary> UltraEdit = 1 ''' <summary> jEdit </summary> jEdit = 2 ''' <summary> Crimson Editor </summary> CrimsonEditor = 3 End Enum #End Region #Region "ReadOnly Properties" ''' <summary> Returns the one and only AppUtils instance to allow WPF two way binding. </summary> Public Shared ReadOnly Property Instance() As AppUtils Get SyncLock (SyncHandle) If (_Instance Is Nothing) Then _Instance = New AppUtils Logger.logDebug("Instance [Get]: AppUtils instantiated.") End If Return _Instance End SyncLock End Get End Property ''' <summary> Returns the path of the existing Crimson Editor application file. </summary> ''' <remarks> ''' <para> ''' Returns an empty String if the application file hasn't been found. ''' </para> ''' <para> ''' Cedt.exe is searched for in the following places: ''' </para> ''' <list type="number"> ''' <item> ''' <description> in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Crimson Editor 3.72\DisplayIcon\ (version 3.72) </description> ''' </item> ''' <item> ''' <description> in G:\Tools\Crimson Editor </description> ''' </item> ''' <item> ''' <description> in "%PROGRAMFILES%\Crimson Editor" </description> ''' </item> ''' <item> ''' <description> in "%PROGRAMFILES%\Tools\Crimson Editor" </description> ''' </item> ''' <item> ''' <description> in %PATH% without subdirectories </description> ''' </item> ''' </list> ''' </remarks> Public Shared ReadOnly Property AppPathCrimsonEditor() As String Get SyncLock (SyncHandle) If (_AppPathCrimsonEditor Is Nothing) Then _AppPathCrimsonEditor = GetAppPathCrimsonEditor() End If Return _AppPathCrimsonEditor End SyncLock End Get End Property ''' <summary> Returns the path of the existing UltraEdit application file. </summary> ''' <remarks> ''' <para> ''' Returns an empty String if the application file hasn't been found. ''' </para> ''' <para> ''' UEdit32.exe is searched for in the following places: ''' </para> ''' <list type="number"> ''' <item> ''' <description> in HKEY_CLASSES_ROOT\Applications\UEdit32.exe\shell\edit\command\ (version 6..10) </description> ''' </item> ''' <item> ''' <description> in HKEY_CLASSES_ROOT\UltraEdit-32 Document\shell\open\command\ (version 6..10) </description> ''' </item> ''' <item> ''' <description> in HKEY_CLASSES_ROOT\UltraEdit.txt\shell\open\command\ (version 11) </description> ''' </item> ''' <item> ''' <description> in %PATH% without subdirectories </description> ''' </item> ''' </list> ''' </remarks> Public Shared ReadOnly Property AppPathUltraEdit() As String Get SyncLock (SyncHandle) If (_AppPathUltraEdit Is Nothing) Then _AppPathUltraEdit = GetAppPathUltraEdit() End If Return _AppPathUltraEdit End SyncLock End Get End Property ''' <summary> Returns the path of the existing Java application file. </summary> ''' <remarks> ''' <para> ''' Returns an empty String if the application file hasn't been found. ''' </para> ''' <para> ''' Javaw.exe is searched for in the following places: ''' </para> ''' <list type="number"> ''' <item> ''' <description> in %JAVA_HOME%\bin </description> ''' </item> ''' <item> ''' <description> in %PATH% </description> ''' </item> ''' <item> ''' <description> in HKEY_CLASSES_ROOT\jarfile\shell\open\command\ </description> ''' </item> ''' </list> ''' </remarks> Public Shared ReadOnly Property AppPathJava() As String Get SyncLock (SyncHandle) If (_AppPathJava Is Nothing) Then GetJavaEnvironment() End If Return _AppPathJava End SyncLock End Get End Property ''' <summary> Returns the path of the existing JEdit.jar application file. </summary> ''' <remarks> ''' <para> ''' Returns an empty String if the application file hasn't been found. ''' </para> ''' <para> ''' jEdit.jar is searched for in the following places: ''' </para> ''' <list type="number"> ''' <item> ''' <description> in %JEDIT_HOME% </description> ''' </item> ''' <item> ''' <description> in "%PROGRAMFILES%\jEdit" </description> ''' </item> ''' <item> ''' <description> in "%PROGRAMFILES(X86)%\jEdit" </description> ''' </item> ''' <item> ''' <description> in "%PROGRAMW6432%\jEdit" </description> ''' </item> ''' <item> ''' <description> in Application Setting "AppUtils_jEdit_FallbackPath" </description> ''' </item> ''' <item> ''' <description> in %PATH% without subdirectories </description> ''' </item> ''' </list> ''' </remarks> Public Shared ReadOnly Property AppPathJEdit() As String Get SyncLock (SyncHandle) If (_AppPathJEdit Is Nothing) Then GetJEditEnvironment() End If Return _AppPathJEdit End SyncLock End Get End Property ''' <summary> Returns a list of all available editors. </summary> Public Shared ReadOnly Property AvailableEditors() As Dictionary(Of SupportedEditors, EditorInfo) Get SyncLock (SyncHandle) If (_AvailableEditors Is Nothing) Then _AvailableEditors = GetAvailableEditors() End If Return _AvailableEditors End SyncLock End Get End Property ''' <summary> Returns Java's program directory if <see cref="AppPathJava" /> has been found, otherwise String.Empty. </summary> Public Shared ReadOnly Property JAVA_HOME() As String Get SyncLock (SyncHandle) If (_JAVA_HOME Is Nothing) Then GetJavaEnvironment() End If Return _JAVA_HOME End SyncLock End Get End Property ''' <summary> Returns jEdit's program directory if <see cref="AppPathJEdit" /> has been found, otherwise String.Empty. </summary> Public Shared ReadOnly Property JEDIT_HOME() As String Get SyncLock (SyncHandle) If (_JEDIT_HOME Is Nothing) Then GetJEditEnvironment() End If Return _JEDIT_HOME End SyncLock End Get End Property ''' <summary> Returns expanded environment variable %JEDIT_SETTINGS%, which is the settings directory jEdit should use (maybe String.Empty). </summary> Public Shared ReadOnly Property JEDIT_SETTINGS() As String Get SyncLock (SyncHandle) If (_JEDIT_SETTINGS Is Nothing) Then GetJEditEnvironment() End If Return _JEDIT_SETTINGS End SyncLock End Get End Property #End Region #Region "Settings" ''' <summary> Determines the editor to use for editing tasks when no other editor is stated explicitly. </summary> ''' <value> One of the <see cref="AvailableEditors"/> keys. "SupportedEditors.None" and all other values are ignored. </value> ''' <returns> The editor to use as current. If "SupportedEditors.None", then there is no editor available. </returns> ''' <remarks> This is an application setting. </remarks> Public Shared Property CurrentEditor() As SupportedEditors Get SyncLock (SyncHandle) ' _CurrentEditor is initialized by initCurrentEditor(). Return _CurrentEditor End SyncLock End Get Set(value As SupportedEditors) SyncLock (SyncHandle) If ((value <> _CurrentEditor) AndAlso (value <> SupportedEditors.None) AndAlso ([Enum].IsDefined(GetType(SupportedEditors), value))) Then Logger.logDebug(StringUtils.sprintf("CurrentEditor [Set]: Aktueller Editor wird geändert zu '%s'.", value.ToDisplayString())) _CurrentEditor = value My.Settings.AppUtils_CurrentEditor = _CurrentEditor Else Logger.logDebug(StringUtils.sprintf("CurrentEditor [Set]: Änderung des aktuellen Editors zu '%s' abgewiesen oder unnötig.", value.ToDisplayString())) End If End SyncLock End Set End Property #End Region #Region "Public Static Methods" ''' <summary> The current culture will be patched to use'.' as decimal separator, ' ' as number grouping character and ',' as list separator. </summary> Public Shared Sub PatchCurrentCultureSeparators() Logger.logDebug("PatchCurrentCultureSeparators(): Set '.' as decimal separator, ' ' as number grouping character and ',' as list separator.") Dim ci As CultureInfo = Thread.CurrentThread.CurrentCulture.Clone() ci.NumberFormat.NumberDecimalSeparator = CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator ci.NumberFormat.NumberGroupSeparator = " " ci.TextInfo.ListSeparator = CultureInfo.InvariantCulture.TextInfo.ListSeparator Thread.CurrentThread.CurrentCulture = ci End Sub ''' <summary> The given editor will be started if possible. </summary> ''' <param name="TargetEditor"> Determines one of the supported editors. </param> ''' <param name="Arguments"> Command line arguments for the editor. May be <see langword="null"/>. </param> ''' <exception cref="System.ArgumentException"> <paramref name="TargetEditor"/> is not supported or <see cref="SupportedEditors"/><c>.None</c> or currently not available. </exception> ''' <remarks> ''' <para> ''' Notes on jEdit's command line: ''' </para> ''' <para> ''' The Java command line is: "-ms128m -mx1024m -Dawt.useSystemAAFontSettings=on -Dsun.java2d.noddraw=true -jar &lt;path of jedit.jar&gt;. ''' </para> ''' <para> ''' The options "-reuseview -background" are automatically specified. ''' </para> ''' <para> ''' If %JEDIT_SETTINGS% is defined, the argument "-settings=%JEDIT_SETTINGS%" is automatically specified. ''' </para> ''' </remarks> Public Shared Sub StartEditor(ByVal TargetEditor As SupportedEditors, ByVal Arguments As String) Logger.logDebug(StringUtils.sprintf("startEditor(): Anforderungen: Editor = '%s', Argumente = '%s'.", TargetEditor.ToDisplayString(), Arguments)) ' Validate Arguments. Dim ErrMessage As String = Nothing If (TargetEditor = SupportedEditors.None) Then If (AvailableEditors.Count = 0) Then ErrMessage = Rstyx.Utilities.Resources.Messages.AppUtils_NoEditorAvailable Else ErrMessage = StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.AppUtils_InvalidEditor, TargetEditor.ToDisplayString()) End If ElseIf (Not AvailableEditors.ContainsKey(TargetEditor)) Then If ([Enum].IsDefined(GetType(SupportedEditors), TargetEditor)) Then ErrMessage = StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.AppUtils_EditorNotAvailable, TargetEditor.ToDisplayString()) Else ErrMessage = StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.AppUtils_NotSupportedEditor, TargetEditor.ToDisplayString()) End If End If If (ErrMessage IsNot Nothing) Then Throw New System.ArgumentException(ErrMessage, "TargetEditor") If (Arguments Is Nothing) Then Arguments = String.Empty ' Start process. Dim StartInfo As New System.Diagnostics.ProcessStartInfo() StartInfo.FileName = AvailableEditors.Item(TargetEditor).AppPath StartInfo.Arguments = AvailableEditors.Item(TargetEditor).Arguments & " " & Arguments Logger.logDebug(StringUtils.sprintf("startEditor(): Auszuführende Datei: '%s'.", StartInfo.FileName)) Logger.logDebug(StringUtils.sprintf("startEditor(): Argumente: '%s'.", StartInfo.Arguments)) Logger.logDebug(StringUtils.sprintf("startEditor(): %s wird gestartet.", TargetEditor.ToDisplayString())) Using EditorProcess As System.Diagnostics.Process = System.Diagnostics.Process.Start(StartInfo) End Using End Sub ''' <summary> The given File will be opened in it's associated application if possible. </summary> ''' <param name="AbsoluteFilePath"> The absolute path of the file to start. </param> ''' <exception cref="System.IO.FileNotFoundException"> <paramref name="AbsoluteFilePath"/> hasn't been found. </exception> Public Shared Sub StartFile(ByVal AbsoluteFilePath As String) Logger.logDebug(StringUtils.sprintf("startFile(): zu startende Datei = '%s'.", AbsoluteFilePath)) Using FileProcess As System.Diagnostics.Process = System.Diagnostics.Process.Start(AbsoluteFilePath) End Using End Sub ''' <summary> Activates Excel and invokes the CSV import of GeoTools VBA Add-In. </summary> ''' <param name="FilePath"> The csv file to import in Excel. </param> ''' <exception cref="System.IO.FileNotFoundException"> <paramref name="FilePath"/> hasn't been found. </exception> ''' <exception cref="System.IO.FileNotFoundException"> xlm.vbs hasn't been found after extracting from resources. </exception> ''' <exception cref="Rstyx.Utilities.RemarkException"> Wraps any exception occurred while invoking the system command with a clear message. </exception> ''' <remarks> ''' <para> ''' Excel will be started up if no running instance is found. ''' </para> ''' <para> ''' The GeoTools VBA Add-In for Excel has to be installed (www.rstyx.de). ''' </para> ''' <para> ''' This method extracts a VBscript file from dll resource to a temporary file, wich in turn is invoked via wscript.exe. ''' The VBscript does the work. ''' </para> ''' </remarks> Public Shared Sub StartExcelGeoToolsCSVImport(byVal FilePath As String) SyncLock (SyncHandle) Logger.logInfo(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.AppUtils_InvokeGeoToolsCsvImport, FilePath)) If (Not File.Exists(FilePath)) Then Throw New System.IO.FileNotFoundException(Rstyx.Utilities.Resources.Messages.AppUtils_GeoToolsCsvNotFound, FilePath) ' Exctract resource VBscript to temporary file. Dim XlmVbsFile As String = System.IO.Path.GetTempFileName() Logger.logDebug(StringUtils.sprintf("startExcelGeoToolsCSVImport(): Exctract shell vb script form dll to: '%s'", XlmVbsFile)) System.IO.File.WriteAllText(XlmVbsFile, My.Resources.StartExcelAndXLMacro) If (Not File.Exists(XlmVbsFile)) Then Throw New System.IO.FileNotFoundException(Rstyx.Utilities.Resources.Messages.AppUtils_XlmVBScriptNotFound, XlmVbsFile) Try ' Invoke temporary file via wscript.exe. Dim ShellCommand As String = StringUtils.sprintf("%%comspec%% /c wscript /E:vbscript ""%s"" /M:Import_CSV ""/D:%s"" /silent:true", XlmVbsFile, FilePath) Logger.logDebug(StringUtils.sprintf("startExcelGeoToolsCSVImport(): Invoke shell command = '%s'", ShellCommand)) Microsoft.VisualBasic.Interaction.Shell(System.Environment.ExpandEnvironmentVariables(ShellCommand), AppWinStyle.Hide, Wait:=False) Catch ex as System.Exception Throw New RemarkException(StringUtils.sprintf(Rstyx.Utilities.Resources.Messages.AppUtils_ErrorInvokingXlGeoToolsImport, FilePath), ex) End Try End SyncLock End Sub #End Region #Region "Data Structures, Nested Classes" ''' <summary> Editor info record </summary> Public Class EditorInfo ''' <summary> Creates a new, empty EditorInfo. </summary> Public Sub New End Sub ''' <summary> Creates a new EditorInfo and initializes all properties. </summary> ''' <param name="DisplayName"> Editor name for displaying </param> ''' <param name="AppPath"> Full path of the application file </param> ''' <param name="Arguments"> Fixed arguments that will be provided at the command line </param> Public Sub New(DisplayName As String, AppPath As String, Arguments As String) Me.DisplayName = DisplayName Me.AppPath = AppPath Me.Arguments = Arguments End Sub ''' <summary> Editor name for displaying. </summary> Public Property DisplayName As String = String.Empty ''' <summary> Full path of the application file. </summary> Public Property AppPath As String = String.Empty ''' <summary> Immutual arguments that will be provided at the command line before other arguments. </summary> Public Property Arguments As String = String.Empty End Class #End Region #Region "Private Members" ''' <summary> Searches for the Crimson Editor application file in some places. </summary> ''' <returns> The found application file path or String.Empty. </returns> Private Shared Function GetAppPathCrimsonEditor() As String Dim Key_CEditExe As String Dim CEditExe As String Dim CEditDir As String Dim fi As FileInfo Dim Success As Boolean = false const AppName As String = "cedt.exe" Logger.logDebug("getAppPathCrimsonEditor(): Programmdatei von Crimson Editor ermitteln.") ' If it could be uninstalled, maybe it could be found ... Key_CEditExe = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Crimson Editor 3.72\DisplayIcon" CEditExe = RegUtils.getApplicationPath(Key_CEditExe) if (CEditExe.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAppPathCrimsonEditor(): Crimson Editor nicht gefunden in Registry => suche nach Portable Version.") Success = False end if ' Search for portable version in 3 places. if (not Success) Then Logger.logDebug("getAppPathCrimsonEditor(): Crimson Editor nicht gefunden in Registry => suche nach Portable Version.") CEditDir = "G:\Tools\Crimson Editor" CEditExe = CEditDir & "\" & AppName if (File.Exists(CEditExe)) Then Success = true else Logger.logDebug("getAppPathCrimsonEditor(): cedt.exe nicht gefunden im (hart kodierten) Verzeichnis '" & CEditDir & "'") end if end if if (not Success) Then CEditDir = Environment.GetEnvironmentVariable("PROGRAMFILES") & "\Crimson Editor" CEditExe = CEditDir & "\" & AppName if (File.Exists(CEditExe)) Then Success = true else Logger.logDebug("getAppPathCrimsonEditor(): cedt.exe nicht gefunden im (hart kodierten) Verzeichnis '" & CEditDir & "'") end if end if if (not Success) Then CEditDir = Environment.GetEnvironmentVariable("PROGRAMFILES") & "\Tools\Crimson Editor" CEditExe = CEditDir & "\" & AppName if (File.Exists(CEditExe)) Then Success = true else Logger.logDebug("getAppPathCrimsonEditor(): cedt.exe nicht gefunden im (hart kodierten) Verzeichnis '" & CEditDir & "'") end if end if ' Search in %PATH% if (not Success) Then CEditExe = String.Empty Logger.logDebug("getAppPathCrimsonEditor(): Programmdatei von Crimson Editor im Dateisystem suchen im %PATH%.") fi = IO.FileUtils.findFile(AppName, Environment.ExpandEnvironmentVariables("%PATH%"), ";", SearchOption.TopDirectoryOnly) If (fi IsNot Nothing) Then CEditExe = fi.FullName end if ' Result if (CEditExe.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAppPathCrimsonEditor(): Programmdatei von Crimson Editor nicht gefunden.") Else Logger.logDebug(StringUtils.sprintf("getAppPathCrimsonEditor(): Programmdatei von Crimson Editor gefunden: '%s'.", CEditExe)) end if Return CEditExe End Function ''' <summary> Searches for the UltraEdit application file in some places. </summary> ''' <returns> The found application file path or String.Empty. </returns> Private Shared Function GetAppPathUltraEdit() As String Dim Key_UEditExe As String Dim UEditExe As String Dim fi As FileInfo Const AppNames As String = "UEdit*.exe;UltaEdit*.exe" Logger.logDebug("getAppPathUltraEdit(): Programmdatei von UltraEdit ermitteln.") ' Version 6 ... 10: Key_UEditExe = "HKEY_CLASSES_ROOT\Applications\UEdit32.exe\shell\edit\command\" UEditExe = RegUtils.getApplicationPath(Key_UEditExe) If (UEditExe.IsEmptyOrWhiteSpace()) Then Key_UEditExe = "HKEY_CLASSES_ROOT\UltraEdit-32 Document\shell\open\command\" UEditExe = RegUtils.getApplicationPath(Key_UEditExe) End if ' Version 11 If (UEditExe.IsEmptyOrWhiteSpace()) Then ' This only works if UltraEdit has made a file association for ".txt"!!! Key_UEditExe = "HKEY_CLASSES_ROOT\UltraEdit.txt\shell\open\command\" UEditExe = RegUtils.getApplicationPath(Key_UEditExe) End if ' Search in %PATH% If (UEditExe.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAppPathUltraEdit(): Programmdatei von UltraEdit im Dateisystem suchen im %PATH%.") fi = IO.FileUtils.findFile(AppNames, Environment.ExpandEnvironmentVariables("%PATH%"), ";", SearchOption.TopDirectoryOnly) If (fi IsNot Nothing) Then UEditExe = fi.FullName End if ' Result If (UEditExe.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAppPathUltraEdit(): Programmdatei von UltraEdit nicht gefunden.") Else Logger.logDebug(StringUtils.sprintf("getAppPathUltraEdit(): Programmdatei von UltraEdit gefunden: '%s'.", UEditExe)) End if Return UEditExe End Function ''' <summary> Searches for the Java application file in some places and gets it's environment. </summary> ''' <remarks> Determines the Java application file path and %JAVA_HOME%. </remarks> Private Shared Sub GetJavaEnvironment() Dim JavaExe As String = String.Empty Dim fi As FileInfo Const AppNames As String = "Javaw.exe" Const Key_JavaExe As String = "HKEY_CLASSES_ROOT\jarfile\shell\open\command\" Logger.logDebug("getJavaEnvironment(): Programmdatei von Java ermitteln.") ' Search in %JAVA_HOME% Logger.logDebug("getJavaEnvironment(): Programmdatei von Java im Dateisystem suchen in %JAVA_HOME%.") _JAVA_HOME = Environment.GetEnvironmentVariable("JAVA_HOME") If (_JAVA_HOME Is Nothing) Then _JAVA_HOME = String.Empty Else fi = IO.FileUtils.findFile(AppNames, _JAVA_HOME & "\bin", ";", SearchOption.TopDirectoryOnly) If (fi IsNot Nothing) Then JavaExe = fi.FullName End If ' Search dafault Java in %PATH% If (JavaExe.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getJavaEnvironment(): Programmdatei der Java-Standardinstallation im Dateisystem suchen im %PATH%.") fi = IO.FileUtils.findFile(AppNames, Environment.GetEnvironmentVariable("PATH"), ";", SearchOption.TopDirectoryOnly) If (fi IsNot Nothing) Then JavaExe = fi.FullName End if ' Default app for .jar files If (JavaExe.IsEmptyOrWhiteSpace()) Then JavaExe = RegUtils.getApplicationPath(Key_JavaExe) End if '' Search in %PROGRAMFILES% 'if (JavaExe.IsEmptyOrWhiteSpace()) Then ' Logger.logDebug("getJavaEnvironment(): Programmdatei von Java im Dateisystem suchen unter %PROGRAMFILES%.") ' fi = IO.FileUtils.findFile(AppNames, Environment.GetEnvironmentVariable("PROGRAMFILES"), ";", SearchOption.AllDirectories) ' If (fi IsNot Nothing) Then JavaExe = fi.FullName 'end if ' Result If (JavaExe.IsEmptyOrWhiteSpace()) Then _JAVA_HOME = String.Empty Logger.logDebug("getJavaEnvironment(): Programmdatei von Java nicht gefunden.") Else _JAVA_HOME = IO.FileUtils.getFilePart(JavaExe, IO.FileUtils.FilePart.Dir) If (_JAVA_HOME.EndsWith("\bin", ignoreCase:=True, culture:= CultureInfo.InvariantCulture)) Then _JAVA_HOME = _JAVA_HOME.Left(_JAVA_HOME.Length - 4) ElseIf (_JAVA_HOME.EndsWith("\bin\", ignoreCase:=True, culture:= CultureInfo.InvariantCulture)) Then _JAVA_HOME = _JAVA_HOME.Left(_JAVA_HOME.Length - 5) End If Logger.logDebug(StringUtils.sprintf("getJavaEnvironment(): Programmdatei von Java gefunden: '%s'.", JavaExe)) Logger.logDebug(StringUtils.sprintf("getJavaEnvironment(): _JAVA_HOME davon abgeleitet: '%s'.", _JAVA_HOME)) End if _AppPathJava = JavaExe End Sub ''' <summary> Searches for the jEdit application file in some places and gets it's environment. </summary> ''' <remarks> Determines jedit.jar path, %JEDIT_HOME% and %JEDIT_SETTINGS%. </remarks> Private Shared Sub GetJEditEnvironment() Dim jEditJar As String = String.Empty Dim jEditHome As String = String.Empty Dim fi As FileInfo Const JarName As String = "jEdit.jar" dim Success As Boolean = false Logger.logDebug("getJEditEnvironment(): Pfad\Dateiname von " & JarName & " ermitteln.") ' Search in %JEDIT_HOME% _JEDIT_HOME = Environment.GetEnvironmentVariable("JEDIT_HOME") If (_JEDIT_HOME Is Nothing) Then _JEDIT_HOME = String.Empty Logger.logDebug("getJEditEnvironment(): Umgebungsvariable %JEDIT_HOME% existiert nicht. => Suche weiter in Konfiguration") Else _JEDIT_HOME = _JEDIT_HOME.ReplaceWith("\\+$", "") jEditJar = _JEDIT_HOME & "\" & JarName if (File.Exists(jEditJar)) Then Success = true Logger.logDebug("getJEditEnvironment(): jEdit.jar gefunden im Verzeichnis der Umgebungsvariable %JEDIT_HOME%='" & _JEDIT_HOME & "'") else Logger.logDebug("getJEditEnvironment(): jEdit.jar nicht gefunden im Verzeichnis der Umgebungsvariable %JEDIT_HOME%='" & _JEDIT_HOME & "'") end if End if ' Search in %PROGRAMFILES% If (not Success) Then jEditHome = Environment.GetEnvironmentVariable("PROGRAMFILES") & "\jEdit" jEditJar = jEditHome & "\" & JarName if (File.Exists(jEditJar)) Then Success = true else Logger.logDebug("getJEditEnvironment(): jEdit.jar nicht gefunden im Verzeichnis der Umgebungsvariable %PROGRAMFILES%='" & jEditHome & "'") end if End if ' Search in %PROGRAMFILES(X86)% If (not Success) Then jEditHome = Environment.GetEnvironmentVariable("PROGRAMFILES(X86)") & "\jEdit" jEditJar = jEditHome & "\" & JarName if (File.Exists(jEditJar)) Then Success = true else Logger.logDebug("getJEditEnvironment(): jEdit.jar nicht gefunden im Verzeichnis der Umgebungsvariable %PROGRAMFILES(X86)%='" & jEditHome & "'") end if End if ' Search in %PROGRAMW6432% If (not Success) Then jEditHome = Environment.GetEnvironmentVariable("PROGRAMW6432") & "\jEdit" jEditJar = jEditHome & "\" & JarName if (File.Exists(jEditJar)) Then Success = true else Logger.logDebug("getJEditEnvironment(): jEdit.jar nicht gefunden im Verzeichnis der Umgebungsvariable %PROGRAMW6432%='" & jEditHome & "'") end if End if ' Search in Application Setting "AppUtils_jEdit_FallbackPath" If (not Success) Then jEditHome = My.Settings.AppUtils_jEdit_FallbackPath jEditJar = jEditHome & "\" & JarName if (File.Exists(jEditJar)) Then Success = true else Logger.logDebug("getJEditEnvironment(): jEdit.jar nicht gefunden im (hart kodierten) Verzeichnis '" & jEditHome & "'") end if End if ' Search in %PATH% If (not Success) Then Logger.logDebug("getJEditEnvironment(): jEdit.jar im Dateisystem suchen im %PATH%.") fi = IO.FileUtils.findFile(JarName, Environment.ExpandEnvironmentVariables("%PATH%"), ";", SearchOption.TopDirectoryOnly) If (fi IsNot Nothing) Then jEditJar = fi.FullName End if ' jEdit settings directory _JEDIT_SETTINGS = Environment.GetEnvironmentVariable("JEDIT_SETTINGS") If (_JEDIT_SETTINGS Is Nothing) Then _JEDIT_SETTINGS = String.Empty Else _JEDIT_SETTINGS = _JEDIT_SETTINGS.ReplaceWith("\\+$", "") End If Logger.logDebug("getJEditEnvironment(): Umgebungsvariable %JEDIT_SETTINGS%='" & _JEDIT_SETTINGS & "'") ' Result If (not Success) Then _AppPathJEdit = String.Empty _JEDIT_HOME = String.Empty Logger.logDebug("getJEditEnvironment(): Programmdatei von jEdit nicht gefunden.") Else _AppPathJEdit = jEditJar _JEDIT_HOME = IO.FileUtils.getFilePart(jEditJar, IO.FileUtils.FilePart.Dir) Logger.logDebug(StringUtils.sprintf("getJEditEnvironment(): Programmdatei von jEdit gefunden: '%s'.", jEditJar)) End if End Sub ''' <summary> Looks for availability of supported editors. </summary> ''' <returns> A dictionary of all available editors. If no editor has been found, the dictionary has no entry. </returns> Private Shared Function GetAvailableEditors() As Dictionary(Of SupportedEditors, EditorInfo) Dim Arguments As String Dim Editors As New Dictionary(Of SupportedEditors, EditorInfo) Logger.logDebug("getAvailableEditors(): Suche alle unterstützten Editoren...") ' UltraEdit. If (AppPathUltraEdit.IsNotEmptyOrWhiteSpace()) Then Editors.Add(SupportedEditors.UltraEdit, New EditorInfo(SupportedEditors.UltraEdit.ToDisplayString(), AppPathUltraEdit, String.Empty)) End If ' Crimson Editor. If (AppPathCrimsonEditor.IsNotEmptyOrWhiteSpace()) Then Editors.Add(SupportedEditors.CrimsonEditor, New EditorInfo(SupportedEditors.CrimsonEditor.ToDisplayString(), AppPathCrimsonEditor, String.Empty)) End If ' jEdit. If (AppPathJava.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAvailableEditors(): jEdit ist nicht verfügbar, weil Java nicht verfügbar ist.") ElseIf (AppPathJEdit.IsEmptyOrWhiteSpace()) Then Logger.logDebug("getAvailableEditors(): jEdit ist nicht verfügbar, weil jEdit.jar nicht gefunden wurde.") Else ' Arguments: all for Java and basic for jEdit. 'Arguments = "-ms128m -mx1024m -Dawt.useSystemAAFontSettings=on -Dsun.java2d.noddraw=true -jar """ & AppPathJEdit & """ -reuseview -background " Arguments = "-jar """ & AppPathJEdit & """ -reuseview -background " ' Arguments: jEdit settings directory if needed. if (JEDIT_SETTINGS.IsNotEmptyOrWhiteSpace()) Then Arguments &= """-settings=" & JEDIT_SETTINGS & """ " Logger.logDebug(StringUtils.sprintf("getAvailableEditors(): Als jEdit-Einstellungsverzeichnis wird verwendet: '%s'.", JEDIT_SETTINGS)) End If Editors.Add(SupportedEditors.jEdit, New EditorInfo(SupportedEditors.jEdit.ToDisplayString(), AppPathJava, Arguments)) End If 'Result If (Editors.Count = 0) Then Logger.logWarning(Rstyx.Utilities.Resources.Messages.AppUtils_NoEditorAvailable) Else Logger.logDebug("getAvailableEditors(): Gefundene Editoren:") For Each Editor As KeyValuePair(Of SupportedEditors, EditorInfo) In Editors Logger.logDebug(StringUtils.sprintf("getAvailableEditors(): - '%s'.", Editor.Value.DisplayName)) Next End If Return Editors End Function ''' <summary> Initializes the current editor.. </summary> ''' <returns> The initial current editor. May be "SupportedEditors.None". </returns> ''' <remarks> ''' <para> ''' First, the current editor is restored from application settings "AppUtils_CurrentEditor". ''' </para> ''' <para> ''' If this restored editor is not available, then the first available is used if there is one, otherwise "SupportedEditors.None", ''' and the application setting is updated. ''' </para> ''' </remarks> Private Shared Function InitCurrentEditor() As SupportedEditors Logger.logDebug("initCurrentEditor(): Aktuellen Editor ermitteln.") Dim initialEditor As SupportedEditors = SupportedEditors.None If ([Enum].IsDefined(GetType(SupportedEditors), My.Settings.AppUtils_CurrentEditor)) Then initialEditor = CType(My.Settings.AppUtils_CurrentEditor, SupportedEditors) End If Logger.logDebug(StringUtils.sprintf("initCurrentEditor(): Aktueller Editor war zuletzt '%s'.", initialEditor.ToDisplayString())) ' If editor restored from settings is not available, then use the first available if there is one. If (Not AvailableEditors.ContainsKey(initialEditor)) Then Logger.logDebug(StringUtils.sprintf("initCurrentEditor(): '%s' ist nicht verfügbar => verwende den ersten verfügbaren Editor.", initialEditor.ToDisplayString())) If (AvailableEditors.Count > 0) Then initialEditor = AvailableEditors.Keys.ElementAt(0) Else initialEditor = SupportedEditors.None End If End If ' Store the new current editor in settings. If (My.Settings.AppUtils_CurrentEditor <> initialEditor) Then My.Settings.AppUtils_CurrentEditor = initialEditor End If Logger.logDebug(StringUtils.sprintf("initCurrentEditor(): Aktueller Editor ist '%s'.", initialEditor.ToDisplayString())) Return initialEditor End Function #End Region End Class End Namespace ' for jEdit: :collapseFolds=2::tabSize=4::indentSize=4:
rschwenn/Rstyx.Utilities
Utilities/source/Apps/AppUtils.vb
Visual Basic
mit
45,596
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.UseObjectInitializer Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.UseObjectInitializer), [Shared]> Friend Class VisualBasicUseObjectInitializerCodeFixProvider Inherits AbstractUseObjectInitializerCodeFixProvider(Of SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax, VariableDeclaratorSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetNewStatement( statement As StatementSyntax, objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As StatementSyntax Dim newStatement = statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)) Dim totalTrivia = ArrayBuilder(Of SyntaxTrivia).GetInstance() totalTrivia.AddRange(statement.GetLeadingTrivia()) totalTrivia.Add(SyntaxFactory.ElasticMarker) For Each match In matches For Each trivia In match.Statement.GetLeadingTrivia() If trivia.Kind = SyntaxKind.CommentTrivia Then totalTrivia.Add(trivia) totalTrivia.Add(SyntaxFactory.ElasticMarker) End If Next Next Return newStatement.WithLeadingTrivia(totalTrivia) End Function Private Function GetNewObjectCreation( objectCreation As ObjectCreationExpressionSyntax, matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As ObjectCreationExpressionSyntax Return UseInitializerHelpers.GetNewObjectCreation( objectCreation, SyntaxFactory.ObjectMemberInitializer( CreateFieldInitializers(matches))) End Function Private Function CreateFieldInitializers( matches As ImmutableArray(Of Match(Of ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, AssignmentStatementSyntax))) As SeparatedSyntaxList(Of FieldInitializerSyntax) Dim nodesAndTokens = New List(Of SyntaxNodeOrToken) For i = 0 To matches.Length - 1 Dim match = matches(i) Dim rightValue = match.Initializer If i < matches.Length - 1 Then rightValue = rightValue.WithoutTrailingTrivia() End If Dim initializer = SyntaxFactory.NamedFieldInitializer( keyKeyword:=Nothing, dotToken:=match.MemberAccessExpression.OperatorToken, name:=SyntaxFactory.IdentifierName(match.MemberName), equalsToken:=match.Statement.OperatorToken, expression:=rightValue).WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker) nodesAndTokens.Add(initializer) If i < matches.Length - 1 Then Dim comma = SyntaxFactory.Token(SyntaxKind.CommaToken). WithTrailingTrivia(match.Initializer.GetTrailingTrivia()) nodesAndTokens.Add(comma) End If Next Return SyntaxFactory.SeparatedList(Of FieldInitializerSyntax)(nodesAndTokens) End Function End Class End Namespace
reaction1989/roslyn
src/Analyzers/VisualBasic/CodeFixes/UseObjectInitializer/VisualBasicUseObjectInitializerCodeFixProvider.vb
Visual Basic
apache-2.0
4,470
Imports System.ComponentModel Imports DevExpress.XtraGrid Imports DevExpress.XtraGrid.Views.Grid Imports bv.winclient.Core Imports EIDSS.model.Resources Public Class AggregateMatrixBase Friend WithEvents m_MatrixDataView As DataView Protected m_AggregateMatrixDbService As AggregateMatrix_DB Public Sub New() ' This call is required by the Windows Form Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. m_AggregateMatrixDbService = New AggregateMatrix_DB DbService = m_AggregateMatrixDbService End Sub Protected Overrides Sub DefineBinding() m_DoDeleteAfterNo = False BindView() Core.LookupBinder.BindTextEdit(txtVersionName, baseDataSet, AggregateMatrix_DB.TableCurrentVersion + ".MatrixName") Core.LookupBinder.BindDateEdit(dtVersionDate, baseDataSet, AggregateMatrix_DB.TableCurrentVersion + ".datStartDate") Core.LookupBinder.BindAggregateMatrixVersionLookup(cbSelectVersion, baseDataSet, AggregateMatrix_DB.TableCurrentVersion + ".idfVersion", MatrixType, False) cbSelectVersion.Properties.DataSource = VersionListView 'VersionListView.Sort = "idfVersion" eventManager.AttachDataHandler(AggregateMatrix_DB.TableCurrentVersion + ".MatrixName", AddressOf VersionDescription_Changed) eventManager.AttachDataHandler(AggregateMatrix_DB.TableCurrentVersion + ".datStartDate", AddressOf VersionDescription_Changed) eventManager.AttachDataHandler(AggregateMatrix_DB.TableCurrentVersion + ".idfVersion", AddressOf Version_Changed) eventManager.Cascade(AggregateMatrix_DB.TableCurrentVersion + ".idfVersion") End Sub <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Protected ReadOnly Property MatrixTable() As DataTable Get Return baseDataSet.Tables(AggregateMatrix_DB.TableMatrix) End Get End Property <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Protected ReadOnly Property VersionListTable() As DataTable Get Return baseDataSet.Tables(AggregateMatrix_DB.TableVersionsList) End Get End Property <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Protected ReadOnly Property VersionListView() As DataView Get Return VersionListTable.DefaultView End Get End Property <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Protected ReadOnly Property VersionTable() As DataTable Get Return baseDataSet.Tables(AggregateMatrix_DB.TableCurrentVersion) End Get End Property <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Protected ReadOnly Property CurrentVersion() As Long Get If (VersionTable.Rows.Count > 0) Then Return CLng(VersionTable.Rows(0)("idfVersion")) Else Return -1 End If End Get End Property Dim m_MatrixGrid As GridControl <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Public Property MatrixGrid() As GridControl Get Return m_MatrixGrid End Get Set(ByVal value As GridControl) m_MatrixGrid = value End Set End Property <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Public ReadOnly Property MatrixGridView() As GridView Get If MatrixGrid Is Nothing Then Return Nothing End If Return CType(m_MatrixGrid.MainView, GridView) End Get End Property Dim m_MatrixType As AggregateCaseSection <Browsable(False), Localizable(False), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> _ Public Property MatrixType() As AggregateCaseSection Get Return m_MatrixType End Get Set(ByVal value As AggregateCaseSection) m_MatrixType = value If Not m_AggregateMatrixDbService Is Nothing Then m_AggregateMatrixDbService.MatrixType = value End If End Set End Property Protected Overridable Sub BindView() If baseDataSet.Tables.Contains(AggregateMatrix_DB.TableMatrix) Then If m_MatrixDataView Is Nothing Then m_MatrixDataView = MatrixTable.DefaultView m_MatrixDataView.Sort = "intNumRow" AddHandler MatrixTable.TableNewRow, AddressOf OnMatrixRowAdded MatrixGrid.DataSource = MatrixTable End If End If End Sub Private Sub OnMatrixRowAdded(ByVal sender As Object, ByVal e As DataTableNewRowEventArgs) If m_MatrixDataView.Count = 0 Then e.Row("intNumRow") = 0 Else Dim row As DataRowView = m_MatrixDataView(m_MatrixDataView.Count - 1) If row("intNumRow") Is DBNull.Value Then e.Row("intNumRow") = m_MatrixDataView.Count Else e.Row("intNumRow") = CInt(row("intNumRow")) + 1 End If End If End Sub ' Private Sub OnMatrixRowAdded1(ByVal sender As Object, ByVal e As ListChangedEventArgs) ' If e.ListChangedType = ListChangedType.ItemAdded Then ' ' If e.NewIndex = 0 Then ' MatrixTable.Columns("intNumRow").DefaultValue = 0 ' 'MatrixDataView(e.NewIndex)("idfNumRow") = 0 ' Else ' Dim row As DataRowView = m_MatrixDataView(e.NewIndex - 1) ' If row("idfNumRow") Is DBNull.Value Then ' 'MatrixDataView(e.NewIndex)("idfNumRow") = MatrixDataView.Count ' Else ' MatrixTable.Columns("intNumRow").DefaultValue = CInt(row("idfNumRow")) + 1 ' ' 'MatrixDataView(e.NewIndex)("idfNumRow") = CInt(row("idfNumRow")) + 1 ' End If ' End If ' End If ' End Sub Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnDelete.Click Dim row As DataRow = GetCurrentRow(AggregateMatrix_DB.TableMatrix) If Not row Is Nothing AndAlso WinUtils.ConfirmDelete Then row.Delete() End If End Sub Private Sub DisplayCurrentVersionMatrix() If Not m_MatrixDataView Is Nothing Then MatrixGrid.DataSource = Nothing MatrixTable.Columns("idfVersion").DefaultValue = CurrentVersion MatrixGrid.DataSource = MatrixTable m_MatrixDataView.RowFilter = String.Format("idfVersion = {0}", CurrentVersion) End If End Sub Protected Overridable Sub Version_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs) Dim row As DataRowView = FindVersionRow(e.Value) If Not row Is Nothing Then VersionTable.Rows(0)("MatrixName") = row("MatrixName") VersionTable.Rows(0)("datStartDate") = row("datStartDate") VersionTable.Rows(0)("blnIsActive") = row("blnIsActive") VersionTable.Rows(0)("blnIsDefault") = row("blnIsDefault") VersionTable.Rows(0).EndEdit() End If SetEditMode() DisplayCurrentVersionMatrix() End Sub Private Sub VersionDescription_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs) Dim row As DataRowView = FindVersionRow(CurrentVersion) If Not row Is Nothing Then If e.Column.ColumnName <> "datStartDate" OrElse row("blnIsActive").Equals(True) Then row(e.Column.ColumnName) = e.Value row.EndEdit() End If End If End Sub Private Sub btnDeleteVersion_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnDeleteVersion.Click 'Last version can't be deleted If VersionListView.Count < 2 Then Return End If If Not WinUtils.ConfirmDelete Then Return End If While m_MatrixDataView.Count > 0 m_MatrixDataView(0).Delete() End While Dim row As DataRowView = FindVersionRow(CurrentVersion) If Not row Is Nothing Then row.Delete() End If VersionTable.Rows(0)("idfVersion") = VersionListView(0)("idfVersion") eventManager.Cascade(AggregateMatrix_DB.TableCurrentVersion + ".idfVersion") End Sub Private Sub btnNewVersion_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnNewVersion.Click If Not ValidateData() Then Return End If If VersionListView.Table.Select("blnIsActive<>1").Length > 0 Then ErrorForm.ShowMessageDirect(EidssMessages.Get("msgOnlyOneNonActiveMatrixEnabled", "You can have only one inactive matrix. Please activate currently inactive matrix before creating the new one.")) Return End If m_AggregateMatrixDbService.CreateNewMatrixVersion(baseDataSet, CurrentVersion) End Sub Private Sub btnActivateVersion_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnActivateVersion.Click If m_MatrixDataView.Count = 0 Then ErrorForm.ShowMessageDirect(EidssMessages.Get("msgCantActivateEmptyMatrix", "Empty matrix can't be activated.")) Return End If VersionTable.Rows(0)("blnIsActive") = 1 VersionTable.Rows(0)("blnIsDefault") = 1 For Each row As DataRowView In VersionListView If row("idfVersion").Equals(CurrentVersion) Then row("blnIsActive") = 1 row("blnIsDefault") = 1 If VersionTable.Rows(0)("datStartDate") Is DBNull.Value Then row("datStartDate") = DateTime.Now VersionTable.Rows(0)("datStartDate") = row("datStartDate") Else row("datStartDate") = VersionTable.Rows(0)("datStartDate") End If Else row("blnIsDefault") = 0 If row("blnIsActive") Is DBNull.Value Then row("blnIsActive") = 0 End If End If row("intState") = CInt(IIf(row("blnIsActive").Equals(True), 1, 0)) + CInt(IIf(row("blnIsDefault").Equals(True), 1, 0)) row.EndEdit() Next SetEditMode() End Sub Private Function FindVersionRow(ByVal version As Object) As DataRowView For Each row As DataRowView In VersionListView If row("idfVersion").Equals(version) Then Return row End If Next Return Nothing End Function Public Overrides Sub UpdateButtonsState(ByVal sender As Object, ByVal e As EventArgs) If VersionTable Is Nothing Then btnActivateVersion.Enabled = False btnDown.Enabled = False btnUp.Enabled = False Return End If btnActivateVersion.Enabled = Not [ReadOnly] AndAlso VersionTable.Rows.Count > 0 AndAlso CInt(VersionTable.Rows(0)("blnIsActive")) = 0 btnDown.Enabled = Not [ReadOnly] AndAlso MatrixGridView.FocusedRowHandle >= 0 AndAlso MatrixGridView.FocusedRowHandle < MatrixGridView.RowCount - 1 btnUp.Enabled = Not [ReadOnly] AndAlso MatrixGridView.FocusedRowHandle > 0 End Sub Private Sub SetEditMode() Dim isVersionActive As Boolean = CType(VersionTable.Rows(0)("blnIsActive"), Boolean) m_MatrixDataView.AllowNew = model.Core.EidssUserContext.User.HasPermission(PermissionHelper.InsertPermission(model.Enums.EIDSSPermissionObject.Reference)) AndAlso Not isVersionActive If m_MatrixDataView.AllowNew Then MatrixGridView.OptionsView.NewItemRowPosition = Views.Grid.NewItemRowPosition.Top Else MatrixGridView.OptionsView.NewItemRowPosition = Views.Grid.NewItemRowPosition.None End If m_MatrixDataView.AllowEdit = model.Core.EidssUserContext.User.HasPermission(PermissionHelper.UpdatePermission(model.Enums.EIDSSPermissionObject.Reference)) AndAlso Not isVersionActive m_MatrixDataView.AllowDelete = model.Core.EidssUserContext.User.HasPermission(PermissionHelper.DeletePermission(model.Enums.EIDSSPermissionObject.Reference)) AndAlso Not isVersionActive btnDeleteVersion.Enabled = m_MatrixDataView.AllowDelete btnDelete.Enabled = m_MatrixDataView.AllowDelete End Sub Private Sub btnUp_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnUp.Click Dim rowHandle As Integer = MatrixGridView.FocusedRowHandle If rowHandle <= 0 Then Return End If Dim row As DataRow = MatrixGridView.GetDataRow(rowHandle) Dim prevRow As DataRow = MatrixGridView.GetDataRow(rowHandle - 1) row("intNumRow") = rowHandle - 1 prevRow("intNumRow") = rowHandle End Sub Private Sub btnDown_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnDown.Click Dim rowHandle As Integer = MatrixGridView.FocusedRowHandle If rowHandle >= MatrixGridView.RowCount - 1 Then Return End If Dim row As DataRow = MatrixGridView.GetDataRow(rowHandle) Dim nextRow As DataRow = MatrixGridView.GetDataRow(rowHandle + 1) row("intNumRow") = rowHandle + 1 nextRow("intNumRow") = rowHandle End Sub Public Overrides Function ValidateData() As Boolean If Not MyBase.ValidateData() Then Return False End If If VersionListTable.Select(String.Format("MatrixName = '{0}' and idfVersion<>{1}", Utils.Str(VersionTable.Rows(0)("MatrixName")).Replace("'", "''"), CurrentVersion)).Length > 0 Then ErrorForm.ShowWarningDirect(EidssMessages.Get("ErrDuplicateMatrixVersionName", "Matrix version with such name exists already. Please enter unique matrix version name")) txtVersionName.Select() Return False End If Return True End Function Public Overrides Function HasChanges() As Boolean 'we add this check on the case when error during dataloading occur. Without this 'the form will give an error during form closing If baseDataSet.Tables.Contains(AggregateMatrix_DB.TableVersionsList) Then Return Not baseDataSet.Tables(AggregateMatrix_DB.TableVersionsList).GetChanges() Is Nothing _ OrElse Not baseDataSet.Tables(AggregateMatrix_DB.TableMatrix).GetChanges() Is Nothing End If End Function End Class
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS_Admin/AggregateMTX/AggregateMatrixBase.vb
Visual Basic
bsd-2-clause
15,368
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System Imports System.Globalization Imports System.Linq Imports System.Text Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Partial Module ExpressionGenerator Private Structure StringPiece Public ReadOnly Value As String Public ReadOnly Kind As StringPieceKind Public Sub New(value As String, kind As StringPieceKind) Me.Value = value Me.Kind = kind End Sub Private Shared Function IsPrintable(c As Char) As Boolean Dim category = CharUnicodeInfo.GetUnicodeCategory(c) Return IsPrintable(category) AndAlso Not IsQuoteCharacter(c) End Function Private Shared Function IsPrintable(c As UnicodeCategory) As Boolean Return c <> UnicodeCategory.OtherNotAssigned AndAlso c <> UnicodeCategory.ParagraphSeparator AndAlso c <> UnicodeCategory.Control AndAlso c <> UnicodeCategory.Surrogate End Function Private Shared Function IsQuoteCharacter(c As Char) As Boolean Const DWCH_LSMART_DQ As Char = ChrW(&H201CS) '// DW left single Const DWCH_RSMART_DQ As Char = ChrW(&H201DS) '// DW right single smart quote Const DWCH_DQ As Char = ChrW(AscW(""""c) + (&HFF00US - &H20US)) '// DW dual quote Return c = DWCH_LSMART_DQ OrElse c = DWCH_RSMART_DQ OrElse c = DWCH_DQ End Function Public Function GenerateExpression() As ExpressionSyntax Select Case Me.Kind Case StringPieceKind.Normal Dim literal = VisualBasic.SymbolDisplay.FormatPrimitive(Me.Value, quoteStrings:=True, useHexadecimalNumbers:=False) Return SyntaxFactory.StringLiteralExpression( SyntaxFactory.StringLiteralToken(literal, Me.Value)) Case StringPieceKind.NonPrintable Return GenerateChrWExpression(Me.Value(0)) Case StringPieceKind.Cr Return GenerateStringConstantExpression("vbCr") Case StringPieceKind.Lf Return GenerateStringConstantExpression("vbLf") Case StringPieceKind.CrLf Return GenerateStringConstantExpression("vbCrLf") Case StringPieceKind.NullChar Return GenerateStringConstantExpression("vbNullChar") Case StringPieceKind.Back Return GenerateStringConstantExpression("vbBack") Case StringPieceKind.FormFeed Return GenerateStringConstantExpression("vbFormFeed") Case StringPieceKind.Tab Return GenerateStringConstantExpression("vbTab") Case StringPieceKind.VeriticalTab Return GenerateStringConstantExpression("vbVerticalTab") End Select Throw ExceptionUtilities.Unreachable End Function Private Shared Function GenerateStringConstantExpression(name As String) As MemberAccessExpressionSyntax Dim factory = New VisualBasicSyntaxGenerator() Dim result = GenerateMemberAccessExpression("Microsoft", "VisualBasic", "Constants", name) Return result.WithAdditionalAnnotations(Simplifier.Annotation) End Function Public Shared Function Split(value As String) As IList(Of StringPiece) Dim result = New List(Of StringPiece) Dim sb = New StringBuilder() Dim i = 0 While i < value.Length Dim c = value(i) i += 1 ' Handle unicode surrogates. If this character is a surrogate, but we get a ' viable surrogate pair, then just add the pair to the resultant string piece. Dim category = CharUnicodeInfo.GetUnicodeCategory(c) If category = UnicodeCategory.Surrogate Then Dim fullCategory = CharUnicodeInfo.GetUnicodeCategory(value, i - 1) If IsPrintable(fullCategory) Then sb.Append(c) sb.Append(value(i)) i += 1 Continue While End If End If If IsPrintable(c) Then sb.Append(c) Else If sb.Length > 0 Then result.Add(New StringPiece(sb.ToString(), StringPieceKind.Normal)) sb.Clear() End If If c = vbNullChar Then result.Add(New StringPiece(Nothing, StringPieceKind.NullChar)) ElseIf c = vbBack Then result.Add(New StringPiece(Nothing, StringPieceKind.Back)) ElseIf c = vbFormFeed Then result.Add(New StringPiece(Nothing, StringPieceKind.FormFeed)) ElseIf c = vbTab Then result.Add(New StringPiece(Nothing, StringPieceKind.Tab)) ElseIf c = vbVerticalTab Then result.Add(New StringPiece(Nothing, StringPieceKind.VeriticalTab)) ElseIf c = vbCr Then If i < value.Length AndAlso value(i) = vbLf Then result.Add(New StringPiece(Nothing, StringPieceKind.CrLf)) i = i + 1 Else result.Add(New StringPiece(Nothing, StringPieceKind.Cr)) End If ElseIf c = vbLf Then result.Add(New StringPiece(Nothing, StringPieceKind.Lf)) Else result.Add(New StringPiece(c, StringPieceKind.NonPrintable)) End If End If End While If sb.Length > 0 Then result.Add(New StringPiece(sb.ToString(), StringPieceKind.Normal)) sb.Clear() End If Return result End Function End Structure End Module End Namespace
DavidKarlas/roslyn
src/Workspaces/VisualBasic/Portable/CodeGeneration/ExpressionGenerator.StringPiece.vb
Visual Basic
apache-2.0
7,194
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection.Metadata Imports System.Reflection.PortableExecutable Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Partial Public Class InternalsVisibleToAndStrongNameTests Inherits BasicTestBase #Region "Helpers" Public Sub New() SigningTestHelpers.InstallKey() End Sub Private Shared ReadOnly s_keyPairFile As String = SigningTestHelpers.KeyPairFile Private Shared ReadOnly s_publicKeyFile As String = SigningTestHelpers.PublicKeyFile Private Shared ReadOnly s_publicKey As ImmutableArray(Of Byte) = SigningTestHelpers.PublicKey Private Shared ReadOnly s_defaultProvider As DesktopStrongNameProvider = New SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create(Of String)()) Private Shared Function GetProviderWithPath(keyFilePath As String) As DesktopStrongNameProvider Return New SigningTestHelpers.VirtualizedStrongNameProvider(ImmutableArray.Create(keyFilePath)) End Function Private Shared Sub VerifySigned(comp As Compilation) Using outStream = comp.EmitToStream() outStream.Position = 0 Dim headers = New PEHeaders(outStream) Dim flags = headers.CorHeader.Flags Assert.True(flags.HasFlag(CorFlags.StrongNameSigned)) End Using End Sub #End Region #Region "Naming Tests" <Fact> Public Sub PubKeyFromKeyFileAttribute() Dim x = s_keyPairFile Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""" & x & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim g = Guid.NewGuid() Dim other = VisualBasicCompilation.Create( g.ToString(), {VisualBasicSyntaxTree.ParseText(s)}, {MscorlibRef}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""" & keyFileName & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim syntaxTree = ParseAndVerify(s) ' verify failure with default assembly key file resolver Dim comp = CreateCompilationWithMscorlib({syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), {syntaxTree}, {MscorlibRef}, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim s = "<Assembly: System.Reflection.AssemblyKeyFile(""..\" & keyFileName & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim syntaxTree = ParseAndVerify(s) ' verify failure with default assembly key file resolver Dim comp As Compilation = CreateCompilationWithMscorlib({syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments("..\" & keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:={MscorlibRef}, syntaxTrees:={syntaxTree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, "TempSubDir\")))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyContainerAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptions_ReferenceResolver() Dim keyFileDir = Path.GetDirectoryName(s_keyPairFile) Dim keyFileName = Path.GetFileName(s_keyPairFile) Dim source = <![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> Dim references = {MscorlibRef} Dim syntaxTrees = {ParseAndVerify(source)} ' verify failure with default resolver Dim comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(s_defaultProvider)) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with keyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptionsJustPublicKey() Dim s = <compilation> <file name="Clavelle.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation> Dim other = CreateCompilationWithMscorlib(s, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) Assert.Empty(other.GetDiagnostics()) Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver() Dim publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile) Dim publicKeyFileName = Path.GetFileName(s_publicKeyFile) Dim source = <![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> Dim references = {MscorlibRef} Dim syntaxTrees = {ParseAndVerify(source)} ' verify failure with default resolver Dim comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) ' error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. ' warning CS7033: Delay signing was specified and requires a public key, but no public key was specified comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), Diagnostic(ERRID.WRN_DelaySignButNoKey)) Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty) ' verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = VisualBasicCompilation.Create( GetUniqueName(), references:=references, syntaxTrees:=syntaxTrees, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(True).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))) comp.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)) End Sub <Fact> Public Sub PubKeyFileNotFoundOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseExe.WithCryptoKeyFile("foo").WithStrongNameProvider(s_defaultProvider)) CompilationUtils.AssertTheseDeclarationDiagnostics(other, <errors> BC36980: Error extracting public key from file 'foo': <%= CodeAnalysisResources.FileNotFound %> </errors>) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub KeyFileAttributeEmpty() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyFile("")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub KeyContainerEmpty() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub PublicKeyFromOptions_DelaySigned() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey)) c.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)) Dim Metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()) Dim identity = Metadata.Module.ReadAssemblyIdentityOrThrow() Assert.True(identity.HasPublicKey) AssertEx.Equal(identity.PublicKey, s_publicKey) Assert.Equal(CorFlags.ILOnly, Metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags) End Sub <Fact> Public Sub PublicKeyFromOptions_OssSigned() ' attributes are ignored Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> <assembly: System.Reflection.AssemblyKeyFile("some file")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey)) c.VerifyDiagnostics() Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)) Dim Metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()) Dim identity = Metadata.Module.ReadAssemblyIdentityOrThrow() Assert.True(identity.HasPublicKey) AssertEx.Equal(identity.PublicKey, s_publicKey) Assert.Equal(CorFlags.ILOnly Or CorFlags.StrongNameSigned, Metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags) End Sub <Fact> Public Sub PublicKeyFromOptions_InvalidCompilationOptions() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll. WithCryptoPublicKey(ImmutableArray.Create(Of Byte)(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"). WithStrongNameProvider(s_defaultProvider)) AssertTheseDiagnostics(c, <error> BC2014: the value '01-02-03' is invalid for option 'CryptoPublicKey' BC2046: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. BC2046: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. </error>) End Sub <Fact> Public Sub PubKeyFileBogusOptions() Dim tmp = Temp.CreateFile().WriteAllBytes(New Byte() {1, 2, 3, 4}) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file> <![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(tmp.Path).WithStrongNameProvider(New DesktopStrongNameProvider())) other.VerifyDiagnostics( Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments(tmp.Path, CodeAnalysisResources.InvalidPublicKey)) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub <Fact> Public Sub PubKeyContainerBogusOptions() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseExe.WithCryptoKeyContainer("foo").WithStrongNameProvider(s_defaultProvider)) ' CompilationUtils.AssertTheseDeclarationDiagnostics(other, ' <errors> 'BC36981: Error extracting public key from container 'foo': Keyset does not exist (Exception from HRESULT: 0x80090016) ' </errors>) Dim err = other.GetDeclarationDiagnostics().Single() Assert.Equal(ERRID.ERR_PublicKeyContainerFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal("foo", DirectCast(err.Arguments(0), String)) Assert.True(DirectCast(err.Arguments(1), String).Contains("HRESULT: 0x80090016")) Assert.True(other.Assembly.Identity.PublicKey.IsEmpty) End Sub #End Region #Region "IVT Access checking" <Fact> Public Sub IVTBasicCompilation() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="HasIVTToCompilation"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim c As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccessButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Foo() End Sub End Class End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() CompilationUtils.AssertTheseDiagnostics(c, <error> BC30390: 'C.Friend Sub Foo()' is not accessible in this context because it is 'Friend'. o.Foo() ~~~~~ </error>) Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Foo() End Sub End Class End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) c2.VerifyDiagnostics() End Sub <Fact> Public Sub IVTBasicMetadata() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="HasIVTToCompilation"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim otherImage = other.EmitToArray() Dim c As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccessButCantHave"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Foo() End Sub End Class End Class ]]> </file> </compilation>, {MetadataReference.CreateFromImage(otherImage)}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) 'compilation should not succeed, and internals should not be imported. c.GetDiagnostics() 'gives "is not a member" error because internals were not imported because no IVT was found 'on HasIVTToCompilation that referred to WantsIVTAccessButCantHave CompilationUtils.AssertTheseDiagnostics(c, <error> BC30456: 'Foo' is not a member of 'C'. o.Foo() ~~~~~ </error>) Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class A Friend Class B Protected Sub New(o As C) o.Foo() End Sub End Class End Class ]]> </file> </compilation>, {MetadataReference.CreateFromImage(otherImage)}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) c2.VerifyDiagnostics() End Sub <Fact> Public Sub SignModuleKeyContainerBogus() Dim c1 As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("bogus")> Public Class A End Class ]]> </file> </compilation>, TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider)) 'shouldn't have an error. The attribute's contents are checked when the module is added. Dim reference = c1.EmitToImageReference() Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( (<compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>), {reference}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) 'BC36981: Error extracting public key from container 'bogus': Keyset does not exist (Exception from HRESULT: 0x80090016) 'c2.VerifyDiagnostics(Diagnostic(ERRID.ERR_PublicKeyContainerFailure).WithArguments("bogus", "Keyset does not exist (Exception from HRESULT: 0x80090016)")) Dim err = c2.GetDiagnostics(CompilationStage.Emit).Single() Assert.Equal(ERRID.ERR_PublicKeyContainerFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal("bogus", DirectCast(err.Arguments(0), String)) Assert.True(DirectCast(err.Arguments(1), String).Contains("HRESULT: 0x80090016")) End Sub <Fact> Public Sub SignModuleKeyFileBogus() Dim c1 As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyFile("bogus")> Public Class A End Class ]]> </file> </compilation>, TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider)) 'shouldn't have an error. The attribute's contents are checked when the module is added. Dim reference = c1.EmitToImageReference() Dim c2 As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( (<compilation name="WantsIVTAccess"> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>), {reference}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) c2.VerifyDiagnostics(Diagnostic(ERRID.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)) End Sub <Fact> Public Sub IVTSigned() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Foo() End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider)) Dim unused = requestor.Assembly.Identity requestor.VerifyDiagnostics() End Sub <Fact> Public Sub IVTErrorNotBothSigned() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class A Private Sub New(o As C) o.Foo() End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) Dim unused = requestor.Assembly.Identity 'gives "is not accessible" error because internals were imported because IVT was found CompilationUtils.AssertTheseDiagnostics(requestor, <error>BC30389: 'C' is not accessible in this context because it is 'Friend'. Private Sub New(o As C) ~ </error>) End Sub <Fact> Public Sub IVTDeferredSuccess() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C 'causes optimistic granting <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim unused = requestor.Assembly.Identity Assert.True(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) requestor.AssertNoDiagnostics() End Sub <Fact> Public Sub IVTDeferredFailSignMismatch() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim unused = requestor.Assembly.Identity CompilationUtils.AssertTheseDiagnostics(requestor, <error>BC36958: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the strong name signing state of the output assembly does not match that of the granting assembly.</error>) End Sub <Fact> Public Sub IVTDeferredFailKeyMismatch() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ 'key is wrong in the first digit <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim unused = requestor.Assembly.Identity CompilationUtils.AssertTheseDiagnostics(requestor, <errors>BC36957: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', but the public key of the output assembly does not match that specified by the attribute in the granting assembly.</errors>) End Sub <Fact> Public Sub IVTSuccessThroughIAssembly() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C 'causes optimistic granting <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Assert.True(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) End Sub <Fact> Public Sub IVTFailSignMismatchThroughIAssembly() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Friend Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) other.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Imports MyC=C <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class A End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(other)}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Assert.False(DirectCast(other.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) End Sub <WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")> <Fact> Public Sub IVTGivesAccessToUsingDifferentKeys() Dim giver As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Paul"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb")> Namespace ClassLibrary Friend Class FriendClass Public Sub Foo() End Sub End Class end Namespace ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2).WithStrongNameProvider(s_defaultProvider)) giver.VerifyDiagnostics() Dim requestor As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="John"> <file name="a.vb"><![CDATA[ Public Class ClassWithFriendMethod Friend Sub Test(A as ClassLibrary.FriendClass) End Sub End Class ]]> </file> </compilation>, {New VisualBasicCompilationReference(giver)}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Assert.True(DirectCast(giver.Assembly, IAssemblySymbol).GivesAccessTo(requestor.Assembly)) Assert.Empty(requestor.GetDiagnostics()) End Sub #End Region #Region "IVT instantiations" <Fact> Public Sub IVTHasCulture() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("WantsIVTAccess, Culture=neutral")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim expectedErrors = <error><![CDATA[ BC31534: Friend assembly reference 'WantsIVTAccess, Culture=neutral' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. <Assembly: InternalsVisibleTo("WantsIVTAccess, Culture=neutral")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error> CompilationUtils.AssertTheseDeclarationDiagnostics(other, expectedErrors) End Sub <Fact> Public Sub IVTNoKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("WantsIVTAccess")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim expectedErrors = <error><![CDATA[ BC31535: Friend assembly reference 'WantsIVTAccess' is invalid. Strong-name signed assemblies must specify a public key in their InternalsVisibleTo declarations. <Assembly: InternalsVisibleTo("WantsIVTAccess")> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></error> CompilationUtils.AssertTheseDeclarationDiagnostics(other, expectedErrors) End Sub #End Region #Region "Signing" <Fact> Public Sub MaxSizeKey() Dim pubKey = TestResources.General.snMaxSizePublicKeyString Const pubKeyToken = "1540923db30520b2" Dim pubKeyTokenBytes As Byte() = {&H15, &H40, &H92, &H3D, &HB3, &H5, &H20, &HB2} Dim comp = CreateCompilationWithMscorlib( <compilation> <file name="c.vb"> Imports System Imports System.Runtime.CompilerServices &lt;Assembly:InternalsVisibleTo("MaxSizeComp2, PublicKey=<%= pubKey %>, PublicKeyToken=<%= pubKeyToken %>")&gt; Friend Class C Public Shared Sub M() Console.WriteLine("Called M") End Sub End Class </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultProvider)) comp.VerifyEmitDiagnostics() Assert.True(comp.IsRealSigned) VerifySigned(comp) Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken) Dim src = <compilation name="MaxSizeComp2"> <file name="c.vb"> Class D Public Shared Sub Main() C.M() End Sub End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlib(src, references:={comp.ToMetadataReference()}, options:=TestOptions.ReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(comp2, expectedOutput:="Called M") Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken) Dim comp3 = CreateCompilationWithMscorlib(src, references:={comp.EmitToImageReference()}, options:=TestOptions.ReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(comp3, expectedOutput:="Called M") Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey) Assert.Equal(Of Byte)(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken) End Sub <Fact> Public Sub SignIt() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(CorFlags.StrongNameSigned, peHeaders.CorHeader.Flags And CorFlags.StrongNameSigned) End Sub <Fact> Public Sub SignItWithOnlyPublicKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Sam"> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider)) Using outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors> BC36961: Key file '<%= s_publicKeyFile %>' is missing the private key needed for signing. </errors>) End Using other = other.WithOptions(TestOptions.ReleaseModule.WithCryptoKeyFile(s_publicKeyFile)) Dim assembly As VisualBasicCompilation = CreateCompilationWithMscorlibAndReferences( <compilation name="Sam2"> <file name="a.vb"> </file> </compilation>, {other.EmitToImageReference()}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Using outStrm = New MemoryStream() Dim emitResult = assembly.Emit(outStrm) CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors> BC36961: Key file '<%= s_publicKeyFile %>' is missing the private key needed for signing. </errors>) End Using End Sub <Fact> Public Sub DelaySignItWithOnlyPublicKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Sam"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(other) End Sub <Fact> Public Sub DelaySignButNoKey() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) ' Dev11: vbc : warning BC40010: Possible problem detected while building assembly 'VBTestD': Delay signing was requested, but no key was given ' warning BC41008: Use command-line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySignAttribute'. CompilationUtils.AssertTheseDiagnostics(emitResult.Diagnostics, <errors>BC40060: Delay signing was specified and requires a public key, but no public key was specified.</errors>) Assert.True(emitResult.Success) End Sub <Fact> Public Sub SignInMemory() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.True(emitResult.Success) End Sub <WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")> <WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")> <Fact> Public Sub InvalidAssemblyName() Dim il = <![CDATA[ .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } ]]> Dim vb = <compilation> <file name="a.vb"><![CDATA[ Public Class Derived Inherits Base End Class ]]> </file> </compilation> Dim ilRef = CompileIL(il.Value, appendDefaultHeader:=False) Dim comp = CreateCompilationWithMscorlibAndReferences(vb, {ilRef}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) ' NOTE: dev10 reports ERR_FriendAssemblyNameInvalid, but Roslyn won't (DevDiv #15099). comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InaccessibleSymbol2, "Base").WithArguments("Base", "Friend")) End Sub <Fact> Public Sub DelaySignWithAssemblySignatureKey() '//Note that this SignatureKey is some random one that I found in the devdiv build. '//It is not related to the other keys we use in these tests. '//In the native compiler, when the AssemblySignatureKey attribute is present, and '//the binary is configured for delay signing, the contents of the assemblySignatureKey attribute '//(rather than the contents of the keyfile or container) are used to compute the size needed to '//reserve in the binary for its signature. Signing using this key is only supported via sn.exe Dim other = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> <Assembly: System.Reflection.AssemblySignatureKey("002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3", "a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, TestOptions.ReleaseDll.WithDelaySign(True).WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) ' confirm header has expected SN signature size Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(256, peHeaders.CorHeader.StrongNameSignatureDirectory.Size) End Sub ''' <summary> ''' Won't fix (easy to be tested here) ''' </summary> <Fact(), WorkItem(529953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529953"), WorkItem(530112, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530112")> Public Sub DeclareAssemblyKeyNameAndFile_BC41008() Dim src = "<Assembly: System.Reflection.AssemblyKeyName(""Key1"")>" & vbCrLf & "<Assembly: System.Reflection.AssemblyKeyFile(""" & s_keyPairFile & """)>" & vbCrLf & "Public Class C" & vbCrLf & "End Class" Dim tree = ParseAndVerify(src) Dim comp = CreateCompilationWithMscorlib({tree}, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) ' Native Compiler: 'warning BC41008: Use command-line option '/keycontainer' or appropriate project settings instead of 'System.Reflection.AssemblyKeyNameAttribute() '. ' <Assembly: System.Reflection.AssemblyKeyName("Key1")> ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 'warning BC41008: Use command-line option '/keyfile' or appropriate project settings instead of 'System.Reflection.AssemblyKeyFileAttribute() '. '<Assembly: System.Reflection.AssemblyKeyFile("Key2.snk")> ' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ comp.VerifyDiagnostics() ' Diagnostic(ERRID.WRN_UseSwitchInsteadOfAttribute, "System.Reflection.AssemblyKeyName(""Key1""").WithArguments("/keycontainer"), ' Diagnostic(ERRID.WRN_UseSwitchInsteadOfAttribute, "System.Reflection.AssemblyKeyFile(""Key2.snk""").WithArguments("/keyfile")) Dim outStrm = New MemoryStream() Dim emitResult = comp.Emit(outStrm) Assert.True(emitResult.Success) End Sub Private Sub ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput( moduleContents As Stream, expectedModuleAttr As AttributeDescription ) ' a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute ' parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the ' resulting assembly is signed with the key referred to by the aforementioned attribute. Dim success As EmitResult Dim tempFile = Temp.CreateFile() moduleContents.Position = 0 Using metadata = ModuleMetadata.CreateFromStream(moduleContents) Dim flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags ' confirm file does not claim to be signed Assert.Equal(0, CInt(flags And CorFlags.StrongNameSigned)) Dim token As EntityHandle = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere") Assert.False(token.IsNil) ' could the magic type ref be located? If not then the attribute's not there. Dim attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr) Assert.Equal(1, attrInfos.Count()) Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class Z End Class ]]> </file> </compilation> ' now that the module checks out, ensure that adding it to a compilation outputting a dll ' results in a signed assembly. Dim assemblyComp = CreateCompilationWithMscorlibAndReferences(source, {metadata.GetReference()}, TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Using finalStrm = tempFile.Open() success = assemblyComp.Emit(finalStrm) End Using End Using success.Diagnostics.Verify() Assert.True(success.Success) AssertFileIsSigned(tempFile) End Sub Private Shared Sub AssertFileIsSigned(file As TempFile) ' TODO should check to see that the output was actually signed Using peStream = New FileStream(file.Path, FileMode.Open) Dim flags = New PEHeaders(peStream).CorHeader.Flags Assert.Equal(CorFlags.StrongNameSigned, flags And CorFlags.StrongNameSigned) End Using End Sub <Fact> Public Sub SignModuleKeyFileAttr() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>Assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider)) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(other.EmitToStream(), AttributeDescription.AssemblyKeyFileAttribute) End Sub <Fact> Public Sub SignModuleKeyContainerAttr() Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine() Dim source = <compilation> <file name="a.vb"> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine_1() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class ]]></file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyContainerCmdLine_2() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("bogus")> Public Class C End Class ]]></file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyContainer("roslynTestContainer").WithStrongNameProvider(s_defaultProvider)) AssertTheseDiagnostics(other, <expected> BC37207: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. </expected>) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine() Dim source = <compilation> <file name="a.vb"> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute) End Sub <WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")> <Fact> Public Sub SignModuleKeyFileCmdLine_1() Dim x = s_keyPairFile Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>assembly: System.Reflection.AssemblyKeyFile("<%= x %>")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim success = other.Emit(outStrm) Assert.True(success.Success) ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute) End Sub <Fact> Public Sub SignModuleKeyFileCmdLine_2() Dim source = <compilation> <file name="a.vb"> <![CDATA[<]]>assembly: System.Reflection.AssemblyKeyFile("bogus")> Public Class C End Class </file> </compilation> Dim other = CreateCompilationWithMscorlib(source, TestOptions.ReleaseModule.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) AssertTheseDiagnostics(other, <expected> BC37207: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. </expected>) End Sub <Fact> <WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")> Public Sub Bug529779_1() Dim unsigned As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C1 End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() Dim x as New System.Guid() System.Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(other.WithReferences({other.References(0), New VisualBasicCompilationReference(unsigned)})).VerifyDiagnostics() CompileAndVerify(other.WithReferences({other.References(0), MetadataReference.CreateFromImage(unsigned.EmitToArray)})).VerifyDiagnostics() End Sub <Fact> <WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")> Public Sub Bug529779_2() Dim unsigned As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation name="Unsigned"> <file name="a.vb"><![CDATA[ Public Class C1 End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C Friend Sub Foo() Dim x as New C1() System.Console.WriteLine(x) End Sub End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim comps = {other.WithReferences({other.References(0), New VisualBasicCompilationReference(unsigned)}), other.WithReferences({other.References(0), MetadataReference.CreateFromImage(unsigned.EmitToArray)})} For Each comp In comps Dim outStrm = New MemoryStream() Dim emitResult = comp.Emit(outStrm) ' Dev12 reports an error Assert.True(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC41997: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. </expected>) Next End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_1() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim peHeaders = New PEHeaders(other.EmitToStream()) Assert.Equal(CorFlags.StrongNameSigned, peHeaders.CorHeader.Flags And CorFlags.StrongNameSigned) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_2() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_3() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_keyPairFile).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) ' AssertTheseDiagnostics(emitResult.Diagnostics, '<expected> 'BC36980: Error extracting public key from file '<%= KeyPairFile %>': Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) '</expected>) Dim err = emitResult.Diagnostics.Single() Assert.Equal(ERRID.ERR_PublicKeyFileFailure, err.Code) Assert.Equal(2, err.Arguments.Count) Assert.Equal(s_keyPairFile, DirectCast(err.Arguments(0), String)) Assert.True(DirectCast(err.Arguments(1), String).EndsWith(" HRESULT: 0x80131423)", StringComparison.Ordinal)) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_4() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_5() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", "FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(other) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_6() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( Nothing, "bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819")> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) Dim outStrm = New MemoryStream() Dim emitResult = other.Emit(outStrm) Assert.False(emitResult.Success) AssertTheseDiagnostics(emitResult.Diagnostics, <expected> BC37209: Invalid signature public key specified in AssemblySignatureKeyAttribute. Nothing, ~~~~~~~ </expected>) End Sub <Fact> Public Sub AssemblySignatureKeyAttribute_7() Dim other As VisualBasicCompilation = CreateCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblySignatureKeyAttribute( "00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Nothing)> Public Class C Friend Sub Foo() End Sub End Class ]]> </file> </compilation>, {MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(True).WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(other) End Sub #End Region Public Sub PublicSignCore(options As VisualBasicCompilationOptions) Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source, options:=options) PublicSignCore(compilation) End Sub Public Sub PublicSignCore(compilation As Compilation) Assert.True(compilation.Options.PublicSign) Assert.Null(compilation.Options.DelaySign) Dim stream As New MemoryStream() Dim emitResult = compilation.Emit(stream) Assert.True(emitResult.Success) Assert.True(emitResult.Diagnostics.IsEmpty) stream.Position = 0 Using reader As New PEReader(stream) Assert.True(reader.HasMetadata) Dim flags = reader.PEHeaders.CorHeader.Flags Assert.True(flags.HasFlag(CorFlags.StrongNameSigned)) End Using End Sub <Fact> Public Sub PublicSign_NoKey() Dim options = TestOptions.ReleaseDll.WithPublicSign(True) Dim comp = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) Assert.True(comp.Options.PublicSign) Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty) End Sub <Fact> Public Sub KeyFileFromAttributes_PublicSign() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyFile("test.snk")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithPublicSign(True)) AssertTheseDiagnostics(c, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) Assert.True(c.Options.PublicSign) End Sub <Fact> Public Sub KeyContainerFromAttributes_PublicSign() Dim source = <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> Public Class C End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source, options:=TestOptions.ReleaseDll.WithPublicSign(True)) AssertTheseDiagnostics(c, <errors> BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) Assert.True(c.Options.PublicSign) End Sub <Fact> Public Sub PublicSign_FromKeyFileNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromPublicKeyFileNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromKeyFileAndStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey2) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithStrongNameProvider(s_defaultProvider) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_FromKeyFileAndNoStrongNameProvider() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey2) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) PublicSignCore(options) End Sub <Fact> Public Sub PublicSign_KeyContainerOnly() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation> Dim options = TestOptions.ReleaseDll.WithCryptoKeyContainer("testContainer").WithPublicSign(True) Dim compilation = CreateCompilationWithMscorlib(source, options:=options) AssertTheseDiagnostics(compilation, <errors> BC2046: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. BC37254: Public sign was specified and requires a public key, but no public key was specified </errors>) End Sub <Fact> Public Sub PublicSign_IgnoreSourceAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyKeyName("roslynTestContainer")> <Assembly: System.Reflection.AssemblyKeyFile("some file")> Public Class C End Class ]]> </file> </compilation> Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) Dim compilation = CreateCompilationWithMscorlib(source, options:=options) PublicSignCore(compilation) End Sub <Fact> Public Sub PublicSign_DelaySignAttribute() Dim source = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDelaySign(True)> Public Class C End Class ]]> </file> </compilation> Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True) Dim comp = CreateCompilationWithMscorlib(source, options:=options) AssertTheseDiagnostics(comp, <errors> BC37207: Attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file conflicts with option 'PublicSign'. </errors>) Assert.True(comp.Options.PublicSign) End Sub <Fact> Public Sub PublicSignAndDelaySign() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithDelaySign(True) Dim comp = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp, <errors> BC2046: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. </errors>) Assert.True(comp.Options.PublicSign) Assert.True(comp.Options.DelaySign) End Sub <Fact> Public Sub PublicSignAndDelaySignFalse() Dim snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey) Dim options = TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(True).WithDelaySign(False) Dim comp = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Public Class C End Class ]]> </file> </compilation>, options:=options ) AssertTheseDiagnostics(comp) Assert.True(comp.Options.PublicSign) Assert.False(comp.Options.DelaySign) End Sub <Fact, WorkItem(769840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769840")> Public Sub Bug769840() Dim ca = CreateCompilationWithMscorlib( <compilation name="Bug769840_A"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Bug769840_B, PublicKey=0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4")> Friend Class A Public Value As Integer = 3 End Class ]]></file> </compilation>, options:=TestOptions.ReleaseDll.WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlibAndReferences( <compilation name="Bug769840_B"> <file name="a.vb"><![CDATA[ Friend Class B Public Function GetA() As A Return New A() End Function End Class ]]></file> </compilation>, {New VisualBasicCompilationReference(ca)}, options:=TestOptions.ReleaseModule.WithStrongNameProvider(s_defaultProvider)) CompileAndVerify(cb, verify:=False).Diagnostics.Verify() End Sub <Fact, WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")> Public Sub Bug1072350() Dim sourceA As XElement = <compilation name="ClassLibrary2"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("X ")> Friend Class A Friend Shared I As Integer = 42 End Class]]> </file> </compilation> Dim sourceB As XElement = <compilation name="X"> <file name="b.vb"><![CDATA[ Class B Shared Sub Main() System.Console.Write(A.I) End Sub End Class]]> </file> </compilation> Dim ca = CreateCompilationWithMscorlib(sourceA, options:=TestOptions.ReleaseDll) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlib(sourceB, options:=TestOptions.ReleaseExe, references:={New VisualBasicCompilationReference(ca)}) CompileAndVerify(cb, expectedOutput:="42").Diagnostics.Verify() End Sub <Fact, WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")> Public Sub Bug1072339() Dim sourceA As XElement = <compilation name="ClassLibrary2"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("x")> Friend Class A Friend Shared I As Integer = 42 End Class]]> </file> </compilation> Dim sourceB As XElement = <compilation name="x"> <file name="b.vb"><![CDATA[ Class B Shared Sub Main() System.Console.Write(A.I) End Sub End Class]]> </file> </compilation> Dim ca = CreateCompilationWithMscorlib(sourceA, options:=TestOptions.ReleaseDll) CompileAndVerify(ca) Dim cb = CreateCompilationWithMscorlib(sourceB, options:=TestOptions.ReleaseExe, references:={New VisualBasicCompilationReference(ca)}) CompileAndVerify(cb, expectedOutput:="42").Diagnostics.Verify() End Sub <Fact, WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")> Public Sub Bug1095618() Dim source As XElement = <compilation name="a"> <file name="a.vb"><![CDATA[ <Assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")> ]]></file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyNameInvalid, "Assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 2)) End Sub End Class
KevinH-MS/roslyn
src/Compilers/VisualBasic/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.vb
Visual Basic
apache-2.0
79,885
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmIcon Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.btnAddGoldCoinIcon = New System.Windows.Forms.Button Me.btnUpdateGoldCoinIcon = New System.Windows.Forms.Button Me.btnAddParcelIcon = New System.Windows.Forms.Button Me.btnUpdateParcelIcon = New System.Windows.Forms.Button Me.btnRemoveGoldCoinIcon = New System.Windows.Forms.Button Me.btnRemoveParcelIcon = New System.Windows.Forms.Button Me.btnRemoveAll = New System.Windows.Forms.Button Me.SuspendLayout() ' 'btnAddGoldCoinIcon ' Me.btnAddGoldCoinIcon.Location = New System.Drawing.Point(12, 12) Me.btnAddGoldCoinIcon.Name = "btnAddGoldCoinIcon" Me.btnAddGoldCoinIcon.Size = New System.Drawing.Size(131, 23) Me.btnAddGoldCoinIcon.TabIndex = 0 Me.btnAddGoldCoinIcon.Text = "Add Gold Coin Icon" Me.btnAddGoldCoinIcon.UseVisualStyleBackColor = True ' 'btnUpdateGoldCoinIcon ' Me.btnUpdateGoldCoinIcon.Location = New System.Drawing.Point(149, 12) Me.btnUpdateGoldCoinIcon.Name = "btnUpdateGoldCoinIcon" Me.btnUpdateGoldCoinIcon.Size = New System.Drawing.Size(131, 23) Me.btnUpdateGoldCoinIcon.TabIndex = 1 Me.btnUpdateGoldCoinIcon.Text = "Update Gold Coin Icon" Me.btnUpdateGoldCoinIcon.UseVisualStyleBackColor = True ' 'btnAddParcelIcon ' Me.btnAddParcelIcon.Location = New System.Drawing.Point(12, 41) Me.btnAddParcelIcon.Name = "btnAddParcelIcon" Me.btnAddParcelIcon.Size = New System.Drawing.Size(131, 23) Me.btnAddParcelIcon.TabIndex = 2 Me.btnAddParcelIcon.Text = "Add Parcel Icon" Me.btnAddParcelIcon.UseVisualStyleBackColor = True ' 'btnUpdateParcelIcon ' Me.btnUpdateParcelIcon.Location = New System.Drawing.Point(149, 41) Me.btnUpdateParcelIcon.Name = "btnUpdateParcelIcon" Me.btnUpdateParcelIcon.Size = New System.Drawing.Size(131, 23) Me.btnUpdateParcelIcon.TabIndex = 3 Me.btnUpdateParcelIcon.Text = "Update Parcel Icon" Me.btnUpdateParcelIcon.UseVisualStyleBackColor = True ' 'btnRemoveGoldCoinIcon ' Me.btnRemoveGoldCoinIcon.Location = New System.Drawing.Point(286, 12) Me.btnRemoveGoldCoinIcon.Name = "btnRemoveGoldCoinIcon" Me.btnRemoveGoldCoinIcon.Size = New System.Drawing.Size(131, 23) Me.btnRemoveGoldCoinIcon.TabIndex = 4 Me.btnRemoveGoldCoinIcon.Text = "Remove Gold Coin Icon" Me.btnRemoveGoldCoinIcon.UseVisualStyleBackColor = True ' 'btnRemoveParcelIcon ' Me.btnRemoveParcelIcon.Location = New System.Drawing.Point(286, 41) Me.btnRemoveParcelIcon.Name = "btnRemoveParcelIcon" Me.btnRemoveParcelIcon.Size = New System.Drawing.Size(131, 23) Me.btnRemoveParcelIcon.TabIndex = 5 Me.btnRemoveParcelIcon.Text = "Remove Parcel Icon" Me.btnRemoveParcelIcon.UseVisualStyleBackColor = True ' 'btnRemoveAll ' Me.btnRemoveAll.Location = New System.Drawing.Point(286, 70) Me.btnRemoveAll.Name = "btnRemoveAll" Me.btnRemoveAll.Size = New System.Drawing.Size(131, 23) Me.btnRemoveAll.TabIndex = 6 Me.btnRemoveAll.Text = "Remove All" Me.btnRemoveAll.UseVisualStyleBackColor = True ' 'frmIcon ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(429, 100) Me.Controls.Add(Me.btnRemoveAll) Me.Controls.Add(Me.btnRemoveParcelIcon) Me.Controls.Add(Me.btnRemoveGoldCoinIcon) Me.Controls.Add(Me.btnUpdateParcelIcon) Me.Controls.Add(Me.btnAddParcelIcon) Me.Controls.Add(Me.btnUpdateGoldCoinIcon) Me.Controls.Add(Me.btnAddGoldCoinIcon) Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.MaximizeBox = False Me.Name = "frmIcon" Me.Text = "Icon" Me.ResumeLayout(False) End Sub Friend WithEvents btnAddGoldCoinIcon As System.Windows.Forms.Button Friend WithEvents btnUpdateGoldCoinIcon As System.Windows.Forms.Button Friend WithEvents btnAddParcelIcon As System.Windows.Forms.Button Friend WithEvents btnUpdateParcelIcon As System.Windows.Forms.Button Friend WithEvents btnRemoveGoldCoinIcon As System.Windows.Forms.Button Friend WithEvents btnRemoveParcelIcon As System.Windows.Forms.Button Friend WithEvents btnRemoveAll As System.Windows.Forms.Button End Class
gareox/tibiaapi
apps/Smart Update Test/frmIcon.Designer.vb
Visual Basic
mit
5,656
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Composition Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax) Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel) As Boolean Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper( current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing) End Function End Class End Namespace
VSadov/roslyn
src/Features/VisualBasic/Portable/RemoveUnnecessaryParentheses/VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider.vb
Visual Basic
apache-2.0
1,046
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Threading Imports System.Reflection.Metadata Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports System.Reflection Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE ''' <summary> ''' The class to represent all generic type parameters imported from a PE/module. ''' </summary> ''' <remarks></remarks> Friend NotInheritable Class PETypeParameterSymbol Inherits TypeParameterSymbol Private ReadOnly _containingSymbol As Symbol ' Could be PENamedType or a PEMethod Private ReadOnly _handle As GenericParameterHandle Private _lazyCustomAttributes As ImmutableArray(Of VisualBasicAttributeData) #Region "Metadata" Private ReadOnly _name As String Private ReadOnly _ordinal As UShort ' 0 for first, 1 for second, ... Private ReadOnly _flags As GenericParameterAttributes #End Region Private _lazyConstraintTypes As ImmutableArray(Of TypeSymbol) ''' <summary> ''' First error calculating bounds. ''' </summary> Private _lazyBoundsErrorInfo As DiagnosticInfo = ErrorFactory.EmptyErrorInfo ' Indicates unknown state. Friend Sub New( moduleSymbol As PEModuleSymbol, definingNamedType As PENamedTypeSymbol, ordinal As UShort, handle As GenericParameterHandle ) Me.New(moduleSymbol, DirectCast(definingNamedType, Symbol), ordinal, handle) End Sub Friend Sub New( moduleSymbol As PEModuleSymbol, definingMethod As PEMethodSymbol, ordinal As UShort, handle As GenericParameterHandle ) Me.New(moduleSymbol, DirectCast(definingMethod, Symbol), ordinal, handle) End Sub Private Sub New( moduleSymbol As PEModuleSymbol, definingSymbol As Symbol, ordinal As UShort, handle As GenericParameterHandle ) Debug.Assert(moduleSymbol IsNot Nothing) Debug.Assert(definingSymbol IsNot Nothing) Debug.Assert(ordinal >= 0) Debug.Assert(Not handle.IsNil) _containingSymbol = definingSymbol Dim flags As GenericParameterAttributes Try moduleSymbol.Module.GetGenericParamPropsOrThrow(handle, _name, flags) Catch mrEx As BadImageFormatException If _name Is Nothing Then _name = String.Empty End If _lazyBoundsErrorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me) End Try ' Clear the '.ctor' flag if both '.ctor' and 'valuetype' are ' set since '.ctor' is redundant in that case. _flags = If((flags And GenericParameterAttributes.NotNullableValueTypeConstraint) = 0, flags, flags And Not GenericParameterAttributes.DefaultConstructorConstraint) _ordinal = ordinal _handle = handle End Sub Public Overrides ReadOnly Property TypeParameterKind As TypeParameterKind Get Return If(Me.ContainingSymbol.Kind = SymbolKind.Method, TypeParameterKind.Method, TypeParameterKind.Type) End Get End Property Public Overrides ReadOnly Property Ordinal As Integer Get Return _ordinal End Get End Property Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Friend ReadOnly Property Handle As GenericParameterHandle Get Return Me._handle End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _containingSymbol End Get End Property Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol Get Return _containingSymbol.ContainingAssembly End Get End Property Public Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) If _lazyCustomAttributes.IsDefault Then Dim containingPEModuleSymbol = DirectCast(ContainingModule(), PEModuleSymbol) containingPEModuleSymbol.LoadCustomAttributes(_handle, _lazyCustomAttributes) End If Return _lazyCustomAttributes End Function Friend Overrides ReadOnly Property ConstraintTypesNoUseSiteDiagnostics As ImmutableArray(Of TypeSymbol) Get EnsureAllConstraintsAreResolved() Return _lazyConstraintTypes End Get End Property Private Function GetDeclaredConstraints() As ImmutableArray(Of TypeParameterConstraint) Dim constraintsBuilder = ArrayBuilder(Of TypeParameterConstraint).GetInstance() If HasConstructorConstraint Then constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.Constructor, Nothing)) End If If HasReferenceTypeConstraint Then constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ReferenceType, Nothing)) End If If HasValueTypeConstraint Then constraintsBuilder.Add(New TypeParameterConstraint(TypeParameterConstraintKind.ValueType, Nothing)) End If Dim containingMethod As PEMethodSymbol = Nothing Dim containingType As PENamedTypeSymbol If _containingSymbol.Kind = SymbolKind.Method Then containingMethod = DirectCast(_containingSymbol, PEMethodSymbol) containingType = DirectCast(containingMethod.ContainingSymbol, PENamedTypeSymbol) Else containingType = DirectCast(_containingSymbol, PENamedTypeSymbol) End If Dim moduleSymbol = containingType.ContainingPEModule Dim metadataReader = moduleSymbol.Module.MetadataReader Dim constraints As GenericParameterConstraintHandleCollection Try constraints = metadataReader.GetGenericParameter(_handle).GetConstraints() Catch mrEx As BadImageFormatException constraints = Nothing Interlocked.CompareExchange(_lazyBoundsErrorInfo, ErrorFactory.ErrorInfo(ERRID.ERR_UnsupportedType1, Me), ErrorFactory.EmptyErrorInfo) End Try If constraints.Count > 0 Then Dim tokenDecoder As MetadataDecoder If containingMethod IsNot Nothing Then tokenDecoder = New MetadataDecoder(moduleSymbol, containingMethod) Else tokenDecoder = New MetadataDecoder(moduleSymbol, containingType) End If For Each constraintHandle In constraints Dim constraint = metadataReader.GetGenericParameterConstraint(constraintHandle) Dim constraintTypeHandle = constraint.Type Dim typeSymbol As TypeSymbol = tokenDecoder.GetTypeOfToken(constraintTypeHandle) ' Drop 'System.ValueType' constraint type if the 'valuetype' constraint was also specified. If ((_flags And GenericParameterAttributes.NotNullableValueTypeConstraint) <> 0) AndAlso (typeSymbol.SpecialType = Microsoft.CodeAnalysis.SpecialType.System_ValueType) Then Continue For End If typeSymbol = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeSymbol, constraintHandle, moduleSymbol) constraintsBuilder.Add(New TypeParameterConstraint(typeSymbol, Nothing)) Next End If Return constraintsBuilder.ToImmutableAndFree() End Function Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return _containingSymbol.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property Public Overrides ReadOnly Property HasConstructorConstraint As Boolean Get Return (_flags And GenericParameterAttributes.DefaultConstructorConstraint) <> 0 End Get End Property Public Overrides ReadOnly Property HasReferenceTypeConstraint As Boolean Get Return (_flags And GenericParameterAttributes.ReferenceTypeConstraint) <> 0 End Get End Property Public Overrides ReadOnly Property HasValueTypeConstraint As Boolean Get Return (_flags And GenericParameterAttributes.NotNullableValueTypeConstraint) <> 0 End Get End Property Public Overrides ReadOnly Property Variance As VarianceKind Get Return CType((_flags And GenericParameterAttributes.VarianceMask), VarianceKind) End Get End Property Friend Overrides Sub EnsureAllConstraintsAreResolved() If _lazyConstraintTypes.IsDefault Then Dim typeParameters = If(_containingSymbol.Kind = SymbolKind.Method, DirectCast(_containingSymbol, PEMethodSymbol).TypeParameters, DirectCast(_containingSymbol, PENamedTypeSymbol).TypeParameters) EnsureAllConstraintsAreResolved(typeParameters) End If End Sub Friend Overrides Sub ResolveConstraints(inProgress As ConsList(Of TypeParameterSymbol)) Debug.Assert(Not inProgress.Contains(Me)) Debug.Assert(Not inProgress.Any() OrElse inProgress.Head.ContainingSymbol Is ContainingSymbol) If _lazyConstraintTypes.IsDefault Then Dim diagnosticsBuilder = ArrayBuilder(Of TypeParameterDiagnosticInfo).GetInstance() Dim inherited = (_containingSymbol.Kind = SymbolKind.Method) AndAlso DirectCast(_containingSymbol, MethodSymbol).IsOverrides ' Check direct constraints on the type parameter to generate any use-site errors ' (for example, the cycle in ".class public A<(!T)T>"). It's necessary to check for such ' errors because invalid constraints are dropped in those cases so use of such ' types/methods is otherwise valid. It shouldn't be necessary to check indirect ' constraints because any indirect constraints are retained, even if invalid, so ' references to such types/methods cannot be satisfied for specific type arguments. ' (An example of an indirect constraint conflict, U in ".class public C<(A)T, (!T, B)U>", ' which cannot be satisfied if A and B are from different hierarchies.) It also isn't ' necessary to report redundant constraints since redundant constraints are still ' valid. Redundant constraints are dropped silently. Dim constraints = Me.RemoveDirectConstraintConflicts(GetDeclaredConstraints(), inProgress.Prepend(Me), DirectConstraintConflictKind.None, diagnosticsBuilder) Dim errorInfo = If(diagnosticsBuilder.Count > 0, diagnosticsBuilder(0).DiagnosticInfo, Nothing) diagnosticsBuilder.Free() Interlocked.CompareExchange(_lazyBoundsErrorInfo, errorInfo, ErrorFactory.EmptyErrorInfo) ImmutableInterlocked.InterlockedInitialize(_lazyConstraintTypes, GetConstraintTypesOnly(constraints)) End If Debug.Assert(_lazyBoundsErrorInfo IsNot ErrorFactory.EmptyErrorInfo) End Sub Friend Overrides Function GetConstraintsUseSiteErrorInfo() As DiagnosticInfo EnsureAllConstraintsAreResolved() Debug.Assert(_lazyBoundsErrorInfo IsNot ErrorFactory.EmptyErrorInfo) Return _lazyBoundsErrorInfo End Function ''' <remarks> ''' This is for perf, not for correctness. ''' </remarks> Friend Overrides ReadOnly Property DeclaringCompilation As VisualBasicCompilation Get Return Nothing End Get End Property End Class End Namespace
mmitche/roslyn
src/Compilers/VisualBasic/Portable/Symbols/Metadata/PE/PETypeParameterSymbol.vb
Visual Basic
apache-2.0
13,205
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "fPedidos_TECHNOIP" '-------------------------------------------------------------------------------------------' Partial Class fPedidos_TECHNOIP Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim loConsulta As New StringBuilder() loConsulta.AppendLine(" SELECT Pedidos.Cod_Cli, ") loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Pedidos.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE ") loConsulta.AppendLine(" (CASE WHEN (Pedidos.Nom_Cli = '') THEN Clientes.Nom_Cli ELSE Pedidos.Nom_Cli END) END) AS Nom_Cli, ") loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Pedidos.Nom_Cli = '') THEN Clientes.Rif ELSE ") loConsulta.AppendLine(" (CASE WHEN (Pedidos.Rif = '') THEN Clientes.Rif ELSE Pedidos.Rif END) END) AS Rif, ") loConsulta.AppendLine(" Clientes.Nit, ") loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Pedidos.Nom_Cli = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE ") loConsulta.AppendLine(" (CASE WHEN (SUBSTRING(Pedidos.Dir_Fis,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Fis,1, 200) ELSE SUBSTRING(Pedidos.Dir_Fis,1, 200) END) END) AS Dir_Fis, ") loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Pedidos.Nom_Cli = '') THEN SUBSTRING(Clientes.Dir_Ent,1, 200) ELSE ") loConsulta.AppendLine(" (CASE WHEN (SUBSTRING(Pedidos.Dir_Ent,1, 200) = '') THEN SUBSTRING(Clientes.Dir_Ent,1, 200) ELSE SUBSTRING(Pedidos.Dir_Ent,1, 200) END) END) AS Dir_Ent, ") loConsulta.AppendLine(" (CASE WHEN (Clientes.Generico = 0 AND Pedidos.Nom_Cli = '') THEN Clientes.Telefonos ELSE ") loConsulta.AppendLine(" (CASE WHEN (Pedidos.Telefonos = '') THEN Clientes.Telefonos ELSE Pedidos.Telefonos END) END) AS Telefonos, ") loConsulta.AppendLine(" Clientes.Fax, ") loConsulta.AppendLine(" Pedidos.Nom_Cli As Nom_Gen, ") loConsulta.AppendLine(" Pedidos.Rif As Rif_Gen, ") loConsulta.AppendLine(" Pedidos.Nit As Nit_Gen, ") loConsulta.AppendLine(" Pedidos.Dir_Fis As Dir_Gen, ") loConsulta.AppendLine(" Pedidos.Telefonos As Tel_Gen, ") loConsulta.AppendLine(" Pedidos.Documento, ") loConsulta.AppendLine(" Pedidos.Por_Des1 AS Por_Des1_Enc, ") loConsulta.AppendLine(" Pedidos.Mon_Des1 AS Mon_Des1_Enc, ") loConsulta.AppendLine(" Pedidos.Por_Rec1 AS Por_Rec1_Enc, ") loConsulta.AppendLine(" Pedidos.Mon_Rec1 AS Mon_Rec1_Enc, ") loConsulta.AppendLine(" Renglones_Pedidos.Cod_Uni, ") loConsulta.AppendLine(" Pedidos.Fec_Ini, ") loConsulta.AppendLine(" Pedidos.Cod_Mon, ") loConsulta.AppendLine(" Pedidos.Fec_Fin, ") loConsulta.AppendLine(" Pedidos.Mon_Bru, ") loConsulta.AppendLine(" Pedidos.Por_Imp1, ") loConsulta.AppendLine(" Pedidos.Dis_Imp, ") loConsulta.AppendLine(" Pedidos.Mon_Imp1, ") loConsulta.AppendLine(" Pedidos.Mon_Net, ") loConsulta.AppendLine(" Pedidos.Cod_For, ") loConsulta.AppendLine(" Pedidos.Comentario, ") loConsulta.AppendLine(" Pedidos.Notas, ") loConsulta.AppendLine(" Formas_Pagos.Nom_For, ") loConsulta.AppendLine(" Pedidos.For_Env, ") loConsulta.AppendLine(" Pedidos.Tip_Env, ") loConsulta.AppendLine(" Pedidos.Not_Des, ") loConsulta.AppendLine(" Pedidos.Cod_Tra, ") loConsulta.AppendLine(" Transportes.Nom_Tra, ") loConsulta.AppendLine(" Pedidos.Cod_Ven, ") loConsulta.AppendLine(" Vendedores.Nom_Ven, ") loConsulta.AppendLine(" Renglones_Pedidos.Cod_Art, ") loConsulta.AppendLine(" CASE") loConsulta.AppendLine(" WHEN Articulos.Generico = 0 THEN Articulos.Nom_Art") loConsulta.AppendLine(" ELSE Renglones_Pedidos.Notas") loConsulta.AppendLine(" END AS Nom_Art, ") loConsulta.AppendLine(" Renglones_Pedidos.Renglon, ") loConsulta.AppendLine(" (CASE WHEN (Renglones_Pedidos.Renglon>26)") loConsulta.AppendLine(" THEN CHAR((Renglones_Pedidos.Renglon-1) / 26 + 64)") loConsulta.AppendLine(" ELSE ''") loConsulta.AppendLine(" END) + CHAR(((Renglones_Pedidos.Renglon-1) % 26 ) + 65) AS Letra,") loConsulta.AppendLine(" Renglones_Pedidos.Can_Art1, ") loConsulta.AppendLine(" Renglones_Pedidos.Por_Des As Por_Des1, ") loConsulta.AppendLine(" Renglones_Pedidos.Precio1 As Precio1, ") loConsulta.AppendLine(" Renglones_Pedidos.Comentario As Comentario_Renglon, ") loConsulta.AppendLine(" Renglones_Pedidos.Mon_Net As Neto, ") loConsulta.AppendLine(" Renglones_Pedidos.Cod_Imp As Cod_Imp, ") loConsulta.AppendLine(" Renglones_Pedidos.Por_Imp1 As Por_Imp, ") loConsulta.AppendLine(" Renglones_Pedidos.Mon_Imp1 As Impuesto ") loConsulta.AppendLine("FROM Pedidos ") loConsulta.AppendLine(" JOIN Renglones_Pedidos ON Renglones_Pedidos.Documento = Pedidos.Documento") loConsulta.AppendLine(" JOIN Clientes ON Clientes.Cod_Cli = Pedidos.Cod_Cli") loConsulta.AppendLine(" JOIN Formas_Pagos ON Formas_Pagos.Cod_For = Pedidos.Cod_For") loConsulta.AppendLine(" JOIN Transportes ON Transportes.Cod_Tra = Pedidos.Cod_Tra") loConsulta.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Pedidos.Cod_Art") loConsulta.AppendLine(" JOIN Vendedores ON Vendedores.Cod_Ven = Pedidos.Cod_Ven") loConsulta.AppendLine("WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal) loConsulta.AppendLine("") loConsulta.AppendLine("") 'Me.mEscribirConsulta(loConsulta.ToString()) Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loConsulta.ToString, "curReportes") '--------------------------------------------------' ' Carga la imagen del logo en cusReportes ' '--------------------------------------------------' Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa") '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte.Tables(0).Rows.Count <= 0) Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fPedidos_TECHNOIP", laDatosReporte) Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvfPedidos_TECHNOIP.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo. ' '-------------------------------------------------------------------------------------------' ' RJG: 02/07/14: Código Inicial. ' '-------------------------------------------------------------------------------------------' ' RJG: 08/07/14: Cambio en los términos al pié del documento, se agregó nombre del cliente. ' ' Otros cambios menores de interfaz. ' '-------------------------------------------------------------------------------------------' ' RJG: 16/09/14: Se agregó el campo Notas con un recuadro. ' '-------------------------------------------------------------------------------------------' ' RJG: 13/12/14: Se ajustó el nombre del cliente para que ocupe 2 líneas si no cabe. ' '-------------------------------------------------------------------------------------------' ' PMV: 16/06/15: Se creo el formato para TECHNO IP. ' '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
fPedidos_TECHNOIP.aspx.vb
Visual Basic
mit
10,815
Imports System.Windows.Forms Public Class AddLecturerUI Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click If Not checkError() Then Return End If Dim l As New Lecturer() l.name = TextBoxLName.Text l.email = TextBoxEmail.Text l.phone = TextBoxPhone.Text l.salary = TextBoxSal.Text l.insert() Me.DialogResult = System.Windows.Forms.DialogResult.OK Me.Close() End Sub Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click Me.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.Close() End Sub Private Function checkError() As Boolean If TextBoxLName.Text = "" Or TextBoxEmail.Text = "" Or TextBoxPhone.Text = "" Or TextBoxSal.Text = "" Then MsgBox("Please fill in all fields.") Return False End If If Not IsNumeric(TextBoxPhone.Text) Or Not IsNumeric(TextBoxSal.Text) Then MsgBox("Salary or Phone number should be numeric.") Return False End If Return True End Function End Class
louislam/summer-course-system
Summer Course System/UI/AddLecturerUI.vb
Visual Basic
mit
1,078
'------------------------------------------------------------------------------ ' <generado automáticamente> ' Este código fue generado por una herramienta. ' ' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si ' se vuelve a generar el código. ' </generado automáticamente> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Partial Public Class ReporteKardexDetallado '''<summary> '''Control ReportViewer1. '''</summary> '''<remarks> '''Campo generado automáticamente. '''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente. '''</remarks> Protected WithEvents ReportViewer1 As Global.Telerik.ReportViewer.WebForms.ReportViewer End Class
crackper/SistFoncreagro
SistFoncreagro.WebSite/Monitoreo/Formularios/ReporteKardexDetallado.aspx.designer.vb
Visual Basic
mit
859
'-------------------------------------------------------------------------------------------' ' Inicio del codigo '-------------------------------------------------------------------------------------------' ' Importando librerias '-------------------------------------------------------------------------------------------' Imports System.Data '-------------------------------------------------------------------------------------------' ' Inicio de clase "grPedidos_MensualesMonto" '-------------------------------------------------------------------------------------------' Partial Class grPedidos_MensualesMonto Inherits vis2formularios.frmReporte Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Try Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0)) Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1)) Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1)) Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2)) Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2)) Dim lcParametro3Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3)) Dim lcParametro3Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(3)) Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4)) Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4)) Dim lcParametro5Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(5)) Dim lcParametro5Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(5)) Dim lcParametro6Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(6)) Dim lcParametro6Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(6)) Dim lcParametro7Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(7)) Dim lcParametro8Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(8)) Dim lcParametro8Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(8)) Dim lcParametro9Desde As String = cusAplicacion.goReportes.paParametrosIniciales(9) Dim lcParametro10Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(10)) Dim lcParametro10Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(10)) Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden Dim loComandoSeleccionar As New StringBuilder() loComandoSeleccionar.AppendLine(" DECLARE @Numero decimal") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" DATEPART(YEAR, Pedidos.Fec_Ini) As Año, ") loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Pedidos.Fec_Ini) AS Mes, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 1 THEN 'Ene' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 2 THEN 'Feb' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 3 THEN 'Mar' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 4 THEN 'Abr' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 5 THEN 'May' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 6 THEN 'Jun' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 7 THEN 'Jul' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 8 THEN 'Ago' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 9 THEN 'Sep' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 10 THEN 'Oct' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 11 THEN 'Nov' ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 12 THEN 'Dic' ") loComandoSeleccionar.AppendLine(" END AS Mes_Letras, ") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 1 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 2 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 3 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 4 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 5 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 6 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 7 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 8 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 9 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 10 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 11 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, Pedidos.Fec_Ini) = 12 THEN SUM(Renglones_Pedidos.Mon_Net) ") loComandoSeleccionar.AppendLine(" ELSE 0 ") loComandoSeleccionar.AppendLine(" END AS Monto ") loComandoSeleccionar.AppendLine(" INTO #Temp ") loComandoSeleccionar.AppendLine(" FROM Pedidos ") loComandoSeleccionar.AppendLine(" JOIN Renglones_Pedidos ON Pedidos.Documento = Renglones_Pedidos.Documento ") loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Pedidos.Cod_Art ") loComandoSeleccionar.AppendLine(" WHERE ") loComandoSeleccionar.AppendLine(" DATEPART(YEAR, Pedidos.Fec_Ini) = " & lcParametro0Desde) loComandoSeleccionar.AppendLine(" AND Renglones_Pedidos.Cod_Art between " & lcParametro1Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta) loComandoSeleccionar.AppendLine(" AND Pedidos.Cod_Cli between " & lcParametro2Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta) loComandoSeleccionar.AppendLine(" AND Pedidos.Cod_Ven between " & lcParametro3Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta) loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep between " & lcParametro4Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta) loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Tip between " & lcParametro5Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta) loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Cla between " & lcParametro6Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta) loComandoSeleccionar.AppendLine(" AND Pedidos.Status IN (" & lcParametro7Desde & ")") If lcParametro9Desde = "Igual" Then loComandoSeleccionar.AppendLine(" AND Pedidos.Cod_Rev between " & lcParametro8Desde) Else loComandoSeleccionar.AppendLine(" AND Pedidos.Cod_Rev NOT between " & lcParametro8Desde) End If loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta) loComandoSeleccionar.AppendLine(" AND Pedidos.Cod_Suc between " & lcParametro10Desde) loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta) loComandoSeleccionar.AppendLine(" GROUP BY DATEPART(YEAR, Pedidos.Fec_Ini), DATEPART(MONTH, Pedidos.Fec_Ini) ") loComandoSeleccionar.AppendLine(" ORDER BY DATEPART(YEAR, Pedidos.Fec_Ini), DATEPART(MONTH, Pedidos.Fec_Ini) ") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 1 AS Mes,") loComandoSeleccionar.AppendLine(" 'Ene' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" INTO #Temp2") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 2 AS Mes,") loComandoSeleccionar.AppendLine(" 'Feb' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 3 AS Mes,") loComandoSeleccionar.AppendLine(" 'Mar' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 4 AS Mes,") loComandoSeleccionar.AppendLine(" 'Abr' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 5 AS Mes,") loComandoSeleccionar.AppendLine(" 'May' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 6 AS Mes,") loComandoSeleccionar.AppendLine(" 'Jun' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 7 AS Mes,") loComandoSeleccionar.AppendLine(" 'Jul' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 8 AS Mes,") loComandoSeleccionar.AppendLine(" 'Ago' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 9 AS Mes,") loComandoSeleccionar.AppendLine(" 'Sep' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 10 AS Mes,") loComandoSeleccionar.AppendLine(" 'Oct' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 11 AS Mes,") loComandoSeleccionar.AppendLine(" 'Nov' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" " & lcParametro0Desde & " AS Año,") loComandoSeleccionar.AppendLine(" 12 AS Mes,") loComandoSeleccionar.AppendLine(" 'Dic' AS Mes_Letras,") loComandoSeleccionar.AppendLine(" 0 AS Monto") loComandoSeleccionar.AppendLine(" UNION ALL") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" Año,") loComandoSeleccionar.AppendLine(" Mes,") loComandoSeleccionar.AppendLine(" Mes_Letras,") loComandoSeleccionar.AppendLine(" Monto") loComandoSeleccionar.AppendLine(" FROM #Temp") loComandoSeleccionar.AppendLine(" SELECT ") loComandoSeleccionar.AppendLine(" Año,") loComandoSeleccionar.AppendLine(" Mes,") loComandoSeleccionar.AppendLine(" Mes_Letras,") loComandoSeleccionar.AppendLine(" SUM(Monto) AS Monto,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 1 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Enero,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 2 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Febrero,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 3 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Marzo,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 4 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Abril,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 5 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Mayo,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 6 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Junio,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 7 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Julio,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 8 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Agosto,") loComandoSeleccionar.AppendLine(" CASE") loComandoSeleccionar.AppendLine(" WHEN Mes = 9 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Septiembre,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 10 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Octubre,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 11 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Noviembre,") loComandoSeleccionar.AppendLine(" CASE ") loComandoSeleccionar.AppendLine(" WHEN Mes = 12 THEN SUM(Monto)") loComandoSeleccionar.AppendLine(" ELSE 0") loComandoSeleccionar.AppendLine(" END AS Diciembre") loComandoSeleccionar.AppendLine(" FROM #Temp2") loComandoSeleccionar.AppendLine(" GROUP BY Año,Mes,Mes_Letras") loComandoSeleccionar.AppendLine(" ORDER BY Año,Mes,Mes_Letras") loComandoSeleccionar.AppendLine(" SET @Numero = (SELECT MAX(Monto) FROM #Temp2)") loComandoSeleccionar.AppendLine(" SELECT Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*1) AS DECIMAL) AS E1,") loComandoSeleccionar.AppendLine(" Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*2) AS DECIMAL) AS E2,") loComandoSeleccionar.AppendLine(" Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*3) AS DECIMAL) AS E3,") loComandoSeleccionar.AppendLine(" Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*4) AS DECIMAL) AS E4,") loComandoSeleccionar.AppendLine(" Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*5) AS DECIMAL) AS E5,") loComandoSeleccionar.AppendLine(" Cast((round(@Numero, -(len(Cast(@Numero As varchar))-4))*0.2*6) AS DECIMAL) AS E6") Dim loServicios As New cusDatos.goDatos Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes") loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("grPedidos_MensualesMonto", laDatosReporte) '------------------------------------------------------------------------------------------------------- ' Verificando si el select (tabla nº0) trae registros '------------------------------------------------------------------------------------------------------- If (laDatosReporte.Tables(0).Rows.Count <= 0) Or (laDatosReporte.Tables(1).Rows(0).Item(5).ToString = "0") Then Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _ "No se Encontraron Registros para los Parámetros Especificados. ", _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _ "350px", _ "200px") End If loObjetoReporte.DataDefinition.FormulaFields("E1").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(0) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E1").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E1").Text & "), ',' , '.' )" loObjetoReporte.DataDefinition.FormulaFields("E2").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(1) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E2").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E2").Text & "), ',' , '.' )" loObjetoReporte.DataDefinition.FormulaFields("E3").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(2) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E3").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E3").Text & "), ',' , '.' )" loObjetoReporte.DataDefinition.FormulaFields("E4").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(3) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E4").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E4").Text & "), ',' , '.' )" loObjetoReporte.DataDefinition.FormulaFields("E5").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(4) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E5").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E5").Text & "), ',' , '.' )" loObjetoReporte.DataDefinition.FormulaFields("E6").Text = "ToText(Replace (ToText(" & laDatosReporte.Tables(1).Rows(0).Item(5) & "), '.00' , '' ))" loObjetoReporte.DataDefinition.FormulaFields("E6").Text = "Replace (ToText(" & loObjetoReporte.DataDefinition.FormulaFields("E6").Text & "), ',' , '.' )" Me.mTraducirReporte(loObjetoReporte) Me.mFormatearCamposReporte(loObjetoReporte) Me.crvgrPedidos_MensualesMonto.ReportSource = loObjetoReporte Catch loExcepcion As Exception Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _ "No se pudo Completar el Proceso: " & loExcepcion.Message, _ vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _ "auto", _ "auto") End Try End Sub Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload Try loObjetoReporte.Close() Catch loExcepcion As Exception End Try End Sub End Class '-------------------------------------------------------------------------------------------' ' Fin del codigo '-------------------------------------------------------------------------------------------' ' JJD: 22/08/09: Codigo inicial '-------------------------------------------------------------------------------------------'
kodeitsolutions/ef-reports
grPedidos_MensualesMonto.aspx.vb
Visual Basic
mit
23,250
'Copyright 2019 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Runtime.InteropServices Imports ESRI.ArcGIS.DataSourcesRaster Imports ESRI.ArcGIS.esriSystem Imports ESRI.ArcGIS.Geodatabase Imports ESRI.ArcGIS.Geometry Imports ESRI.ArcGIS.ADF.CATIDs Namespace CustomFunction <Guid("652642F3-9106-4EB3-9262-A4C39E03BC56")> _ <ClassInterface(ClassInterfaceType.None)> _ <ProgId("CustomFunction.NDVICustomFunction")> _ <ComVisible(True)> _ Public Class NDVICustomFunction Implements IRasterFunction Implements IPersistVariant Implements IDocumentVersionSupportGEN Implements IXMLSerialize Implements IXMLVersionSupport #Region "Private Members" Private myUID As UID ' UID for the Function. Private myRasterInfo As IRasterInfo ' Raster Info for the Function Private myPixeltype As rstPixelType ' Pixel Type of the Function. Private myName As String ' Name of the Function. Private myDescription As String ' Description of the Function. Private myValidFlag As Boolean ' Flag to specify validity of the Function. Private myFunctionHelper As IRasterFunctionHelper ' Raster Function Helper object. Private myInpPixeltype As rstPixelType Private myInpNumBands As Integer Private myBandIndices As String() #End Region Public Sub New() myName = "NDVI Custom Function" myPixeltype = rstPixelType.PT_FLOAT myDescription = "Custom NDVI Function which calculates the NDVI without any scaling." myValidFlag = True myFunctionHelper = New RasterFunctionHelper() myInpPixeltype = myPixeltype myInpNumBands = 0 myBandIndices = Nothing myUID = New UID() myUID.Value = "{652642F3-9106-4EB3-9262-A4C39E03BC56}" End Sub #Region "IRasterFunction Members" ''' <summary> ''' Name of the Raster Function. ''' </summary> Public Property Name() As String Implements IRasterFunction.Name Get Return myName End Get Set myName = value End Set End Property ''' <summary> ''' Pixel Type of the Raster Function ''' </summary> Public Property PixelType() As rstPixelType Implements IRasterFunction.PixelType Get Return myPixeltype End Get Set myPixeltype = value End Set End Property ''' <summary> ''' Output Raster Info for the Raster Function ''' </summary> Public ReadOnly Property RasterInfo() As IRasterInfo Implements IRasterFunction.RasterInfo Get Return myRasterInfo End Get End Property ''' <summary> ''' Description of the Raster Function ''' </summary> Public Property Description() As String Implements IRasterFunction.Description Get Return myDescription End Get Set myDescription = value End Set End Property ''' <summary> ''' Initialize the Raster function using the argument object. This is one of the two ''' main functions to implement for a custom Raster function. The raster object is ''' dereferenced if required and given to the RasterFuntionHelper object to bind. ''' </summary> ''' <param name="pArguments">Arguments object used for initialization</param> Public Sub Bind(pArguments As Object) Implements IRasterFunction.Bind Try ' Check if the Arguments object is of the correct type. Dim customFunctionArgs As INDVICustomFunctionArguments = Nothing If TypeOf pArguments Is INDVICustomFunctionArguments Then customFunctionArgs = DirectCast(pArguments, INDVICustomFunctionArguments) Dim inputRaster As Object = customFunctionArgs.Raster If TypeOf customFunctionArgs.Raster Is IRasterFunctionVariable Then Dim rasterFunctionVariable As IRasterFunctionVariable = DirectCast(customFunctionArgs.Raster, IRasterFunctionVariable) inputRaster = rasterFunctionVariable.Value End If ' Call the Bind method of the Raster Function Helper object. myFunctionHelper.Bind(inputRaster) Else ' Throw an error if incorrect arguments object is passed. Throw New System.Exception("Incorrect arguments object. Expected: INDVICustomFunctionArguments") End If ' Check to see if Band Indices exist. If customFunctionArgs.BandIndices IsNot Nothing AndAlso customFunctionArgs.BandIndices <> "" Then myBandIndices = customFunctionArgs.BandIndices.Split(" "C) Else ' If not, throw an error. Throw New System.Exception("Incorrect parameters specified. Expected: Valid band indices.") End If ' Create a new RasterInfo object and initialize from the FunctionHelper object. ' A new RasterInfo Object is created because assigning myFunctionHelper.RasterInfo ' directly creates a reference. myRasterInfo = New RasterInfo() myRasterInfo.BandCount = myFunctionHelper.RasterInfo.BandCount myRasterInfo.BlockHeight = myFunctionHelper.RasterInfo.BlockHeight myRasterInfo.BlockWidth = myFunctionHelper.RasterInfo.BlockWidth myRasterInfo.CellSize = myFunctionHelper.RasterInfo.CellSize myRasterInfo.Extent = myFunctionHelper.RasterInfo.Extent myRasterInfo.FirstPyramidLevel = myFunctionHelper.RasterInfo.FirstPyramidLevel myRasterInfo.Format = myFunctionHelper.RasterInfo.Format myRasterInfo.GeodataXform = myFunctionHelper.RasterInfo.GeodataXform myRasterInfo.MaximumPyramidLevel = myFunctionHelper.RasterInfo.MaximumPyramidLevel myRasterInfo.NativeExtent = myFunctionHelper.RasterInfo.NativeExtent myRasterInfo.NativeSpatialReference = myFunctionHelper.RasterInfo.NativeSpatialReference myRasterInfo.NoData = myFunctionHelper.RasterInfo.NoData myRasterInfo.Origin = myFunctionHelper.RasterInfo.Origin myRasterInfo.PixelType = rstPixelType.PT_FLOAT ' Output pixel type should be output of the NDVI. myRasterInfo.Resampling = myFunctionHelper.RasterInfo.Resampling myRasterInfo.SupportBandSelection = myFunctionHelper.RasterInfo.SupportBandSelection ' Store required input properties. myInpPixeltype = myRasterInfo.PixelType myInpNumBands = myRasterInfo.BandCount ' Set output pixel properties. myRasterInfo.BandCount = 1 myPixeltype = rstPixelType.PT_FLOAT ' Perform validation to see if the indices passed are valid. If myInpNumBands < 2 OrElse myBandIndices.Length < 2 Then ' If not, throw an error. Throw New System.Exception("Incorrect parameters specified. Expected: Valid band indices.") End If For i As Integer = 0 To myBandIndices.Length - 1 Dim currBand As Integer = Convert.ToInt16(myBandIndices(i)) - 1 If (currBand < 0) OrElse (currBand > myInpNumBands) Then ' If not, throw an error. Throw New System.Exception("Incorrect parameters specified. Expected: Valid band indices.") End If Next Catch exc As Exception Dim myExc As New System.Exception("Exception caught in Bind method: " & exc.Message, exc) Throw myExc End Try End Sub ''' <summary> ''' Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. ''' </summary> ''' <param name="pTlc">Point to start the reading from in the Raster</param> ''' <param name="pRaster">Reference Raster for the PixelBlock</param> ''' <param name="pPixelBlock">PixelBlock to be filled in</param> Public Sub Read(pTlc As IPnt, pRaster As IRaster, pPixelBlock As IPixelBlock) Implements IRasterFunction.Read Try ' Create a new pixel block to read the input data into. ' This is done because the pPixelBlock represents the output ' pixel block which is different from the input. Dim pBHeight As Integer = pPixelBlock.Height Dim pBWidth As Integer = pPixelBlock.Width Dim pBlockSize As IPnt = New Pnt() pBlockSize.X = pBWidth pBlockSize.Y = pBHeight Dim inputPixelBlock As IPixelBlock = New PixelBlock() DirectCast(inputPixelBlock, IPixelBlock4).Create(myInpNumBands, pBWidth, pBHeight, myInpPixeltype) ' Call Read method of the Raster Function Helper object to read the input pixels into ' the inputPixelBlock. myFunctionHelper.Read(pTlc, Nothing, pRaster, inputPixelBlock) Dim inpPixelValues1 As System.Array Dim inpPixelValues2 As System.Array Dim outPixelValues As System.Array Dim index1 As Integer = Convert.ToInt16(myBandIndices(0)) - 1 ' Get NIR band index specified by user. Dim index2 As Integer = Convert.ToInt16(myBandIndices(1)) - 1 ' Get Red Band index specified by user. ' Get the correct bands from the input. Dim ipPixelBlock As IPixelBlock3 = DirectCast(inputPixelBlock, IPixelBlock3) inpPixelValues1 = DirectCast(ipPixelBlock.PixelData(index1), System.Array) inpPixelValues2 = DirectCast(ipPixelBlock.PixelData(index2), System.Array) outPixelValues = DirectCast(DirectCast(pPixelBlock, IPixelBlock3).PixelData(0), System.Array) Dim i As Integer = 0 Dim k As Integer = 0 Dim pixelValue As Double = 0.0 Dim nirValue As Double = 0.0 Dim irValue As Double = 0.0 ' Perform the NDVI computation and store the result in the output pixel block. For i = 0 To pBHeight - 1 For k = 0 To pBWidth - 1 nirValue = Convert.ToDouble(inpPixelValues1.GetValue(k, i)) irValue = Convert.ToDouble(inpPixelValues2.GetValue(k, i)) ' Check if input is not NoData. If (Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index1, k, i)) = 1) AndAlso Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index2, k, i)) = 1 Then ' NDVI[k] = (NIR[k]-Red[k])/(NIR[k]+Red[k]); If (nirValue + irValue) <> 0 Then ' Check for division by 0. pixelValue = (nirValue - irValue) / (nirValue + irValue) If pixelValue < -1.0 OrElse pixelValue > 1.0 Then pixelValue = 0.0 End If Else pixelValue = 0.0 End If End If outPixelValues.SetValue(CSng(pixelValue), k, i) Next Next ' Set the output pixel values on the output pixel block. DirectCast(pPixelBlock, IPixelBlock3).PixelData(0) = outPixelValues ' Copy over the NoData mask from the input and set it on the output. DirectCast(pPixelBlock, IPixelBlock3).NoDataMask(0) = DirectCast(inputPixelBlock, IPixelBlock3).NoDataMask(0) Catch exc As Exception Dim myExc As New System.Exception("Exception caught in Read method: " & exc.Message, exc) Throw myExc End Try End Sub ''' <summary> ''' Update the Raster Function ''' </summary> Public Sub Update() Implements IRasterFunction.Update Try Catch exc As Exception Dim myExc As New System.Exception("Exception caught in Update method: ", exc) Throw myExc End Try End Sub ''' <summary> ''' Property that specifies whether the Raster Function is still valid. ''' </summary> Public ReadOnly Property Valid() As Boolean Implements IRasterFunction.Valid Get Return myValidFlag End Get End Property #End Region #Region "IPersistVariant Members" ''' <summary> ''' UID to identify the function. ''' </summary> Public ReadOnly Property ID() As UID Implements IPersistVariant.ID Get Return myUID End Get End Property ''' <summary> ''' Load the properties of the function from the stream provided ''' </summary> ''' <param name="Stream">Stream that contains the serialized form of the function</param> Public Sub Load(Stream As IVariantStream) Implements IPersistVariant.Load If TypeOf Stream Is IDocumentVersion Then Dim docVersion As IDocumentVersion = DirectCast(Stream, IDocumentVersion) If docVersion.DocumentVersion >= esriArcGISVersion.esriArcGISVersion10 Then Dim streamVersion As esriArcGISVersion = CType(CInt(Stream.Read()), esriArcGISVersion) If streamVersion >= esriArcGISVersion.esriArcGISVersion10 Then myName = DirectCast(Stream.Read(), String) myDescription = DirectCast(Stream.Read(), String) myPixeltype = CType(CInt(Stream.Read()), rstPixelType) End If End If End If End Sub ''' <summary> ''' Save the properties of the function to the stream provided ''' </summary> ''' <param name="Stream">Stream to which to serialize the function into</param> Public Sub Save(Stream As IVariantStream) Implements IPersistVariant.Save If TypeOf Stream Is IDocumentVersion Then Dim docVersion As IDocumentVersion = DirectCast(Stream, IDocumentVersion) If docVersion.DocumentVersion >= esriArcGISVersion.esriArcGISVersion10 Then Stream.Write(CInt(esriArcGISVersion.esriArcGISVersion10)) Stream.Write(myName) Stream.Write(myDescription) Stream.Write(CInt(myPixeltype)) End If End If End Sub #End Region #Region "IDocumentVersionSupportGEN Members" ''' <summary> ''' Convert the instance into an object supported by the given version ''' </summary> ''' <param name="docVersion">Version to convert to</param> ''' <returns>Object that supports given version</returns> Public Function ConvertToSupportedObject(docVersion As esriArcGISVersion) As Object Implements IDocumentVersionSupportGEN.ConvertToSupportedObject Return Nothing End Function ''' <summary> ''' Check if the object is supported at the given version ''' </summary> ''' <param name="docVersion">Version to check against</param> ''' <returns>True if the object is supported</returns> Public Function IsSupportedAtVersion(docVersion As esriArcGISVersion) As Boolean Implements IDocumentVersionSupportGEN.IsSupportedAtVersion If docVersion >= esriArcGISVersion.esriArcGISVersion10 Then Return True Else Return False End If End Function #End Region #Region "IXMLSerialize Members" ''' <summary> ''' Deserialize the Raster Function from the datastream provided ''' </summary> ''' <param name="data">Xml stream to deserialize the function from</param> Public Sub Deserialize(data As IXMLSerializeData) Implements IXMLSerialize.Deserialize myName = data.GetString(data.Find("Name")) myDescription = data.GetString(data.Find("Description")) myPixeltype = CType(data.GetInteger(data.Find("PixelType")), rstPixelType) End Sub ''' <summary> ''' Serialize the Raster Function into the stream provided. ''' </summary> ''' <param name="data">Xml stream to serialize the function into</param> Public Sub Serialize(data As IXMLSerializeData) Implements IXMLSerialize.Serialize data.TypeName = "NDVICustomFunction" data.TypeNamespaceURI = "http://www.esri.com/schemas/ArcGIS/10.2" data.AddString("Name", myName) data.AddString("Description", myDescription) data.AddInteger("PixelType", CInt(myPixeltype)) End Sub #End Region #Region "IXMLVersionSupport Members" ''' <summary> ''' Returns the namespaces supported by the object ''' </summary> Public ReadOnly Property MinNamespaceSupported() As String Implements IXMLVersionSupport.MinNamespaceSupported Get Return "http://www.esri.com/schemas/ArcGIS/10.2" End Get End Property #End Region #Region "COM Registration Function(s)" <ComRegisterFunction> _ Private Shared Sub Reg(regKey As String) ESRI.ArcGIS.ADF.CATIDs.RasterFunctions.Register(regKey) End Sub <ComUnregisterFunction> _ Private Shared Sub Unreg(regKey As String) ESRI.ArcGIS.ADF.CATIDs.RasterFunctions.Unregister(regKey) End Sub #End Region End Class <Guid("157ACDCC-9F2B-4CC4-BFFD-FEB933F3E788")> _ <InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)> _ Public Interface INDVICustomFunctionArguments Inherits IRasterFunctionArguments Inherits IPersistVariant Inherits IDocumentVersionSupportGEN Inherits IXMLSerialize Inherits IXMLVersionSupport #Region "INDVICustomFunctionArguments Members" <DispId(&H50505001)> _ Property Raster() As Object <DispId(&H50505002)> _ Property BandIndices() As String #End Region End Interface <Guid("CB684500-0A15-46C5-B1C1-8062A1629F66")> _ <ClassInterface(ClassInterfaceType.None)> _ <ProgId("CustomFunction.NDVICustomFunctionArguments")> _ <ComVisible(True)> _ Public Class NDVICustomFunctionArguments Implements INDVICustomFunctionArguments #Region "Private Members" Private myName As String Private myDescription As String Private myUID As UID ' UID for the NDVI Custom Function Arguments. Private myProperties As IPropertySet ' Property set to store the properties of the arguments object. #End Region Public Sub New() myName = "NDVI Custom Function Arguments" myDescription = "Arguments object for the NDVI Custom Function" ' Set default values myProperties = New PropertySet() myProperties.SetProperty("Raster", Nothing) myProperties.SetProperty("BandIndices", "1 2") ' Default value for band indexes: first two bands of image. myUID = New UID() myUID.Value = "{CB684500-0A15-46C5-B1C1-8062A1629F66}" End Sub #Region "NDVICustomFunctionArguments Members" ''' <summary> ''' Raster to apply the raster function to. ''' </summary> Public Property Raster() As Object Implements INDVICustomFunctionArguments.Raster Get Return GetDereferencedValue("Raster") End Get Set myProperties.SetProperty("Raster", value) End Set End Property ''' <summary> ''' Indices of the bands to use in the NDVI computation. ''' </summary> Public Property BandIndices() As String Implements INDVICustomFunctionArguments.BandIndices Get Return Convert.ToString(GetDereferencedValue("BandIndices")) End Get Set myProperties.SetProperty("BandIndices", value) End Set End Property ''' <summary> ''' Dereference and return the value of the property whose name is given if necessary. ''' </summary> ''' <param name="name">Name of the property to check.</param> ''' <returns>Dereferenced value of the property corresponding to the name given.</returns> Private Function GetDereferencedValue(name As String) As Object Dim value As Object = myProperties.GetProperty(name) If value IsNot Nothing AndAlso TypeOf value Is IRasterFunctionVariable AndAlso Not (TypeOf value Is IRasterFunctionTemplate) Then Dim rFVar As IRasterFunctionVariable = DirectCast(value, IRasterFunctionVariable) Return rFVar.Value End If Return value End Function #End Region #Region "IRasterFunctionArguments Members" ''' <summary> ''' A list of files associated with the raster ''' </summary> Public ReadOnly Property FileList() As IStringArray Implements IRasterFunctionArguments.FileList Get Dim rasterObject As Object = myProperties.GetProperty("Raster") Dim rasterDataset As IRasterDataset = Nothing If TypeOf rasterObject Is IRasterDataset Then rasterDataset = DirectCast(rasterObject, IRasterDataset) ElseIf TypeOf rasterObject Is IName Then rasterDataset = DirectCast(DirectCast(rasterObject, IName).Open(), IRasterDataset) End If If rasterDataset IsNot Nothing AndAlso TypeOf rasterDataset Is IRasterDatasetInfo Then Dim rasterDatasetInfo As IRasterDatasetInfo = DirectCast(rasterDataset, IRasterDatasetInfo) Return rasterDatasetInfo.FileList Else Return Nothing End If End Get End Property ''' <summary> ''' Get the value associated with the name provided. ''' </summary> ''' <param name="Name">Name of the property</param> ''' <returns>Value of the property name provided</returns> Public Function GetValue(Name As String) As Object Implements IRasterFunctionArguments.GetValue Return myProperties.GetProperty(Name) End Function ''' <summary> ''' A list of all the names in the property set. ''' </summary> Public ReadOnly Property Names() As IStringArray Implements IRasterFunctionArguments.Names Get ' Generate a list of names in the propertyset. Dim names__1 As Object = Nothing, values As Object = Nothing myProperties.GetAllProperties(names__1, values) Dim myNames As IStringArray = New StrArray() Dim nameArray As String() = DirectCast(names__1, String()) For i As Integer = 0 To nameArray.GetLength(0) - 1 myNames.Add(nameArray(i)) Next Return myNames End Get End Property ''' <summary> ''' Set the given property name to the given value ''' </summary> ''' <param name="Name">Name of the property</param> ''' <param name="Value">Value of the property</param> Public Sub PutValue(Name As String, Value As Object) Implements IRasterFunctionArguments.PutValue myProperties.SetProperty(Name, Value) End Sub ''' <summary> ''' Remove the value of the property name provided ''' </summary> ''' <param name="Name">Name of the property to be removed</param> Public Sub Remove(Name As String) Implements IRasterFunctionArguments.Remove myProperties.RemoveProperty(Name) End Sub ''' <summary> ''' Clear the property set of all names and values. ''' </summary> Public Sub RemoveAll() Implements IRasterFunctionArguments.RemoveAll myProperties = Nothing myProperties = New PropertySet() End Sub ''' <summary> ''' A list of all the values in the property set ''' </summary> Public ReadOnly Property Values() As IVariantArray Implements IRasterFunctionArguments.Values Get ' Generate a list of values in the propertyset. Dim names As Object = Nothing, values__1 As Object = Nothing myProperties.GetAllProperties(names, values__1) Dim myValues As IVariantArray = New VarArray() Dim valArray As Object() = DirectCast(values__1, Object()) For i As Integer = 0 To valArray.GetLength(0) - 1 myValues.Add(valArray(i)) Next Return myValues End Get End Property ''' <summary> ''' Resolve variables containing field names with the corresponding values. ''' </summary> ''' <param name="pRow">The row corresponding to the function raster dataset.</param> ''' <param name="pPropertySet">Property Set to add the list of the names and the resolved values to.</param> Public Sub Resolve(pRow As IRow, pPropertySet As IPropertySet) Implements IRasterFunctionArguments.Resolve ResolveRasterVal(pRow) End Sub ''' <summary> ''' Update the variables containing field names to their updated values. ''' </summary> ''' <param name="pRow">The row corresponding to the function raster dataset.</param> ''' <param name="pPropertySet">Property Set to add the list of the names and the updated values to.</param> ''' <param name="pTemplateArguments">The arguements object containing the properties to update if</param> Public Sub Update(pRow As IRow, pPropertySet As IPropertySet, pTemplateArguments As IRasterFunctionArguments) Implements IRasterFunctionArguments.Update Resolve(pRow, pPropertySet) End Sub ''' <summary> ''' Resolve the 'Raster' variable if it contains field names with the corresponding values. ''' </summary> ''' <param name="pRow">The row corresponding to the function raster dataset.</param> Private Sub ResolveRasterVal(pRow As IRow) Try ' Get the Raster property. Dim myRasterObject As Object = myProperties.GetProperty("Raster") ' Check to see if it is a variable If TypeOf myRasterObject Is IRasterFunctionVariable Then Dim rasterVar As IRasterFunctionVariable = DirectCast(myRasterObject, IRasterFunctionVariable) Dim rasterVal As Object = FindPropertyInRow(rasterVar, pRow) If rasterVal IsNot Nothing AndAlso TypeOf rasterVal Is String Then Dim datasetPath As String = DirectCast(rasterVal, String) rasterVar.Value = OpenRasterDataset(datasetPath) End If End If Catch exc As Exception Dim myExc As New System.Exception("Exception caught in ResolveRasterVal: " & exc.Message, exc) Throw myExc End Try End Sub ''' <summary> ''' Check the Name and Alias properties of the given Raster Function Variable to see ''' if they contain a field name and get the value of the corresponding field if needed. ''' </summary> ''' <param name="rasterFunctionVar">The Raster Function Variable to check.</param> ''' <param name="pRow">The row corresponding to the function raster dataset.</param> ''' <returns></returns> Private Function FindPropertyInRow(rasterFunctionVar As IRasterFunctionVariable, pRow As IRow) As Object Dim varName As String = "" Dim varNames As IStringArray = New StrArray() varName = rasterFunctionVar.Name ' If the name of the variable contains '@Field' If varName.Contains("@Field.") Then varNames.Add(varName) End If ' Add it to the list of names. ' Check the aliases of the variable For i As Integer = 0 To rasterFunctionVar.Aliases.Count - 1 ' Check the list of aliases for the '@Field' string varName = rasterFunctionVar.Aliases.Element(i) If varName.Contains("@Field.") Then varNames.Add(varName) ' and add any that are found to the list of names. End If Next ' Use the list of names and find the value by looking up the appropriate field. For i As Integer = 0 To varNames.Count - 1 ' Get the variable name containing the field string varName = varNames.Element(i) ' Replace the '@Field' with nothing to get just the name of the field. Dim fieldName As String = varName.Replace("@Field.", "") Dim rowFields As IFields = pRow.Fields ' Look up the index of the field name in the row. Dim fieldIndex As Integer = rowFields.FindField(fieldName) ' If it is a valid index and the field type is string, return the value. If fieldIndex <> -1 AndAlso ((rowFields.Field(fieldIndex)).Type = esriFieldType.esriFieldTypeString) Then Return pRow.Value(fieldIndex) End If Next ' If no value has been returned yet, return null. Return Nothing End Function ''' <summary> ''' Open the Raster Dataset given the path to the file. ''' </summary> ''' <param name="path">Path to the Raster Dataset file.</param> ''' <returns>The opened Raster Dataset.</returns> Private Function OpenRasterDataset(path As String) As IRasterDataset Try Dim inputWorkspace As String = System.IO.Path.GetDirectoryName(path) Dim inputDatasetName As String = System.IO.Path.GetFileName(path) Dim factoryType As Type = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory") Dim workspaceFactory As IWorkspaceFactory = DirectCast(Activator.CreateInstance(factoryType), IWorkspaceFactory) Dim workspace As IWorkspace = workspaceFactory.OpenFromFile(inputWorkspace, 0) Dim rasterWorkspace As IRasterWorkspace = DirectCast(workspace, IRasterWorkspace) Dim myRasterDataset As IRasterDataset = rasterWorkspace.OpenRasterDataset(inputDatasetName) Return myRasterDataset Catch exc As Exception Throw exc End Try End Function #End Region #Region "IPersistVariant Members" ''' <summary> ''' UID to identify the object. ''' </summary> Public ReadOnly Property ID() As UID Implements IPersistVariant.ID Get Return myUID End Get End Property ''' <summary> ''' Load the properties of the argument object from the stream provided ''' </summary> ''' <param name="Stream">Stream that contains the serialized form of the argument object</param> Public Sub Load(Stream As IVariantStream) Implements IPersistVariant.Load If TypeOf Stream Is IDocumentVersion Then Dim docVersion As IDocumentVersion = DirectCast(Stream, IDocumentVersion) If docVersion.DocumentVersion >= esriArcGISVersion.esriArcGISVersion10 Then Dim streamVersion As esriArcGISVersion = CType(CInt(Stream.Read()), esriArcGISVersion) If streamVersion >= esriArcGISVersion.esriArcGISVersion10 Then myName = DirectCast(Stream.Read(), String) myDescription = DirectCast(Stream.Read(), String) myProperties = DirectCast(Stream.Read(), IPropertySet) End If End If End If End Sub ''' <summary> ''' Save the properties of the argument object to the stream provided ''' </summary> ''' <param name="Stream">Stream to which to serialize the argument object into</param> Public Sub Save(Stream As IVariantStream) Implements IPersistVariant.Save If TypeOf Stream Is IDocumentVersion Then Dim docVersion As IDocumentVersion = DirectCast(Stream, IDocumentVersion) If docVersion.DocumentVersion >= esriArcGISVersion.esriArcGISVersion10 Then Dim names As Object = Nothing, values As Object = Nothing myProperties.GetAllProperties(names, values) Dim nameArray As String() = DirectCast(names, String()) Dim valArray As Object() = DirectCast(values, Object()) For i As Integer = 0 To nameArray.GetLength(0) - 1 If TypeOf valArray(i) Is IDataset Then Dim myDatasetName As IName = DirectCast(valArray(i), IDataset).FullName myProperties.SetProperty(nameArray(i), myDatasetName) End If Next Stream.Write(CInt(esriArcGISVersion.esriArcGISVersion10)) Stream.Write(myName) Stream.Write(myDescription) Stream.Write(myProperties) End If End If End Sub #End Region #Region "IDocumentVersionSupportGEN Members" ''' <summary> ''' Convert the instance into an object supported by the given version ''' </summary> ''' <param name="docVersion">Version to convert to</param> ''' <returns>Object that supports given version</returns> Public Function ConvertToSupportedObject(docVersion As esriArcGISVersion) As Object Implements IDocumentVersionSupportGEN.ConvertToSupportedObject Return Nothing End Function ''' <summary> ''' Check if the object is supported at the given version ''' </summary> ''' <param name="docVersion">Version to check against</param> ''' <returns>True if the object is supported</returns> Public Function IsSupportedAtVersion(docVersion As esriArcGISVersion) As Boolean Implements IDocumentVersionSupportGEN.IsSupportedAtVersion If docVersion >= esriArcGISVersion.esriArcGISVersion10 Then Return True Else Return False End If End Function #End Region #Region "IXMLSerialize Members" ''' <summary> ''' Deserialize the argument object from the datastream provided ''' </summary> ''' <param name="data">Xml stream to deserialize the argument object from</param> Public Sub Deserialize(data As IXMLSerializeData) Implements IXMLSerialize.Deserialize Dim nameIndex As Integer = data.Find("Names") Dim valIndex As Integer = data.Find("Values") If nameIndex <> -1 AndAlso valIndex <> -1 Then Dim myNames As IStringArray = DirectCast(data.GetVariant(nameIndex), IStringArray) Dim myValues As IVariantArray = DirectCast(data.GetVariant(valIndex), IVariantArray) For i As Integer = 0 To myNames.Count - 1 myProperties.SetProperty(myNames.Element(i), myValues.Element(i)) Next End If End Sub ''' <summary> ''' Serialize the argument object into the stream provided. ''' </summary> ''' <param name="data">Xml stream to serialize the argument object into</param> Public Sub Serialize(data As IXMLSerializeData) Implements IXMLSerialize.Serialize '#Region "Prepare PropertySet" Dim names As Object = Nothing, values As Object = Nothing myProperties.GetAllProperties(names, values) Dim myNames As IStringArray = New StrArray() Dim nameArray As String() = DirectCast(names, String()) Dim myValues As IVariantArray = New VarArray() Dim valArray As Object() = DirectCast(values, Object()) For i As Integer = 0 To nameArray.GetLength(0) - 1 myNames.Add(nameArray(i)) If TypeOf valArray(i) Is IDataset Then Dim myDatasetName As IName = DirectCast(valArray(i), IDataset).FullName myValues.Add(myDatasetName) Else myValues.Add(valArray(i)) End If Next '#End Region data.TypeName = "NDVICustomFunctionArguments" data.TypeNamespaceURI = "http://www.esri.com/schemas/ArcGIS/10.2" data.AddObject("Names", myNames) data.AddObject("Values", myValues) End Sub #End Region #Region "IXMLVersionSupport Members" ''' <summary> ''' Returns the namespaces supported by the object ''' </summary> Public ReadOnly Property MinNamespaceSupported() As String Implements IXMLVersionSupport.MinNamespaceSupported Get Return "http://www.esri.com/schemas/ArcGIS/10.2" End Get End Property #End Region End Class End Namespace
Esri/arcobjects-sdk-community-samples
Net/Raster/NDVICustomFunction/VBNet/NDVICustomFunction/NDVICustomFunction.vb
Visual Basic
apache-2.0
32,883
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense <[UseExportProvider]> Public Class CSharpDebuggerIntellisenseTests <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacter() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function LocalsInBlockAfterInstructionPointer() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("x") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("x") state.SendBackspace() state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionAfterReturn() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] int x = 3; string bar = "goo"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) state.SendReturn() Assert.Equal("", state.GetCurrentViewLineText()) state.SendTypeChars("bar") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("bar") state.SendTab() Assert.Equal("bar", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ExecutedUnexecutedLocals() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("goo") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("goo") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") For i As Integer = 0 To 7 state.SendBackspace() Next Await state.AssertNoCompletionSession() state.SendTypeChars("green") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("green") state.SendTab() state.SendTypeChars(".ToS") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSelectedCompletionItem("ToString") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { [|int variable1 = 0;|] } Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; [|}|] Console.Write(0); int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsContainAll("variable1", "variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals3() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } [|Console.Write(0);|] int variable2 = 0; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals4() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); [|int variable2 = 0;|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals5() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; [|}|] }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsContainAll("variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function Locals6() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main() { { int variable1 = 0; } Console.Write(0); int variable2 = 0; } [|}|]</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("variable") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("variable1") Await state.AssertCompletionItemsDoNotContainAny("variable2") End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInParameterizedConstructor() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("new string(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something(string z, int b) { } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function SignatureHelpInGenericMethodCall() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void something&lt;T&gt;(&lt;T&gt; z, int b) { return z } static void Main(string[] args) { string goo = "green"; [|string bar = "goo";|] string green = "yellow"; } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("something<int>(") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertSignatureHelpSession() End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function InstructionPointerInForeach() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { int OOO = 3; foreach (var z in "goo") { [|var q = 1;|] } } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) Await state.VerifyCompletionAndDotAfter("q") Await state.VerifyCompletionAndDotAfter("OOO") End Using End Function <WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner1() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static int STATICINT; static void Main(string[] args) { } [| |] public void M1() { throw new System.NotImplementedException(); } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("STATICI") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertCompletionItemsDoNotContainAny("STATICINT") End Using End Function <WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function ClassDesigner2() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) { } [| |] void M1() { } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, False) state.SendTypeChars("1") Await state.WaitForAsynchronousOperationsAsync() Await state.AssertNoCompletionSession() End Using End Function <WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")> <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionUsesContextBufferPositions() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e. (1,3): error CS1001: Identifier expected e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null e.InnerException {"Exception of type 'System.Exception' was thrown."} Data: {System.Collections.ListDictionaryInternal} HResult: -2146233088 HelpLink: null InnerException: null Message: "Exception of type 'System.Exception' was thrown." Source: null StackTrace: null TargetSite: null $$</Document> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("arg", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() state.SendTab() Assert.Equal("args", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function CompletionOnTypeCharacterInLinkedFileContext() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> { static void Main(string[] args) [|{|] } } </Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ") state.SendTypeChars("arg") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText()) state.SendTab() Assert.Contains("args", state.GetCurrentViewLineText()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, True) state.SendInvokeCompletionList() Await state.AssertCompletionSession() state.SendTypeChars("4") Await state.AssertNoCompletionSession() End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function <ConditionalWpfFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)> Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task Dim text = <Workspace> <Project Language="C#" CommonReferences="true"> <Document>class Program { static void Main(string[] args) [|{|] } }</Document> </Project> </Workspace> Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True) state.SendTypeChars("args") Await state.WaitForAsynchronousOperationsAsync() Assert.Equal("args", state.GetCurrentViewLineText()) Await state.AssertCompletionSession() Assert.True(state.HasSuggestedItem()) state.SendToggleCompletionMode() Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) state.SendTypeChars(".") Await state.WaitForAsynchronousOperationsAsync() Assert.False(state.HasSuggestedItem()) End Using End Function End Class End Namespace
diryboy/roslyn
src/VisualStudio/Core/Test/DebuggerIntelliSense/CSharpDebuggerIntellisenseTests.vb
Visual Basic
mit
26,976
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Globalization Imports System.Text Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class OverridesTests Inherits BasicTestBase ' Test that basic overriding of properties and methods works. ' Test OverriddenMethod/OverriddenProperty API. <Fact> Public Sub SimpleOverrides() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System Class Base Public Overridable Sub O1(a As String) Console.WriteLine("Base.O1") End Sub Public Sub N1(a As String) Console.WriteLine("Base.N1") End Sub Public Overridable Property O2 As String Get Console.WriteLine("Base.O2.Get") Return "Base.O2" End Get Set(value As String) Console.WriteLine("Base.O2.Set") End Set End Property Public Overridable Property N2 As String Get Console.WriteLine("Base.N2.Get") Return "Base.N2" End Get Set(value As String) Console.WriteLine("Base.N2.Set") End Set End Property End Class Class Derived Inherits Base Public Overrides Sub O1(a As String) Console.WriteLine("Derived.O1") End Sub Public Shadows Sub N1(a As String) Console.WriteLine("Derived.N1") End Sub Public Overrides Property O2 As String Get Console.WriteLine("Derived.O2.Get") Return "Derived.O2" End Get Set(value As String) Console.WriteLine("Derived.O2.Set") End Set End Property Public Shadows Property N2 As String Get Console.WriteLine("Derived.N2.Get") Return "Derived.N2" End Get Set(value As String) Console.WriteLine("Derived.N2.Set") End Set End Property End Class Module Module1 Sub Main() Dim s As String Dim b As Base = New Derived() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") b = New Base() b.O1("hi") b.O2 = "x" s = b.O2 b.N1("hi") b.N2 = "x" s = b.N2 Console.WriteLine("---") Dim d As Derived = New Derived() d.O1("hi") d.O2 = "x" s = d.O2 d.N1("hi") d.N2 = "x" s = d.N2 End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code) Dim globalNS = comp.GlobalNamespace Dim clsBase = DirectCast(globalNS.GetMembers("Base").Single(), NamedTypeSymbol) Dim clsDerived = DirectCast(globalNS.GetMembers("Derived").Single(), NamedTypeSymbol) Dim o1Base = DirectCast(clsBase.GetMembers("O1").Single(), MethodSymbol) Dim o1Derived = DirectCast(clsDerived.GetMembers("O1").Single(), MethodSymbol) Assert.Null(o1Base.OverriddenMethod) Assert.Same(o1Base, o1Derived.OverriddenMethod) Dim o2Base = DirectCast(clsBase.GetMembers("O2").Single(), PropertySymbol) Dim o2Derived = DirectCast(clsDerived.GetMembers("O2").Single(), PropertySymbol) Assert.Null(o2Base.OverriddenProperty) Assert.Same(o2Base, o2Derived.OverriddenProperty) Dim get_o2Base = DirectCast(clsBase.GetMembers("get_O2").Single(), MethodSymbol) Dim get_o2Derived = DirectCast(clsDerived.GetMembers("get_O2").Single(), MethodSymbol) Assert.Null(get_o2Base.OverriddenMethod) Assert.Same(get_o2Base, get_o2Derived.OverriddenMethod) Dim set_o2Base = DirectCast(clsBase.GetMembers("set_O2").Single(), MethodSymbol) Dim set_o2Derived = DirectCast(clsDerived.GetMembers("set_O2").Single(), MethodSymbol) Assert.Null(set_o2Base.OverriddenMethod) Assert.Same(set_o2Base, set_o2Derived.OverriddenMethod) Dim n1Base = DirectCast(clsBase.GetMembers("N1").Single(), MethodSymbol) Dim n1Derived = DirectCast(clsDerived.GetMembers("N1").Single(), MethodSymbol) Assert.Null(n1Base.OverriddenMethod) Assert.Null(n1Derived.OverriddenMethod) Dim n2Base = DirectCast(clsBase.GetMembers("N2").Single(), PropertySymbol) Dim n2Derived = DirectCast(clsDerived.GetMembers("N2").Single(), PropertySymbol) Assert.Null(n2Base.OverriddenProperty) Assert.Null(n2Derived.OverriddenProperty) Dim get_n2Base = DirectCast(clsBase.GetMembers("get_N2").Single(), MethodSymbol) Dim get_n2Derived = DirectCast(clsDerived.GetMembers("get_N2").Single(), MethodSymbol) Assert.Null(get_n2Base.OverriddenMethod) Assert.Null(get_n2Derived.OverriddenMethod) Dim set_n2Base = DirectCast(clsBase.GetMembers("set_N2").Single(), MethodSymbol) Dim set_n2Derived = DirectCast(clsDerived.GetMembers("set_N2").Single(), MethodSymbol) Assert.Null(set_n2Base.OverriddenMethod) Assert.Null(set_n2Derived.OverriddenMethod) CompileAndVerify(code, expectedOutput:=<![CDATA[ Derived.O1 Derived.O2.Set Derived.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Base.O1 Base.O2.Set Base.O2.Get Base.N1 Base.N2.Set Base.N2.Get --- Derived.O1 Derived.O2.Set Derived.O2.Get Derived.N1 Derived.N2.Set Derived.N2.Get]]>) End Sub <Fact> Public Sub UnimplementedMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="UnimplementedMustOverride"> <file name="a.vb"> Option Strict On Namespace X Public MustInherit Class A Public MustOverride Sub foo(x As Integer) Public MustOverride Sub bar() Public MustOverride Sub quux() Protected MustOverride Function zing() As String Public MustOverride Property bing As Integer Public MustOverride ReadOnly Property bang As Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub bar() End Sub Protected MustOverride Function baz() As String Protected Overrides Function zing() As String Return "" End Function End Class Partial MustInherit Class C Inherits B Public Overrides Property bing As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Protected MustOverride Overrides Function zing() As String End Class Class D Inherits C Public Overrides Sub quux() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30610: Class 'D' must either be declared 'MustInherit' or override the following inherited 'MustOverride' member(s): C: Protected MustOverride Overrides Function zing() As String B: Protected MustOverride Function baz() As String A: Public MustOverride Sub foo(x As Integer) A: Public MustOverride ReadOnly Property bang As Integer. Class D ~ </expected>) End Sub <Fact> Public Sub HidingMembersInClass() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Option Strict On Namespace N Class A Public Sub foo() End Sub Public Sub foo(x As Integer) End Sub Public Sub bar() End Sub Public Sub bar(x As Integer) End Sub Private Sub bing() End Sub Public Const baz As Integer = 5 Public Const baz2 As Integer = 5 End Class Class B Inherits A Public Shadows Sub foo(x As String) End Sub End Class Class C Inherits B Public foo As String Public bing As Integer Public Shadows baz As Integer Public baz2 As Integer Public Enum bar Red End Enum End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: variable 'foo' conflicts with sub 'foo' in the base class 'B' and should be declared 'Shadows'. Public foo As String ~~~ BC40004: variable 'baz2' conflicts with variable 'baz2' in the base class 'A' and should be declared 'Shadows'. Public baz2 As Integer ~~~~ BC40004: enum 'bar' conflicts with sub 'bar' in the base class 'A' and should be declared 'Shadows'. Public Enum bar ~~~ </expected>) End Sub <WorkItem(540791, "DevDiv")> <Fact> Public Sub HidingMembersInClass_01() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInClass"> <file name="a.vb"> Class C1 Inherits C2 ' no warnings here Class C(Of T) End Class ' warning Sub foo(Of T)() End Sub End Class Class C2 Class C End Class Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'foo' shadows an overloadable member declared in the base class 'C2'. If you want to overload the base method, this method must be declared 'Overloads'. Sub foo(Of T)() ~~~ </expected>) End Sub <Fact> Public Sub HidingMembersInInterface() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HidingMembersInInterface"> <file name="a.vb"> Option Strict On Namespace N Interface A Sub foo() Sub foo(x As Integer) Enum e Red End Enum End Interface Interface B Sub bar() Sub bar(x As Integer) End Interface Interface C Inherits A, B ReadOnly Property quux As Integer End Interface Interface D Inherits C Enum bar Red End Enum Enum foo Red End Enum Shadows Enum quux red End Enum End Interface End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40004: enum 'bar' conflicts with sub 'bar' in the base interface 'B' and should be declared 'Shadows'. Enum bar ~~~ BC40004: enum 'foo' conflicts with sub 'foo' in the base interface 'A' and should be declared 'Shadows'. Enum foo ~~~ </expected>) End Sub <Fact> Public Sub AccessorHidingNonAccessor() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Property Z As Integer Public Property ZZ As Integer End Class Public Class B Inherits A Public Sub get_Z() End Sub Public Shadows Sub get_ZZ() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40014: sub 'get_Z' conflicts with a member implicitly declared for property 'Z' in the base class 'A' and should be declared 'Shadows'. Public Sub get_Z() ~~~~~ </expected>) End Sub <Fact> Public Sub NonAccessorHidingAccessor() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="NonAccessorHidingAccessor"> <file name="a.vb"> Namespace N Public Class B Public Sub get_X() End Sub Public Sub get_XX() End Sub Public Sub set_Z() End Sub Public Sub set_ZZ() End Sub End Class Public Class A Inherits B Public Property X As Integer Public Property Z As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Shadows Property XX As Integer Public Shadows Property ZZ As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40012: property 'X' implicitly declares 'get_X', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property X As Integer ~ BC40012: property 'Z' implicitly declares 'set_Z', which conflicts with a member in the base class 'B', and so the property should be declared 'Shadows'. Public Property Z As Integer ~ </expected>) End Sub <Fact> Public Sub HidingShouldHaveOverloadsOrOverrides() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHidingNonAccessor"> <file name="a.vb"> Namespace N Public Class A Public Sub foo() End Sub Public Overridable Property bar As Integer End Class Public Class B Inherits A Public Sub foo(a As Integer) End Sub Public Property bar As String End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC40003: sub 'foo' shadows an overloadable member declared in the base class 'A'. If you want to overload the base method, this method must be declared 'Overloads'. Public Sub foo(a As Integer) ~~~ BC40005: property 'bar' shadows an overridable method in the base class 'A'. To override the base method, this method must be declared 'Overrides'. Public Property bar As String ~~~ </expected>) End Sub <Fact> Public Sub HiddenMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="HiddenMustOverride"> <file name="a.vb"> Option Strict On Namespace N Public MustInherit Class A Public MustOverride Sub f() Public MustOverride Sub f(a As Integer) Public MustOverride Sub g() Public MustOverride Sub h() Public MustOverride Sub i() Public MustOverride Function j(a As String) as Integer End Class Public MustInherit Class B Inherits A Public Overrides Sub g() End Sub End Class Public MustInherit Class C Inherits B Public Overloads Sub h(x As Integer) End Sub End Class Public MustInherit Class D Inherits C Public Shadows f As Integer Public Shadows g As Integer Public Shadows Enum h Red End Enum Public Overloads Sub i(x As String, y As String) End Sub Public Overloads Function j(a as String) As String return "" End Function End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31404: 'Public f As Integer' cannot shadow a method declared 'MustOverride'. Public Shadows f As Integer ~ BC31404: 'D.h' cannot shadow a method declared 'MustOverride'. Public Shadows Enum h ~ BC31404: 'Public Overloads Function j(a As String) As String' cannot shadow a method declared 'MustOverride'. Public Overloads Function j(a as String) As String ~ </expected>) End Sub <Fact> Public Sub AccessorHideMustOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessorHideMustOverride"> <file name="a.vb"> Namespace N Public MustInherit Class B Public MustOverride Property X As Integer Public MustOverride Function set_Y(a As Integer) End Class Public MustInherit Class A Inherits B Public Shadows Function get_X() As Integer Return 0 End Function Public Shadows Property Y As Integer End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31413: 'Public Property Set Y(AutoPropertyValue As Integer)', implicitly declared for property 'Y', cannot shadow a 'MustOverride' method in the base class 'B'. Public Shadows Property Y As Integer ~ </expected>) End Sub <Fact> Public Sub NoOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="NoOverride"> <file name="a.vb"> Option Strict On Namespace N Class A Public Overridable Property x As Integer Public Overridable Sub y() End Sub Public z As Integer End Class Class B Inherits A Public Overrides Sub x(a As String, b As Integer) End Sub Public Overrides Sub y(x As Integer) End Sub Public Overrides Property z As Integer End Class Structure K Public Overrides Function f() As Integer Return 0 End Function End Structure End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30284: sub 'x' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub x(a As String, b As Integer) ~ BC40004: sub 'x' conflicts with property 'x' in the base class 'A' and should be declared 'Shadows'. Public Overrides Sub x(a As String, b As Integer) ~ BC30284: sub 'y' cannot be declared 'Overrides' because it does not override a sub in a base class. Public Overrides Sub y(x As Integer) ~ BC30284: property 'z' cannot be declared 'Overrides' because it does not override a property in a base class. Public Overrides Property z As Integer ~ BC40004: property 'z' conflicts with variable 'z' in the base class 'A' and should be declared 'Shadows'. Public Overrides Property z As Integer ~ BC30284: function 'f' cannot be declared 'Overrides' because it does not override a function in a base class. Public Overrides Function f() As Integer ~ </expected>) End Sub <Fact> Public Sub AmbiguousOverride() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AmbiguousOverride"> <file name="a.vb"> Namespace N Class A(Of T, U) Public Overridable Sub foo(a As T) End Sub Public Overridable Sub foo(a As U) End Sub Public Overridable Sub foo(a As String) End Sub Public Overridable Property bar As Integer Public Overridable ReadOnly Property bar(a As T) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As U) As Integer Get Return 0 End Get End Property Public Overridable ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class Class B Inherits A(Of String, String) Public Overrides Sub foo(a As String) End Sub Public Overrides ReadOnly Property bar(a As String) As Integer Get Return 0 End Get End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30935: Member 'Public Overridable Sub foo(a As String)' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable Sub foo(a As T)' 'Public Overridable Sub foo(a As U)' 'Public Overridable Sub foo(a As String)' Public Overrides Sub foo(a As String) ~~~ BC30935: Member 'Public Overridable ReadOnly Property bar(a As String) As Integer' that matches this signature cannot be overridden because the class 'A' contains multiple members with this same name and signature: 'Public Overridable ReadOnly Property bar(a As T) As Integer' 'Public Overridable ReadOnly Property bar(a As U) As Integer' 'Public Overridable ReadOnly Property bar(a As String) As Integer' Public Overrides ReadOnly Property bar(a As String) As Integer ~~~ </expected>) End Sub <Fact> Public Sub OverrideNotOverridable() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OverrideNotOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Overridable Sub f() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class B Inherits A Public NotOverridable Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Public Class C Inherits B Public Overrides Sub f() End Sub Public NotOverridable Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30267: 'Public Overrides Sub f()' cannot override 'Public NotOverridable Overrides Sub f()' because it is declared 'NotOverridable'. Public Overrides Sub f() ~ BC30267: 'Public NotOverridable Overrides Property p As Integer' cannot override 'Public NotOverridable Overrides Property p As Integer' because it is declared 'NotOverridable'. Public NotOverridable Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub MustBeOverridable() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="MustBeOverridable"> <file name="a.vb"> Option Strict On Namespace N Public Class A Public Sub f() End Sub Public Property p As Integer End Class Public Class B Inherits A Public Overrides Sub f() End Sub Public Overrides Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31086: 'Public Overrides Sub f()' cannot override 'Public Sub f()' because it is not declared 'Overridable'. Public Overrides Sub f() ~ BC31086: 'Public Overrides Property p As Integer' cannot override 'Public Property p As Integer' because it is not declared 'Overridable'. Public Overrides Property p As Integer ~ </expected>) End Sub <Fact> Public Sub ByRefMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ByRefMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, ByRef a As Integer) End Sub End Class Class B Inherits A Public Overrides Sub f(q As String, a As Integer) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30398: 'Public Overrides Sub f(q As String, a As Integer)' cannot override 'Public Overridable Sub f(q As String, ByRef a As Integer)' because they differ by a parameter that is marked as 'ByRef' versus 'ByVal'. Public Overrides Sub f(q As String, a As Integer) ~ </expected>) End Sub <Fact> Public Sub OptionalMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f(q As String, Optional a As Integer = 5) End Sub Public Overridable Sub g(q As String) End Sub Public Overridable Property p1(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Property p2(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Sub f(q As String) End Sub Public Overrides Sub g(q As String, Optional a As Integer = 4) End Sub Public Overrides Property p1(q As String) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30308: 'Public Overrides Sub f(q As String)' cannot override 'Public Overridable Sub f(q As String, [a As Integer = 5])' because they differ by optional parameters. Public Overrides Sub f(q As String) ~ BC30308: 'Public Overrides Sub g(q As String, [a As Integer = 4])' cannot override 'Public Overridable Sub g(q As String)' because they differ by optional parameters. Public Overrides Sub g(q As String, Optional a As Integer = 4) ~ BC30308: 'Public Overrides Property p1(q As String) As Integer' cannot override 'Public Overridable Property p1(q As String, [a As Integer = 5]) As Integer' because they differ by optional parameters. Public Overrides Property p1(q As String) As Integer ~~ BC30308: 'Public Overrides Property p2(q As String, [a As Integer = 5]) As Integer' cannot override 'Public Overridable Property p2(q As String) As Integer' because they differ by optional parameters. Public Overrides Property p2(q As String, Optional a As Integer = 5) As Integer ~~ </expected>) End Sub <Fact> Public Sub ReturnTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ReturnTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Function x(a As Integer) As String Return "" End Function Public Overridable Function y(Of T)() As T Return Nothing End Function Public Overridable Sub z() End Sub Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides Function y(Of U)() As U Return Nothing End Function Public Overrides Function x(a As Integer) As Integer Return 0 End Function Public Overrides Function z() As Integer Return 0 End Function Public Overrides Property p As String Get Return "" End Get Set(value As String) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30437: 'Public Overrides Function x(a As Integer) As Integer' cannot override 'Public Overridable Function x(a As Integer) As String' because they differ by their return types. Public Overrides Function x(a As Integer) As Integer ~ BC30437: 'Public Overrides Function z() As Integer' cannot override 'Public Overridable Sub z()' because they differ by their return types. Public Overrides Function z() As Integer ~ BC30437: 'Public Overrides Property p As String' cannot override 'Public Overridable Property p As Integer' because they differ by their return types. Public Overrides Property p As String ~ </expected>) End Sub <Fact> Public Sub PropertyTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable ReadOnly Property q As Integer Get Return 0 End Get End Property Public Overridable WriteOnly Property r As Integer Set(value As Integer) End Set End Property End Class Class B Inherits A Public Overrides ReadOnly Property p As Integer Get Return 0 End Get End Property Public Overrides WriteOnly Property q As Integer Set(value As Integer) End Set End Property Public Overrides Property r As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30362: 'Public Overrides ReadOnly Property p As Integer' cannot override 'Public Overridable Property p As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property p As Integer ~ BC30362: 'Public Overrides WriteOnly Property q As Integer' cannot override 'Public Overridable ReadOnly Property q As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property q As Integer ~ BC30362: 'Public Overrides Property r As Integer' cannot override 'Public Overridable WriteOnly Property r As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property r As Integer ~ </expected>) End Sub <WorkItem(540791, "DevDiv")> <Fact> Public Sub PropertyAccessibilityMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Protected Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Get Return m_Property1 End Get Private Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Set").WithArguments("Private Overrides Property Set Property1(value As Long)", "Protected Overridable Property Set Property1(value As Long)")) End Sub <Fact> Public Sub PropertyAccessibilityMismatch2() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="PropertyAccessibilityMismatch"> <file name="a.vb"> Public Class Base Public Overridable Property Property1() As Long Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class Public Class Derived1 Inherits Base Public Overrides Property Property1() As Long Protected Get Return m_Property1 End Get Set(value As Long) m_Property1 = Value End Set End Property Private m_Property1 As Long End Class </file> </compilation>) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_BadOverrideAccess2, "Get").WithArguments("Protected Overrides Property Get Property1() As Long", "Public Overridable Property Get Property1() As Long")) End Sub <Fact> <WorkItem(546836, "DevDiv")> Public Sub PropertyOverrideAccessibility() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() Dim vbComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, emitOptions:=TestEmitters.CCI, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact> <WorkItem(546836, "DevDiv")> Public Sub PropertyOverrideAccessibilityInternalsVisibleTo() Dim csharpComp = CreateCSharpCompilation("Lib", <![CDATA[ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("PropertyOverrideAccessibilityInternalsVisibleTo")] public class A { public virtual int P { get { System.Console.WriteLine("A.P.get"); return 0; } protected internal set { System.Console.WriteLine("A.P.set"); } } internal static void ConfirmIVT() { } } public class B : A { public override int P { protected internal set { System.Console.WriteLine("B.P.set"); } } } public class C : A { public override int P { get { System.Console.WriteLine("C.P.get"); return 0; } } } ]]>) csharpComp.VerifyDiagnostics() Dim csharpRef = csharpComp.EmitToImageReference() ' Unlike in C#, internals-visible-to does not affect the way protected friend ' members are overridden (i.e. still must be protected). Dim vbComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibilityInternalsVisibleTo"> <file name="a.vb"> Public Class D1 Inherits A Public Overrides Property P() As Integer Get System.Console.WriteLine("D1.P.get") Return 0 End Get Protected Set(value As Integer) System.Console.WriteLine("D1.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D2 Inherits B Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) System.Console.WriteLine("D2.P.set") End Set End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Public Class D3 Inherits C Public Overrides ReadOnly Property P() As Integer Get System.Console.WriteLine("D3.P.get") Return 0 End Get End Property Public Sub Test() Me.P = 1 Dim x = Me.P End Sub End Class Module Test Sub Main() A.ConfirmIVT() Dim d1 As New D1() Dim d2 As New D2() Dim d3 As New D3() d1.Test() d2.Test() d3.Test() End Sub End Module </file> </compilation>, {csharpRef}, TestOptions.ReleaseExe) CompileAndVerify(vbComp, emitOptions:=TestEmitters.CCI, expectedOutput:=<![CDATA[ D1.P.set D1.P.get D2.P.set A.P.get A.P.set D3.P.get ]]>) Dim errorComp = CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation name="PropertyOverrideAccessibility"> <file name="a.vb"> ' Set is protected friend, but should be protected Public Class D1 Inherits A Public Overrides Property P() As Integer Get Return 0 End Get Protected Friend Set(value As Integer) End Set End Property End Class ' protected friend, should be protected Public Class D2 Inherits B Protected Friend Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class ' Can't override getter (Dev11 also gives error about accessibility change) Public Class D3 Inherits B Public Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Getter has to be public Public Class D4 Inherits C Protected Overrides ReadOnly Property P() As Integer Get Return 0 End Get End Property End Class ' Can't override setter (Dev11 also gives error about accessibility change) Public Class D5 Inherits C Protected Overrides WriteOnly Property P() As Integer Set(value As Integer) End Set End Property End Class </file> </compilation>, {csharpRef}) errorComp.VerifyDiagnostics( Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "P").WithArguments("Protected Friend Overrides WriteOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_FriendAssemblyBadAccessOverride2, "Set").WithArguments("Protected Friend Overrides Property Set P(value As Integer)", "Protected Friend Overridable Overloads Property Set P(value As Integer)"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Protected Overrides WriteOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer"), Diagnostic(ERRID.ERR_OverridingPropertyKind2, "P").WithArguments("Public Overrides ReadOnly Property P As Integer", "Protected Friend Overrides WriteOnly Property P As Integer"), Diagnostic(ERRID.ERR_BadOverrideAccess2, "P").WithArguments("Protected Overrides ReadOnly Property P As Integer", "Public Overrides ReadOnly Property P As Integer")) End Sub <Fact()> Public Sub OptionalValueMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalValueMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional k As Integer = 4) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional k As String = "foo") End Sub End Class Class B Inherits A Public Overrides Property p(Optional k As Integer = 7) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional k As String = "hi") End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30307: 'Public Overrides Property p([k As Integer = 7]) As Integer' cannot override 'Public Overridable Property p([k As Integer = 4]) As Integer' because they differ by the default values of optional parameters. Public Overrides Property p(Optional k As Integer = 7) As Integer ~ BC30307: 'Public Overrides Sub f([k As String = "hi"])' cannot override 'Public Overridable Sub f([k As String = "foo"])' because they differ by the default values of optional parameters. Public Overrides Sub f(Optional k As String = "hi") ~ </expected>) End Sub <Fact> Public Sub ParamArrayMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ParamArrayMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(ParamArray x() As String) End Sub End Class Class B Inherits A Public Overrides Property p(ParamArray x() As Integer) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(x() As String) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30906: 'Public Overrides Property p(ParamArray x As Integer()) As Integer' cannot override 'Public Overridable Property p(x As Integer()) As Integer' because they differ by parameters declared 'ParamArray'. Public Overrides Property p(ParamArray x() As Integer) As Integer ~ BC30906: 'Public Overrides Sub f(x As String())' cannot override 'Public Overridable Sub f(ParamArray x As String())' because they differ by parameters declared 'ParamArray'. Public Overrides Sub f(x() As String) ~ </expected>) End Sub <WorkItem(529018, "DevDiv")> <Fact()> Public Sub OptionalTypeMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="OptionalTypeMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Property p(Optional x As String = "") As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overridable Sub f(Optional x As String = "") End Sub End Class Class B Inherits A Public Overrides Property p(Optional x As Integer = 0) As Integer Get Return 0 End Get Set(value As Integer) End Set End Property Public Overrides Sub f(Optional x As Integer = 0) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30697: 'Public Overrides Property p([x As Integer = 0]) As Integer' cannot override 'Public Overridable Property p([x As String = ""]) As Integer' because they differ by the types of optional parameters. Public Overrides Property p(Optional x As Integer = 0) As Integer ~ BC30697: 'Public Overrides Sub f([x As Integer = 0])' cannot override 'Public Overridable Sub f([x As String = ""])' because they differ by the types of optional parameters. Public Overrides Sub f(Optional x As Integer = 0) ~ </expected>) End Sub <Fact()> Public Sub ConstraintMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="ConstraintMismatch"> <file name="a.vb"> Imports System Namespace N Class A Public Overridable Sub f(Of T As ICloneable)(x As T) End Sub End Class Class B Inherits A Public Overrides Sub f(Of U)(x As U) End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC32077: 'Public Overrides Sub f(Of U)(x As U)' cannot override 'Public Overridable Sub f(Of T As ICloneable)(x As T)' because they differ by type parameter constraints. Public Overrides Sub f(Of U)(x As U) ~ </expected>) End Sub <Fact> Public Sub AccessMismatch() Dim comp = CreateCompilationWithMscorlibAndVBRuntime( <compilation name="AccessMismatch"> <file name="a.vb"> Namespace N Class A Public Overridable Sub f() End Sub Protected Overridable Sub g() End Sub Friend Overridable Sub h() End Sub End Class Class B Inherits A Protected Overrides Sub f() End Sub Public Overrides Sub g() End Sub Protected Friend Overrides Sub h() End Sub End Class End Namespace </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC30266: 'Protected Overrides Sub f()' cannot override 'Public Overridable Sub f()' because they have different access levels. Protected Overrides Sub f() ~ BC30266: 'Public Overrides Sub g()' cannot override 'Protected Overridable Sub g()' because they have different access levels. Public Overrides Sub g() ~ BC30266: 'Protected Friend Overrides Sub h()' cannot override 'Friend Overridable Sub h()' because they have different access levels. Protected Friend Overrides Sub h() ~ </expected>) End Sub <Fact> Public Sub PropertyShadows() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Interface IA Default Overloads ReadOnly Property P(o As Object) Property Q(o As Object) End Interface Interface IB Inherits IA Default Overloads ReadOnly Property P(x As Integer, y As Integer) Overloads Property Q(x As Integer, y As Integer) End Interface Interface IC Inherits IA Default Shadows ReadOnly Property P(x As Integer, y As Integer) Shadows Property Q(x As Integer, y As Integer) End Interface Module M Sub M(b As IB, c As IC) Dim value As Object value = b.P(1, 2) value = b.P(3) value = b(1, 2) value = b(3) b.Q(1, 2) = value b.Q(3) = value value = c.P(1, 2) value = c.P(3) value = c(1, 2) value = c(3) c.Q(1, 2) = value c.Q(3) = value End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c.P(3) ~ BC30455: Argument not specified for parameter 'y' of 'ReadOnly Default Property P(x As Integer, y As Integer) As Object'. value = c(3) ~ BC30455: Argument not specified for parameter 'y' of 'Property Q(x As Integer, y As Integer) As Object'. c.Q(3) = value ~ </expected>) End Sub <Fact> Public Sub ShadowsNotOverloads() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Class A Public Sub M1(o As Object) End Sub Public Overloads Sub M2(o As Object) End Sub Public ReadOnly Property P1(o As Object) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(o As Object) Get Return Nothing End Get End Property End Class Class B Inherits A Public Shadows Sub M1(x As Integer, y As Integer) End Sub Public Overloads Sub M2(x As Integer, y As Integer) End Sub Public Shadows ReadOnly Property P1(x As Integer, y As Integer) Get Return Nothing End Get End Property Public Overloads ReadOnly Property P2(x As Integer, y As Integer) Get Return Nothing End Get End Property End Class Module M Sub M(o As B) Dim value o.M1(1) o.M2(1) value = o.P1(1) value = o.P2(1) End Sub End Module </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Sub M1(x As Integer, y As Integer)'. o.M1(1) ~~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property P1(x As Integer, y As Integer) As Object'. value = o.P1(1) ~~ </expected>) End Sub <Fact> Public Sub OverridingBlockedByShadowing() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class A Overridable Sub Foo() End Sub Overridable Sub Bar() End Sub Overridable Sub Quux() End Sub End Class Class B Inherits A Shadows Sub Foo(x As Integer) End Sub Overloads Property Bar(x As Integer) Get Return Nothing End Get Set(value) End Set End Property Public Shadows Quux As Integer End Class Class C Inherits B Overrides Sub Foo() End Sub Overrides Sub Bar() End Sub Overrides Sub Quux() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC40004: property 'Bar' conflicts with sub 'Bar' in the base class 'A' and should be declared 'Shadows'. Overloads Property Bar(x As Integer) ~~~ BC30284: sub 'Foo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Foo() ~~~ BC30284: sub 'Bar' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Bar() ~~~ BC40004: sub 'Bar' conflicts with property 'Bar' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Bar() ~~~ BC30284: sub 'Quux' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Quux() ~~~~ BC40004: sub 'Quux' conflicts with variable 'Quux' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Quux() ~~~~ </expected>) End Sub <WorkItem(541752, "DevDiv")> <Fact> Public Sub Bug8634() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Class A Overridable Sub Foo() End Sub End Class Class B Inherits A Shadows Property Foo() As Integer End Class Class C Inherits B Overrides Sub Foo() End Sub End Class </file> </compilation>) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30284: sub 'Foo' cannot be declared 'Overrides' because it does not override a sub in a base class. Overrides Sub Foo() ~~~ BC40004: sub 'Foo' conflicts with property 'Foo' in the base class 'B' and should be declared 'Shadows'. Overrides Sub Foo() ~~~ </expected>) End Sub <Fact> Public Sub HideBySig() Dim customIL = <![CDATA[ .class public A { .method public hidebysig instance object F(object o) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .property object P(object o) { .get instance object A::get_P(object o) } .property object Q(object o) { .get instance object A::get_Q(object o) } } .class public B extends A { .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object x, object y) { .get instance object B::get_P(object x, object y) } .property object Q(object x, object y) { .get instance object B::get_Q(object x, object y) } } .class public C { .method public hidebysig instance object F(object o) { ldnull ret } .method public hidebysig instance object F(object x, object y) { ldnull ret } .method public instance object G(object o) { ldnull ret } .method public instance object G(object x, object y) { ldnull ret } .method public hidebysig instance object get_P(object o) { ldnull ret } .method public hidebysig instance object get_P(object x, object y) { ldnull ret } .method public instance object get_Q(object o) { ldnull ret } .method public instance object get_Q(object x, object y) { ldnull ret } .property object P(object o) { .get instance object C::get_P(object o) } .property object P(object x, object y) { .get instance object C::get_P(object x, object y) } .property object Q(object o) { .get instance object C::get_Q(object o) } .property object Q(object x, object y) { .get instance object C::get_Q(object x, object y) } } ]]> Dim source = <compilation> <file name="a.vb"> Module M Sub M(b As B, c As C) Dim value As Object value = b.F(b, c) value = b.F(Nothing) value = b.G(b, c) value = b.G(Nothing) value = b.P(b, c) value = b.P(Nothing) value = b.Q(b, c) value = b.Q(Nothing) value = c.F(b, c) value = c.F(Nothing) value = c.G(b, c) value = c.G(Nothing) value = c.P(b, c) value = c.P(Nothing) value = c.Q(b, c) value = c.Q(Nothing) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30455: Argument not specified for parameter 'y' of 'Public Function G(x As Object, y As Object) As Object'. value = b.G(Nothing) ~ BC30455: Argument not specified for parameter 'y' of 'Public ReadOnly Property Q(x As Object, y As Object) As Object'. value = b.Q(Nothing) ~ </expected>) End Sub <Fact()> Public Sub Bug10702() Dim code = <compilation name="SimpleOverrides"> <file name="a.vb"> Imports System.Collections.Generic Class SyntaxNode : End Class Structure SyntaxToken : End Structure Class CancellationToken : End Class Class Diagnostic : End Class MustInherit Class BaseSyntaxTree Protected MustOverride Overloads Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Protected MustOverride Overloads Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) End Class Class SyntaxTree : Inherits BaseSyntaxTree Protected Overrides Function GetDiagnosticsCore(Optional cancellationToken As CancellationToken = Nothing) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(node As SyntaxNode) As IEnumerable(Of Diagnostic) Return Nothing End Function Protected Overrides Function GetDiagnosticsCore(token As SyntaxToken) As IEnumerable(Of Diagnostic) Return Nothing End Function End Class Public Module Module1 Sub Main() End Sub End Module </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code) CompileAndVerify(code).VerifyDiagnostics() End Sub <Fact, WorkItem(543948, "DevDiv")> Public Sub OverrideMemberOfConstructedProtectedInnerClass() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Public Class Outer1(Of T) Protected MustInherit Class Inner1 Public MustOverride Sub Method() End Class Protected MustInherit Class Inner2 Inherits Inner1 Public Overrides Sub Method() End Sub End Class End Class </file> </compilation>) Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndReferences( <compilation> <file name="a.vb"> Friend Class Outer2 Inherits Outer1(Of Outer2) Private Class Inner3 Inherits Inner2 End Class End Class </file> </compilation>, {New VisualBasicCompilationReference(compilation1)}) CompilationUtils.AssertNoErrors(compilation2) End Sub <Fact, WorkItem(545484, "DevDiv")> Public Sub MetadataOverridesOfAccessors() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Property Foo As Integer Get Return 1 End Get Set(value As Integer) End Set End Property End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Foo { get { return base.Foo; } set { base.Foo = value; } } public virtual event Action Bar { add{} remove{}} } public class X3: X2 { public override event Action Bar { add {} remove {} } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, additionalRefs:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim propX1Foo = DirectCast(classX1.GetMembers("Foo").First(), PropertySymbol) Dim accessorX1GetFoo = DirectCast(classX1.GetMembers("get_Foo").First(), MethodSymbol) Dim accessorX1SetFoo = DirectCast(classX1.GetMembers("set_Foo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim propX2Foo = DirectCast(classX2.GetMembers("Foo").First(), PropertySymbol) Dim accessorX2GetFoo = DirectCast(classX2.GetMembers("get_Foo").First(), MethodSymbol) Dim accessorX2SetFoo = DirectCast(classX2.GetMembers("set_Foo").First(), MethodSymbol) Dim classX3 = DirectCast(globalNS.GetMembers("X3").First(), NamedTypeSymbol) Dim overriddenPropX1Foo = propX1Foo.OverriddenProperty Assert.Null(overriddenPropX1Foo) Dim overriddenPropX2Foo = propX2Foo.OverriddenProperty Assert.NotNull(overriddenPropX2Foo) Assert.Equal(propX1Foo, overriddenPropX2Foo) Dim overriddenAccessorX1GetFoo = accessorX1GetFoo.OverriddenMethod Assert.Null(overriddenAccessorX1GetFoo) Dim overriddenAccessorX2GetFoo = accessorX2GetFoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2GetFoo) Assert.Equal(accessorX1GetFoo, overriddenAccessorX2GetFoo) Dim overriddenAccessorX1SetFoo = accessorX1SetFoo.OverriddenMethod Assert.Null(overriddenAccessorX1SetFoo) Dim overriddenAccessorX2SetFoo = accessorX2SetFoo.OverriddenMethod Assert.NotNull(overriddenAccessorX2SetFoo) Assert.Equal(accessorX1SetFoo, overriddenAccessorX2SetFoo) Dim eventX2Bar = DirectCast(classX2.GetMembers("Bar").First(), EventSymbol) Dim accessorX2AddBar = DirectCast(classX2.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX2RemoveBar = DirectCast(classX2.GetMembers("remove_Bar").First(), MethodSymbol) Dim eventX3Bar = DirectCast(classX3.GetMembers("Bar").First(), EventSymbol) Dim accessorX3AddBar = DirectCast(classX3.GetMembers("add_Bar").First(), MethodSymbol) Dim accessorX3RemoveBar = DirectCast(classX3.GetMembers("remove_Bar").First(), MethodSymbol) Dim overriddenEventX2Bar = eventX2Bar.OverriddenEvent Assert.Null(overriddenEventX2Bar) Dim overriddenEventX3Bar = eventX3Bar.OverriddenEvent Assert.NotNull(overriddenEventX3Bar) Assert.Equal(eventX2Bar, overriddenEventX3Bar) Dim overriddenAccessorsX2AddBar = accessorX2AddBar.OverriddenMethod Assert.Null(overriddenAccessorsX2AddBar) Dim overriddenAccessorsX3AddBar = accessorX3AddBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3AddBar) Assert.Equal(accessorX2AddBar, overriddenAccessorsX3AddBar) Dim overriddenAccessorsX2RemoveBar = accessorX2RemoveBar.OverriddenMethod Assert.Null(overriddenAccessorsX2RemoveBar) Dim overriddenAccessorsX3RemoveBar = accessorX3RemoveBar.OverriddenMethod Assert.NotNull(overriddenAccessorsX3RemoveBar) Assert.Equal(accessorX2RemoveBar, overriddenAccessorsX3RemoveBar) End Sub <Fact, WorkItem(545484, "DevDiv")> Public Sub OverridesOfConstructedMethods() Dim compilation1 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Option Strict On Public Class X1 Public Overridable Function Foo(Of T)(x as T) As Integer Return 1 End Function End Class </file> </compilation>) Dim compilation2 = CreateCSharpCompilation("assem2", <![CDATA[ using System; public class X2: X1 { public override int Foo<T>(T x) { return base.Foo(x); } } ]]>.Value, referencedCompilations:={compilation1}) Dim compilation2Bytes = compilation2.EmitToArray() Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Class Dummy End Class </file> </compilation>, additionalRefs:={New VisualBasicCompilationReference(compilation1), MetadataReference.CreateFromImage(compilation2Bytes)}) Dim globalNS = compilation3.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim methodX1Foo = DirectCast(classX1.GetMembers("Foo").First(), MethodSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim methodX2Foo = DirectCast(classX2.GetMembers("Foo").First(), MethodSymbol) Dim overriddenMethX1Foo = methodX1Foo.OverriddenMethod Assert.Null(overriddenMethX1Foo) Dim overriddenMethX2Foo = methodX2Foo.OverriddenMethod Assert.NotNull(overriddenMethX2Foo) Assert.Equal(methodX1Foo, overriddenMethX2Foo) ' Constructed methods should never override. Dim constructedMethodX1Foo = methodX1Foo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim constructedMethodX2Foo = methodX2Foo.Construct(compilation3.GetWellKnownType(WellKnownType.System_Exception)) Dim overriddenConstructedMethX1Foo = constructedMethodX1Foo.OverriddenMethod Assert.Null(overriddenConstructedMethX1Foo) Dim overriddenConstructedMethX2Foo = constructedMethodX2Foo.OverriddenMethod Assert.Null(overriddenConstructedMethX2Foo) End Sub <Fact, WorkItem(539893, "DevDiv")> Public Sub AccessorMetadataCasing() Dim compilation1 = CreateCSharpCompilation("assem2", <![CDATA[ using System; using System.Collections.Generic; public class CSharpBase { public virtual int Prop1 { get { return 0; } set { } } } ]]>.Value) Dim compilation1Bytes = compilation1.EmitToArray() Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences( <compilation> <file name="a.vb"> Option Strict On Imports System Class X1 Inherits CSharpBase Public Overloads Property pRop1(x As String) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property prop1 As Integer Get Return MyBase.Prop1 End Get Set(value As Integer) MyBase.Prop1 = value End Set End Property Public Overridable Overloads Property pROP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class X2 Inherits X1 Public Overloads Property PROP1(x As Double) As String Get Return "" End Get Set(value As String) End Set End Property Public Overloads Overrides Property proP1(x As Long) As String Get Return "" End Get Set(value As String) End Set End Property Public Overrides Property PrOp1 As Integer End Class </file> </compilation>, additionalRefs:={MetadataReference.CreateFromImage(compilation1Bytes)}) Dim globalNS = compilation2.GlobalNamespace Dim classX1 = DirectCast(globalNS.GetMembers("X1").First(), NamedTypeSymbol) Dim classX2 = DirectCast(globalNS.GetMembers("X2").First(), NamedTypeSymbol) Dim x1Getters = (From memb In classX1.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1Setters = (From memb In classX1.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Getters = (From memb In classX2.GetMembers("get_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x2Setters = (From memb In classX2.GetMembers("set_Prop1") Where memb.Kind = SymbolKind.Method Select DirectCast(memb, MethodSymbol)) Dim x1noArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_prop1", x1noArgGetter.Name) Assert.Equal("get_Prop1", x1noArgGetter.MetadataName) Dim x1StringArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("get_pRop1", x1StringArgGetter.Name) Assert.Equal("get_pRop1", x1StringArgGetter.MetadataName) Dim x1LongArgGetter = (From meth In x1Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_pROP1", x1LongArgGetter.Name) Assert.Equal("get_pROP1", x1LongArgGetter.MetadataName) Dim x2noArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 0 Select meth).First() Assert.Equal("get_PrOp1", x2noArgGetter.Name) Assert.Equal("get_Prop1", x2noArgGetter.MetadataName) Dim x2LongArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("get_proP1", x2LongArgGetter.Name) Assert.Equal("get_pROP1", x2LongArgGetter.MetadataName) Dim x2DoubleArgGetter = (From meth In x2Getters Let params = meth.Parameters Where params.Length = 1 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("get_PROP1", x2DoubleArgGetter.Name) Assert.Equal("get_PROP1", x2DoubleArgGetter.MetadataName) Dim x1noArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_prop1", x1noArgSetter.Name) Assert.Equal("set_Prop1", x1noArgSetter.MetadataName) Dim x1StringArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_String Select meth).First() Assert.Equal("set_pRop1", x1StringArgSetter.Name) Assert.Equal("set_pRop1", x1StringArgSetter.MetadataName) Dim x1LongArgSetter = (From meth In x1Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_pROP1", x1LongArgSetter.Name) Assert.Equal("set_pROP1", x1LongArgSetter.MetadataName) Dim x2noArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 1 Select meth).First() Assert.Equal("set_PrOp1", x2noArgSetter.Name) Assert.Equal("set_Prop1", x2noArgSetter.MetadataName) Dim x2LongArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Int64 Select meth).First() Assert.Equal("set_proP1", x2LongArgSetter.Name) Assert.Equal("set_pROP1", x2LongArgSetter.MetadataName) Dim x2DoubleArgSetter = (From meth In x2Setters Let params = meth.Parameters Where params.Length = 2 AndAlso params(0).Type.SpecialType = SpecialType.System_Double Select meth).First() Assert.Equal("set_PROP1", x2DoubleArgSetter.Name) Assert.Equal("set_PROP1", x2DoubleArgSetter.MetadataName) End Sub <Fact(), WorkItem(546816, "DevDiv")> Public Sub Bug16887() Dim compilation = CompilationUtils.CreateCompilationWithReferences( <compilation name="E"> <file name="a.vb"><![CDATA[ Class SelfDestruct Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class ]]></file> </compilation>, {MscorlibRef_v20}) Dim obj = compilation.GetSpecialType(SpecialType.System_Object) Dim finalize = DirectCast(obj.GetMembers("Finalize").Single(), MethodSymbol) Assert.True(finalize.IsOverridable) Assert.False(finalize.IsOverrides) AssertTheseDiagnostics(compilation, <expected></expected>) CompileAndVerify(compilation) End Sub <WorkItem(608228, "DevDiv")> <Fact> Sub OverridePropertyWithByRefParameter() Dim il = <![CDATA[ .class public auto ansi Base extends [mscorlib]System.Object { .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method public newslot specialname strict virtual instance string get_P(int32& x) cil managed { ldnull ret } .method public newslot specialname strict virtual instance void set_P(int32& x, string 'value') cil managed { ret } .property instance string P(int32&) { .set instance void Base::set_P(int32&, string) .get instance string Base::get_P(int32&) } } // end of class Base ]]> Dim source = <compilation> <file name="a.vb"> Public Class Derived Inherits Base Public Overrides Property P(x As Integer) As String Get Return Nothing End Get Set(value As String) End Set End Property End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_OverrideWithByref2, "P").WithArguments("Public Overrides Property P(x As Integer) As String", "Public Overridable Property P(ByRef x As Integer) As String")) Dim globalNamespace = compilation.GlobalNamespace Dim baseType = globalNamespace.GetMember(Of NamedTypeSymbol)("Base") Dim baseProperty = baseType.GetMember(Of PropertySymbol)("P") Assert.True(baseProperty.Parameters.Single().IsByRef) Dim derivedType = globalNamespace.GetMember(Of NamedTypeSymbol)("Derived") Dim derivedProperty = derivedType.GetMember(Of PropertySymbol)("P") Assert.False(derivedProperty.Parameters.Single().IsByRef) ' Note: matches dev11, but not interface implementation (which treats the PEProperty as bogus). Assert.Equal(baseProperty, derivedProperty.OverriddenProperty) End Sub <Fact(), WorkItem(528549, "DevDiv")> Public Sub Bug528549() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module CORError033mod NotOverridable Sub abcDef() End Sub Overrides Sub abcDef2() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(compilation, <expected> BC30433: Methods in a Module cannot be declared 'NotOverridable'. NotOverridable Sub abcDef() ~~~~~~~~~~~~~~ BC30433: Methods in a Module cannot be declared 'Overrides'. Overrides Sub abcDef2() ~~~~~~~~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_01() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_02() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_03() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_04() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_05() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Integer' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_06() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Output from native compiler: 'Base::M1_1 'Derived.M1 'Base::M1_3 Dim compilation = CompileWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseExe, expectedOutput:="Base::M1_1" & vbCrLf & "Derived.M1" & vbCrLf & "Base::M1_3") compilation.VerifyDiagnostics() End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_07() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int32 M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_3" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_08() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler doesn't produce any error, but neither method is considered overriden by the runtime. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_09() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int64 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_10() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors, nothing is overriden Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Long' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_11() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public newslot strict virtual instance int64 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int64 V_0) IL_0000: ldstr "Base::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int64 Base::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> ' Native compiler: no errors ' Derived.M1 ' Base::M1_2 ' Roslyn's behavior looks reasonable and it has nothing to do with custom modifiers. Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30935: Member 'Public Overridable Function M1(x As Integer) As Integer' that matches this signature cannot be overridden because the class 'Base' contains multiple members with this same name and signature: 'Public Overridable Function M1(x As Integer) As Integer' 'Public Overridable Function M1(x As Integer) As Long' Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_12() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_13() Dim ilSource = <![CDATA[ .class public abstract auto ansi BaseBase extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "BaseBase::M1_2" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldloc.0 IL_000f: ret } // end of method Base::M1 } // end of class BaseBase .class public abstract auto ansi Base extends BaseBase { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void BaseBase::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 IL_0000: ldstr "Base::M1_1" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000e: ldnull IL_000f: ret } // end of method Base::M1 .method public instance void Test() cil managed { ldarg.0 ldc.i4.0 callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::M1(int32) pop ldarg.0 ldc.i4.0 callvirt instance int32 BaseBase::M1(int32) pop IL_0006: ret } // end of method Base::.ctor } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module Module1 Sub Main() Dim x as Base = New Derived() x.Test() End Sub End Module Class Derived Inherits Base Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function End Class ]]> </file> </compilation> Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30437: 'Public Overrides Function M1(x As Integer) As Integer' cannot override 'Public Overridable Function M1(x As Integer) As Integer()' because they differ by their return types. Public Overrides Function M1(x As Integer) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_14() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M3(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M11(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M1 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] M12(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { } // end of method Base::M2 .method public newslot abstract strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M13(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { } // end of method Base::M3 .method public newslot abstract strict virtual instance !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) M4<T>(!!T y, !!T modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, !!T [] z) cil managed { } // end of method Base::M4 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Imports System.Runtime.InteropServices Module Module1 Sub Main() Dim x as Base = New Derived() x.M1(Nothing) x.M2(Nothing) x.M3(Nothing) x.M11(Nothing) x.M12(Nothing) x.M13(Nothing) x.M4(Of Integer)(Nothing, Nothing, Nothing) End Sub End Module Class Derived Inherits Base Public Overrides Function M2(x() As Integer) As Integer() System.Console.WriteLine("Derived.M2") return Nothing End Function Public Overrides Function M1(x As Integer) As Integer System.Console.WriteLine("Derived.M1") return Nothing End Function Public Overrides Function M3(x() As Integer) As Integer() System.Console.WriteLine("Derived.M3") return Nothing End Function Public Overrides Function M12(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M12") return Nothing End Function Public Overrides Function M11(<[In]> x As Integer) As Integer System.Console.WriteLine("Derived.M11") return Nothing End Function Public Overrides Function M13(<[In]> x() As Integer) As Integer() System.Console.WriteLine("Derived.M13") return Nothing End Function Public Overrides Function M4(Of S)(y as S, x() As S, z() as S) As S System.Console.WriteLine("Derived.M4") return Nothing End Function End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="Derived.M1" & vbCrLf & "Derived.M2" & vbCrLf & "Derived.M3" & vbCrLf & "Derived.M11" & vbCrLf & "Derived.M12" & vbCrLf & "Derived.M13" & vbCrLf & "Derived.M4") compilation.VerifyDiagnostics() Dim derived = DirectCast(compilation.Compilation, VisualBasicCompilation).GetTypeByMetadataName("Derived") Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M1").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M2").Parameters(0)) Assert.IsAssignableFrom(Of SourceSimpleParameterSymbol)(derived.GetMember(Of MethodSymbol)("M3").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M11").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M12").Parameters(0)) Assert.IsAssignableFrom(Of SourceComplexParameterSymbol)(derived.GetMember(Of MethodSymbol)("M13").Parameters(0)) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_15() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_16() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_17() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim verifier = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Base.P2_get" & vbCrLf & "Base.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Base.P2_get" & vbCrLf & "Base.P2_set") verifier.VerifyDiagnostics() AssertOverridingProperty(verifier.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_18() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1(int32 ) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_19() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32) IL_0009: callvirt instance void Base::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 []) IL_0017: callvirt instance void Base::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 []) .set instance void Base::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base Public Shared Sub Main() Dim x As Base = New Derived() x.Test() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_20() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends Base1 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base1::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base2 Public Shared Sub Main() Dim x As Base2 = New Derived() x.Test1() x.Test2() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base2.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_21() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base1::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base2::get_P1(int32) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base2::get_P1(int32 ) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Derived.P1_get 'Derived.P1_set 'Derived.P2_get 'Derived.P2_set 'Base1.P1_get 'Base1.P1_set 'Base1.P2_get 'Base1.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Base2.P1_get" & vbCrLf & "Base2.P1_set" & vbCrLf & "Base2.P2_get" & vbCrLf & "Base2.P2_set" & vbCrLf & "Derived.P1_get" & vbCrLf & "Derived.P1_set" & vbCrLf & "Derived.P2_get" & vbCrLf & "Derived.P2_set" ) compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_22() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base1 extends Base2 { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base2::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base1.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base1.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base1.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test1() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base1::get_P1(int32 ) IL_0009: callvirt instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base1::set_P2(int32 [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base1::get_P1(int32 ) .set instance void Base1::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base1::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base1::set_P2(int32 [], int32 ) } // end of property Base::P2 } // end of class Base .class public abstract auto ansi Base2 extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base2.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base2.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base2.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test2() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base2::set_P1(int32, int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base2::get_P2(int32 []) IL_0017: callvirt instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base2::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base2::set_P1(int32 , int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base2::get_P2(int32 []) .set instance void Base2::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Derived Inherits Base1 Public Shared Sub Main() Dim x As Base1 = New Derived() x.Test2() x.Test1() End Sub Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base2.P1_get 'Derived.P1_set 'Derived.P2_get 'Base2.P2_set 'Derived.P1_get 'Base1.P1_set 'Base1.P2_get 'Derived.P2_set Dim reference As MetadataReference = Nothing Using tempAssembly = SharedCompilationUtils.IlasmTempAssembly(ilSource) reference = MetadataReference.CreateFromImage(ReadFromFile(tempAssembly.Path)) End Using Dim compilation = CreateCompilationWithReferences(vbSource, {MscorlibRef, MsvbRef, reference}, TestOptions.ReleaseExe) compilation.AssertTheseDiagnostics(<expected> BC30643: Property 'Base1.P2(x As Integer())' is of an unsupported type. Public Overrides Property P2(x As Integer()) As Integer ~~ </expected>) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_23() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_24() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 []) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1() { .get instance int32 [] Base::get_P1() .set instance void Base::set_P1(int32 []) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2() { .get instance int32 Base::get_P2() .set instance void Base::set_P2(int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_25() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2() cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0002: ldarg.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1() IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_0010: ldarg.0 IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32 [] P1() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1() .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2() { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2() .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1() As Integer() Public Overrides Property P2() As Integer End Class ]]> </file> </compilation> Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:="") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_26() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_0009: callvirt instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) IL_001c: ret } // end of method Base::Test .property instance int32[] P1(int32) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[] Base::get_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) .set instance void Base::set_P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong), int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[]) } // end of property Base::P1 .property instance int32 P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub <WorkItem(819295, "DevDiv")> <Fact> Public Sub CustomModifiers_27() Dim ilSource = <![CDATA[ .class public abstract auto ansi Base extends [mscorlib]System.Object { .method family specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor .method public newslot specialname strict virtual instance int32 [] get_P1(int32 x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32[] V_0) IL_0000: ldstr "Base.P1_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldnull IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P1 .method public newslot specialname strict virtual instance void set_P1(int32 x, int32 [] 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P1_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P1 .method public newslot specialname strict virtual instance int32 get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x) cil managed { // Code size 16 (0x10) .maxstack 1 .locals init (int32 V_0) IL_0000: ldstr "Base.P2_get" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ldc.i4.0 IL_000b: stloc.0 IL_000c: br.s IL_000e IL_000e: ldloc.0 IL_000f: ret } // end of method Base::get_P2 .method public newslot specialname strict virtual instance void set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] x, int32 'value') cil managed { // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Base.P2_set" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } // end of method Base::set_P2 .method public instance void Test() cil managed { // Code size 29 (0x1d) .maxstack 8 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: ldarg.0 IL_0003: ldc.i4.0 IL_0004: callvirt instance int32 [] Base::get_P1(int32 ) IL_0009: callvirt instance void Base::set_P1(int32 , int32 []) IL_000e: ldarg.0 IL_000f: ldnull IL_0010: ldarg.0 IL_0011: ldnull IL_0012: callvirt instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) IL_0017: callvirt instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [], int32 ) IL_001c: ret } // end of method Base::Test .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) [] P1(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)) { .get instance int32 [] Base::get_P1(int32 ) .set instance void Base::set_P1(int32, int32[]) } // end of property Base::P1 .property instance int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) { .get instance int32 Base::get_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong) []) .set instance void Base::set_P2(int32 modopt([mscorlib]System.Runtime.CompilerServices.IsLong)[], int32) } // end of property Base::P2 } // end of class Base ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Module M Public Sub Main() Dim x As Base = New Derived1() x.Test() x = New Derived2() x.Test() End Sub End Module Class Derived1 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived1.P1_get") Return Nothing End Get Set(value As Integer()) System.Console.WriteLine("Derived1.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived1.P2_get") Return Nothing End Get Set(value As Integer) System.Console.WriteLine("Derived1.P2_set") End Set End Property End Class Class Derived2 Inherits Base Public Overrides Property P1(x As Integer) As Integer() Get System.Console.WriteLine("Derived2.P1_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P1_set") End Set End Property Public Overrides Property P2(x As Integer()) As Integer Get System.Console.WriteLine("Derived2.P2_get") Return Nothing End Get Set System.Console.WriteLine("Derived2.P2_set") End Set End Property End Class ]]> </file> </compilation> ' Output from native compiler: 'Base.P1_get 'Base.P1_set 'Base.P2_get 'Base.P2_set Dim compilation = CompileWithCustomILSource(vbSource, ilSource, emitOptions:=TestEmitters.RefEmitBug, options:=TestOptions.ReleaseExe, expectedOutput:= "Derived1.P1_get" & vbCrLf & "Derived1.P1_set" & vbCrLf & "Derived1.P2_get" & vbCrLf & "Derived1.P2_set" & vbCrLf & "Derived2.P1_get" & vbCrLf & "Derived2.P1_set" & vbCrLf & "Derived2.P2_get" & vbCrLf & "Derived2.P2_set") compilation.VerifyDiagnostics() AssertOverridingProperty(compilation.Compilation) End Sub Private Sub AssertOverridingProperty(compilation As Compilation) For Each namedType In compilation.SourceModule.GlobalNamespace.GetTypeMembers() If namedType.Name.StartsWith("Derived", StringComparison.OrdinalIgnoreCase) Then For Each member In namedType.GetMembers() If member.Kind = SymbolKind.Property Then Dim thisProperty = DirectCast(member, PropertySymbol) Dim overriddenProperty = thisProperty.OverriddenProperty Assert.True(overriddenProperty.TypeCustomModifiers.SequenceEqual(thisProperty.TypeCustomModifiers)) Assert.Equal(overriddenProperty.Type, thisProperty.Type) For i As Integer = 0 To thisProperty.ParameterCount - 1 Assert.True(overriddenProperty.Parameters(i).CustomModifiers.SequenceEqual(thisProperty.Parameters(i).CustomModifiers)) Assert.Equal(overriddenProperty.Parameters(i).Type, thisProperty.Parameters(i).Type) Assert.Equal(overriddenProperty.Parameters(i).HasByRefBeforeCustomModifiers, thisProperty.Parameters(i).HasByRefBeforeCustomModifiers) Next End If Next End If Next End Sub <Fact(), WorkItem(830352, "DevDiv")> Public Sub Bug830352() Dim code = <compilation> <file name="a.vb"> Public Class Base Overridable Sub Test(Of T As Structure)(x As T?) End Sub End Class Class Derived Inherits Base Public Overrides Sub Test(Of T As Structure)(x As T?) MyBase.Test(x) End Sub End Class </file> </compilation> Dim comp = CreateCompilationWithMscorlib(code, TestOptions.ReleaseDll) CompileAndVerify(comp).VerifyDiagnostics() End Sub <Fact(), WorkItem(837884, "DevDiv")> Public Sub Bug837884() Dim code1 = <compilation> <file name="a.vb"> Public Class Cls Public Overridable Property r() Get Return 1 End Get Friend Set(ByVal Value) End Set End Property End Class </file> </compilation> Dim comp1 = CreateCompilationWithMscorlib(code1, TestOptions.ReleaseDll) CompileAndVerify(comp1).VerifyDiagnostics() Dim code2 = <compilation> <file name="a.vb"> Class cls2 Inherits Cls Public Overrides Property r() As Object Get Return 1 End Get Friend Set(ByVal Value As Object) End Set End Property End Class </file> </compilation> Dim comp2 = CreateCompilationWithMscorlibAndReferences(code2, {New VisualBasicCompilationReference(comp1)}, TestOptions.ReleaseDll) Dim expected = <expected> BC31417: 'Friend Overrides Property Set r(Value As Object)' cannot override 'Friend Overridable Property Set r(Value As Object)' because it is not accessible in this context. Friend Set(ByVal Value As Object) ~~~ </expected> AssertTheseDeclarationDiagnostics(comp2, expected) Dim comp3 = CreateCompilationWithMscorlibAndReferences(code2, {comp1.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDeclarationDiagnostics(comp3, expected) End Sub <WorkItem(1067044, "DevDiv")> <Fact> Sub Bug1067044() Dim il = <![CDATA[ .class public abstract auto ansi beforefieldinit C1 extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance int32* M1() cil managed { } // end of method C1::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C1::.ctor } // end of class C1 .class public abstract auto ansi beforefieldinit C2 extends C1 { .method public hidebysig virtual instance int32* M1() cil managed { // Code size 8 (0x8) .maxstack 1 .locals init (int32* V_0) IL_0000: nop IL_0001: ldc.i4.0 IL_0002: conv.u IL_0003: stloc.0 IL_0004: br.s IL_0006 IL_0006: ldloc.0 IL_0007: ret } // end of method C2::M1 .method public hidebysig newslot abstract virtual instance void M2() cil managed { } // end of method C2::M2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void C1::.ctor() IL_0006: nop IL_0007: ret } // end of method C2::.ctor } // end of class C2 ]]> Dim source = <compilation> <file name="a.vb"> Public Class C3 Inherits C2 Public Overrides Sub M2() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(source, il.Value, options:=TestOptions.DebugDll) CompileAndVerify(compilation) End Sub End Class End Namespace
DavidKarlas/roslyn
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/OverridesTests.vb
Visual Basic
apache-2.0
226,458
Public Class $safeitemname$ End Class
jiailiuyan/MXA-Game-Studio
src/ItemTemplates/Sprite Font v5.0-vb/Class.vb
Visual Basic
mit
42
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.IO Imports System.Reflection Imports System.Runtime.InteropServices Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class AttributeTests Inherits BasicTestBase #Region "Function Tests" <WorkItem(530310, "DevDiv")> <Fact> Public Sub PEParameterSymbolParamArrayAttribute() Dim source1 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }]]>.Value Dim reference1 = CompileIL(source1, appendDefaultHeader:=False) Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Class C Shared Sub Main(args As String()) A.M(1, 2, 3) A.M(1, 2, 3, 4) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndReferences(source2, {reference1}) Dim method = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of PEMethodSymbol)("M") Dim yParam = method.Parameters.Item(1) Assert.Equal(0, yParam.GetAttributes().Length) Assert.True(yParam.IsParamArray) CompilationUtils.AssertNoDiagnostics(comp) End Sub ''' <summary> ''' This function is the same as PEParameterSymbolParamArray ''' except that we check attributes first (to check for race ''' conditions). ''' </summary> <WorkItem(530310, "DevDiv")> <Fact> Public Sub PEParameterSymbolParamArrayAttribute2() Dim source1 = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly '<<GeneratedFileName>>' { } .class public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public static void M(int32 x, int32[] y) { .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) ret } }]]>.Value Dim reference1 = CompileIL(source1, appendDefaultHeader:=False) Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Class C Shared Sub Main(args As String()) A.M(1, 2, 3) A.M(1, 2, 3, 4) End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndReferences(source2, {reference1}) Dim method = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A").GetMember(Of PEMethodSymbol)("M") Dim yParam = method.Parameters.Item(1) Assert.True(yParam.IsParamArray) Assert.Equal(0, yParam.GetAttributes().Length) CompilationUtils.AssertNoDiagnostics(comp) End Sub <Fact> Public Sub BindingScope_Parameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class A Inherits System.Attribute Public Sub New(value As Integer) End Sub End Class Class C Const Value As Integer = 0 Sub method1(<A(Value)> x As Integer) End Sub End Class ]]> </file> </compilation> CompileAndVerify(source) End Sub <Fact> Public Sub TestAssemblyAttributes() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <assembly: InternalsVisibleTo("Roslyn.Compilers.UnitTests")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp.UnitTests")> <assembly: InternalsVisibleTo("Roslyn.Compilers.CSharp.Test.Utilities")> <assembly: InternalsVisibleTo("Roslyn.Compilers.VisualBasic")> ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim assembly = m.ContainingSymbol Dim compilerServicesNS = GetSystemRuntimeCompilerServicesNamespace(m) Dim internalsVisibleToAttr As NamedTypeSymbol = compilerServicesNS.GetTypeMembers("InternalsVisibleToAttribute").First() Dim attrs = assembly.GetAttributes(internalsVisibleToAttr) Assert.Equal(5, attrs.Count) attrs(0).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.UnitTests") attrs(1).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp") attrs(2).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.UnitTests") attrs(3).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.CSharp.Test.Utilities") attrs(4).VerifyValue(0, TypedConstantKind.Primitive, "Roslyn.Compilers.VisualBasic") End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub Private Function GetSystemRuntimeCompilerServicesNamespace(m As ModuleSymbol) As NamespaceSymbol Dim compilation = m.DeclaringCompilation Dim globalNS = If(compilation Is Nothing, m.ContainingAssembly.CorLibrary.GlobalNamespace, compilation.GlobalNamespace) Return globalNS. GetMember(Of NamespaceSymbol)("System"). GetMember(Of NamespaceSymbol)("Runtime"). GetMember(Of NamespaceSymbol)("CompilerServices") End Function <Fact> Public Sub TestAssemblyAttributesReflection() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="attr.vb"><![CDATA[ Imports System.Reflection Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices ' These are not pseduo attributes, but encoded as bits in metadata <assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)> <assembly: AssemblyCultureAttribute("")> <assembly: AssemblyDelaySign(true)> <assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)> <assembly: AssemblyKeyFile("MyKey.snk")> <assembly: AssemblyKeyName("Key Name")> <assembly: AssemblyVersion("1.2.*")> <assembly: AssemblyFileVersionAttribute("4.3.2.100")> ]]> </file> </compilation>) Dim attrs = compilation.Assembly.GetAttributes() Assert.Equal(8, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyAlgorithmIdAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(0, a.CommonNamedArguments.Length) Assert.Equal(TypedConstantKind.Enum, a.CommonConstructorArguments(0).Kind) Assert.Equal("System.Configuration.Assemblies.AssemblyHashAlgorithm", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(Configuration.Assemblies.AssemblyHashAlgorithm.MD5, CType(a.CommonConstructorArguments(0).Value, Configuration.Assemblies.AssemblyHashAlgorithm)) Case "AssemblyCultureAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(0, a.CommonNamedArguments.Length) Case "AssemblyDelaySignAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("Boolean", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(True, a.CommonConstructorArguments(0).Value) Case "AssemblyFlagsAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Enum, a.CommonConstructorArguments(0).Kind) Assert.Equal("System.Reflection.AssemblyNameFlags", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal(AssemblyNameFlags.Retargetable, CType(a.CommonConstructorArguments(0).Value, AssemblyNameFlags)) Case "AssemblyKeyFileAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("MyKey.snk", a.CommonConstructorArguments(0).Value) Case "AssemblyKeyNameAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("Key Name", a.CommonConstructorArguments(0).Value) Case "AssemblyVersionAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("1.2.*", a.CommonConstructorArguments(0).Value) Case "AssemblyFileVersionAttribute" Assert.Equal(1, a.CommonConstructorArguments.Length) Assert.Equal(TypedConstantKind.Primitive, a.CommonConstructorArguments(0).Kind) Assert.Equal("String", a.CommonConstructorArguments(0).Type.ToDisplayString) Assert.Equal("4.3.2.100", a.CommonConstructorArguments(0).Value) Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) End Select Next End Sub ' Verify that resolving an attribute defined within a class on a class does not cause infinite recursion <Fact> Public Sub TestAttributesOnClassDefinedInClass() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.CompilerServices <A.X()> Public Class A <AttributeUsage(AttributeTargets.All, allowMultiple:=true)> Public Class XAttribute Inherits Attribute End Class End Class]]> </file> </compilation>) Dim attrs = compilation.SourceModule.GlobalNamespace.GetMember("A").GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("A.XAttribute", attrs(0).AttributeClass.ToDisplayString) End Sub <WorkItem(540506, "DevDiv")> <Fact> Public Sub TestAttributesOnClassWithConstantDefinedInClass() Dim compilation = CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ <Attr(Foo.p)> Class Foo Friend Const p As Object = 2 + 2 End Class Friend Class AttrAttribute Inherits Attribute End Class ]]> </file> </compilation>) Dim attrs = compilation.SourceModule.GlobalNamespace.GetMember("Foo").GetAttributes() Assert.Equal(1, attrs.Length) attrs(0).VerifyValue(0, TypedConstantKind.Primitive, 4) End Sub <WorkItem(540407, "DevDiv")> <Fact> Public Sub TestAttributesOnProperty() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Interface I <A> Property AP(<A()>a As Integer) As <A>Integer End Interface Public Class C <A> Public Property AP As <A>Integer <A> Public Property P(<A> a As Integer) As <A>Integer <A> Get Return 0 End Get <A> Set(<A>value As Integer) End Set End Property End Class ]]></file> </compilation> Dim attributeValidator = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) Dim c = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) ' auto-property in interface Dim ap = i.GetMember("AP") Assert.Equal(1, ap.GetAttributes().Length) Dim get_AP = DirectCast(i.GetMember("get_AP"), MethodSymbol) Assert.Equal(0, get_AP.GetAttributes().Length) Assert.Equal(1, get_AP.GetReturnTypeAttributes().Length) Assert.Equal(1, get_AP.Parameters(0).GetAttributes().Length) Dim set_AP = DirectCast(i.GetMember("set_AP"), MethodSymbol) Assert.Equal(0, set_AP.GetAttributes().Length) Assert.Equal(0, set_AP.GetReturnTypeAttributes().Length) Assert.Equal(1, set_AP.Parameters(0).GetAttributes().Length) Assert.Equal(0, set_AP.Parameters(1).GetAttributes().Length) ' auto-property on class ap = c.GetMember("AP") Assert.Equal(1, ap.GetAttributes().Length) get_AP = DirectCast(c.GetMember("get_AP"), MethodSymbol) If isFromSource Then Assert.Equal(0, get_AP.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(get_AP.GetAttributes())) End If Assert.Equal(1, get_AP.GetReturnTypeAttributes().Length) set_AP = DirectCast(c.GetMember("set_AP"), MethodSymbol) If isFromSource Then Assert.Equal(0, get_AP.GetAttributes().Length) Else AssertEx.Equal({"CompilerGeneratedAttribute"}, GetAttributeNames(set_AP.GetAttributes())) End If Assert.Equal(0, set_AP.GetReturnTypeAttributes().Length) Assert.Equal(0, set_AP.Parameters(0).GetAttributes().Length) ' property Dim p = c.GetMember("P") Assert.Equal(1, p.GetAttributes().Length) Dim get_P = DirectCast(c.GetMember("get_P"), MethodSymbol) Assert.Equal(1, get_P.GetAttributes().Length) Assert.Equal(1, get_P.GetReturnTypeAttributes().Length) Assert.Equal(1, get_P.Parameters(0).GetAttributes().Length) Dim set_P = DirectCast(c.GetMember("set_P"), MethodSymbol) Assert.Equal(1, set_P.GetAttributes().Length) Assert.Equal(0, set_P.GetReturnTypeAttributes().Length) Assert.Equal(1, set_P.Parameters(0).GetAttributes().Length) Assert.Equal(1, set_P.Parameters(1).GetAttributes().Length) End Sub CompileAndVerify(source, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False)) End Sub <WorkItem(540407, "DevDiv")> <Fact> Public Sub TestAttributesOnPropertyReturnType() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Class A Inherits System.Attribute End Class Public Class B Inherits System.Attribute End Class Public Interface I Property Auto As <A> Integer ReadOnly Property AutoRO As <A> Integer WriteOnly Property AutoWO As <A> Integer ' warning End Interface Public Class C Property Auto As <A> Integer ReadOnly Property ROA As <A> Integer Get Return 0 End Get End Property WriteOnly Property WOA As <A> Integer ' warning Set(value As Integer) End Set End Property Property A As <A> Integer Get Return 0 End Get Set(value As Integer) End Set End Property Property AB As <A> Integer Get Return 0 End Get Set(<B()> value As Integer) End Set End Property End Class ]]></file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) Dim c = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) ' auto-property in interface Dim auto = DirectCast(i.GetMember("Auto"), PropertySymbol) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) Dim autoRO = DirectCast(i.GetMember("AutoRO"), PropertySymbol) Assert.Equal(1, autoRO.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(autoRO.SetMethod) Dim autoWO = DirectCast(i.GetMember("AutoWO"), PropertySymbol) Assert.Null(autoWO.GetMethod) Assert.Equal(0, autoWO.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) ' auto-property in class auto = DirectCast(c.GetMember("Auto"), PropertySymbol) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) ' custom property in class Dim roa = DirectCast(c.GetMember("ROA"), PropertySymbol) Assert.Equal(1, roa.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(roa.SetMethod) Dim woa = DirectCast(c.GetMember("WOA"), PropertySymbol) Assert.Null(woa.GetMethod) Assert.Equal(0, woa.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, woa.SetMethod.Parameters(0).GetAttributes().Length) Dim a = DirectCast(c.GetMember("A"), PropertySymbol) Assert.Equal(1, a.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, a.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(0, a.SetMethod.Parameters(0).GetAttributes().Length) Dim ab = DirectCast(c.GetMember("AB"), PropertySymbol) Assert.Equal(1, ab.GetMethod.GetReturnTypeAttributes().Length) Assert.Equal("A", ab.GetMethod.GetReturnTypeAttributes()(0).AttributeClass.Name) Assert.Equal(0, ab.SetMethod.GetReturnTypeAttributes().Length) Assert.Equal(1, ab.SetMethod.Parameters(0).GetAttributes().Length) Assert.Equal("B", ab.SetMethod.Parameters(0).GetAttributes()(0).AttributeClass.Name) End Sub Dim verifier = CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) CompilationUtils.AssertTheseDiagnostics(verifier.Compilation, <errors><![CDATA[ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property AutoWO As <A> Integer ' warning ~ BC42364: Attributes applied on a return type of a WriteOnly Property have no effect. WriteOnly Property WOA As <A> Integer ' warning ~ ]]></errors>) End Sub <WorkItem(546779, "DevDiv")> <Fact> Public Sub TestAttributesOnPropertyReturnType_MarshalAs() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Public Interface I Property Auto As <MarshalAs(UnmanagedType.I4)> Integer End Interface ]]></file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim i = DirectCast(m.GlobalNamespace.GetMember("I"), NamedTypeSymbol) ' auto-property in interface Dim auto = DirectCast(i.GetMember("Auto"), PropertySymbol) Assert.Equal(UnmanagedType.I4, auto.GetMethod.ReturnTypeMarshallingInformation.UnmanagedType) Assert.Equal(1, auto.GetMethod.GetReturnTypeAttributes().Length) Assert.Null(auto.SetMethod.ReturnTypeMarshallingInformation) Assert.Equal(UnmanagedType.I4, auto.SetMethod.Parameters(0).MarshallingInformation.UnmanagedType) Assert.Equal(0, auto.SetMethod.Parameters(0).GetAttributes().Length) End Sub ' TODO (tomat): implement reading from PE: symbolValidator:=attributeValidator CompileAndVerify(source, sourceSymbolValidator:=attributeValidator) End Sub <WorkItem(540433, "DevDiv")> <Fact> Public Sub TestAttributesOnPropertyAndGetSet() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AObject(GetType(Object), O:=A.obj)> Public Class A Public Const obj As Object = Nothing Public ReadOnly Property RProp As String <AObject(New Object() {GetType(String)})> Get Return Nothing End Get End Property <AObject(New Object() {1, "two", GetType(String), 3.1415926})> Public WriteOnly Property WProp <AObject(New Object() {New Object() {GetType(String)}})> Set(value) End Set End Property End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.MDTestAttributeDefLib.AsImmutableOrNull())}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = type.GetAttributes() Assert.Equal("AObjectAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(Object)) attrs(0).VerifyValue(Of Object)(0, "O", TypedConstantKind.Primitive, Nothing) Dim prop = type.GetMember(Of PropertySymbol)("RProp") attrs = prop.GetMethod.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Array, {GetType(String)}) prop = type.GetMember(Of PropertySymbol)("WProp") attrs = prop.GetAttributes() attrs(0).VerifyValue(Of Object())(0, TypedConstantKind.Array, {1, "two", GetType(String), 3.1415926}) attrs = prop.SetMethod.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Array, {New Object() {GetType(String)}}) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesOnPropertyParameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Class X Public Property P(<A>a As Integer) As <A>Integer Get Return 0 End Get Set(<A>value As Integer) End Set End Property End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim type = DirectCast(m.GlobalNamespace.GetMember("X"), NamedTypeSymbol) Dim getter = DirectCast(type.GetMember("get_P"), MethodSymbol) Dim setter = DirectCast(type.GetMember("set_P"), MethodSymbol) ' getter Assert.Equal(1, getter.Parameters.Length) Assert.Equal(1, getter.Parameters(0).GetAttributes().Length) Assert.Equal(1, getter.GetReturnTypeAttributes().Length) ' setter Assert.Equal(2, setter.Parameters.Length) Assert.Equal(1, setter.Parameters(0).GetAttributes().Length) Assert.Equal(1, setter.Parameters(1).GetAttributes().Length) End Sub CompileAndVerify(source, symbolValidator:=attributeValidator, sourceSymbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesOnEnumField() Dim source = <compilation> <file name="attr.vb"><![CDATA[ Option Strict On Imports System Imports system.Collections.Generic Imports System.Reflection Imports CustomAttribute Imports AN = CustomAttribute.AttrName ' Use AttrName without Attribute suffix <Assembly: AN(UShortField:=4321)> <Assembly: AN(UShortField:=1234)> <Module: AttrName(TypeField:=GetType(System.IO.FileStream))> Namespace AttributeTest Public Interface IFoo Class NestedClass ' enum as object <AllInheritMultiple(System.IO.FileMode.Open, BindingFlags.DeclaredOnly Or BindingFlags.Public, UIntField:=123 * Field)> Public Const Field As UInteger = 10 End Class <AllInheritMultiple(New Char() {"q"c, "c"c}, "")> <AllInheritMultiple()> Enum NestedEnum zero one = 1 <AllInheritMultiple(Nothing, 256, 0.0F, -1, AryField:=New ULong() {0, 1, 12345657})> <AllInheritMultipleAttribute(GetType(Dictionary(Of String, Integer)), 255 + NestedClass.Field, -0.0001F, 3 - CShort(NestedEnum.oneagain))> three = 3 oneagain = one End Enum End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Function(isFromSource As Boolean) _ Sub(m As ModuleSymbol) Dim attrs = m.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal("CustomAttribute.AttrNameAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(0, "TypeField", TypedConstantKind.Type, GetType(FileStream)) Dim assembly = m.ContainingSymbol attrs = assembly.GetAttributes() If isFromSource Then Assert.Equal(2, attrs.Length) Assert.Equal("CustomAttribute.AttrName", attrs(0).AttributeClass.ToDisplayString) attrs(1).VerifyValue(Of UShort)(0, "UShortField", TypedConstantKind.Primitive, 1234) Else Assert.Equal(5, attrs.Length) ' 3 synthesized assembly attributes Assert.Equal("CustomAttribute.AttrName", attrs(3).AttributeClass.ToDisplayString) attrs(4).VerifyValue(Of UShort)(0, "UShortField", TypedConstantKind.Primitive, 1234) End If Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim top = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim type = top.GetMember(Of NamedTypeSymbol)("NestedClass") Dim field = type.GetMember(Of FieldSymbol)("Field") attrs = field.GetAttributes() Assert.Equal("CustomAttribute.AllInheritMultipleAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(0, TypedConstantKind.Enum, CInt(FileMode.Open)) attrs(0).VerifyValue(1, TypedConstantKind.Enum, CInt(BindingFlags.DeclaredOnly Or BindingFlags.Public)) attrs(0).VerifyValue(0, "UIntField", TypedConstantKind.Primitive, 1230) Dim nenum = top.GetMember(Of TypeSymbol)("NestedEnum") attrs = nenum.GetAttributes() Assert.Equal(2, attrs.Length) attrs(0).VerifyValue(0, TypedConstantKind.Array, {"q"c, "c"c}) attrs = nenum.GetMember("three").GetAttributes() Assert.Equal(2, attrs.Length) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, Nothing) attrs(0).VerifyValue(Of Long)(1, TypedConstantKind.Primitive, 256) attrs(0).VerifyValue(Of Single)(2, TypedConstantKind.Primitive, 0) attrs(0).VerifyValue(Of Short)(3, TypedConstantKind.Primitive, -1) attrs(0).VerifyValue(Of ULong())(0, "AryField", TypedConstantKind.Array, New ULong() {0, 1, 12345657}) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(Dictionary(Of String, Integer))) attrs(1).VerifyValue(Of Long)(1, TypedConstantKind.Primitive, 265) attrs(1).VerifyValue(Of Single)(2, TypedConstantKind.Primitive, -0.0001F) attrs(1).VerifyValue(Of Short)(3, TypedConstantKind.Primitive, 2) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator(True), symbolValidator:=attributeValidator(False)) End Sub <Fact> Public Sub TestAttributesOnDelegate() Dim source = <compilation> <file name="TestAttributesOnDelegate.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest Public Interface IFoo <AllInheritMultiple(New Object() {0, "", Nothing}, 255, -127 - 1, AryProp:=New Object() {New Object() {"", GetType(IList(Of String))}})> Delegate Sub NestedSubDele(<AllInheritMultiple()> <Derived(GetType(String(,,)))> p As String) End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim dele = DirectCast(type.GetTypeMember("NestedSubDele"), NamedTypeSymbol) Dim attrs = dele.GetAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Array, New Object() {0, "", Nothing}) attrs(0).VerifyValue(Of Byte)(1, TypedConstantKind.Primitive, 255) attrs(0).VerifyValue(Of SByte)(2, TypedConstantKind.Primitive, -128) attrs(0).VerifyValue(Of Object())(0, "AryProp", TypedConstantKind.Array, New Object() {New Object() {"", GetType(IList(Of String))}}) Dim mem = dele.GetMember(Of MethodSymbol)("Invoke") ' no attributes on the method: Assert.Equal(0, mem.GetAttributes().Length) ' attributes on parameters: attrs = mem.Parameters(0).GetAttributes() Assert.Equal(2, attrs.Length) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Type, GetType(String(,,))) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(540600, "DevDiv")> <Fact> Public Sub TestAttributesUseBaseAttributeField() Dim source = <compilation> <file name="TestAttributesUseBaseAttributeField.vb"><![CDATA[ Imports System Namespace AttributeTest Public Interface IFoo <CustomAttribute.Derived(New Object() {1, Nothing, "Hi"}, ObjectField:=2)> Function F(p As Integer) As Integer End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim attrs = type.GetMember(Of MethodSymbol)("F").GetAttributes() Assert.Equal("CustomAttribute.DerivedAttribute", attrs(0).AttributeClass.ToDisplayString) attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Array, New Object() {1, Nothing, "Hi"}) attrs(0).VerifyValue(Of Object)(0, "ObjectField", TypedConstantKind.Primitive, 2) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact(), WorkItem(529421, "DevDiv")> Public Sub TestAttributesWithParamArrayInCtor() Dim source = <compilation> <file name="TestAttributesWithParamArrayInCtor.vb"><![CDATA[ Imports System Imports CustomAttribute Namespace AttributeTest <AllInheritMultiple(New Char() {" "c, Nothing}, "")> Public Interface IFoo End Interface End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim sourceAttributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim attrs = type.GetAttributes() attrs(0).VerifyValue(Of Char())(0, TypedConstantKind.Array, New Char() {" "c, Nothing}) attrs(0).VerifyValue(Of String())(1, TypedConstantKind.Array, New String() {""}) Dim attrCtor = attrs(0).AttributeConstructor Debug.Assert(attrCtor.Parameters.Last.IsParamArray) End Sub Dim mdAttributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim type = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim attrs = type.GetAttributes() attrs(0).VerifyValue(Of Char())(0, TypedConstantKind.Array, New Char() {" "c, Nothing}) attrs(0).VerifyValue(Of String())(1, TypedConstantKind.Array, New String() {""}) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=sourceAttributeValidator, symbolValidator:=mdAttributeValidator) End Sub <WorkItem(540605, "DevDiv")> <Fact> Public Sub TestAttributesOnReturnType() Dim source = <compilation> <file name="TestAttributesOnReturnType.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest Class XAttribute inherits Attribute Sub New(s as string) End Sub End Class Public Interface IFoo Function F1(i as integer) as <X("f1 return type")> string Property P1 as <X("p1 return type")> string End Interface Class C1 Property P1 as <X("p1 return type")> string ReadOnly Property P2 as <X("p2 return type")> string Get return nothing End Get End Property Function F2(i as integer) As <X("f2 returns an integer")> integer return 0 end function End Class End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01.AsImmutableOrNull())}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim iFoo = DirectCast(ns.GetMember("IFoo"), NamedTypeSymbol) Dim f1 = DirectCast(iFoo.GetMember("F1"), MethodSymbol) Dim attrs = f1.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "f1 return type") Dim p1 = DirectCast(iFoo.GetMember("P1"), PropertySymbol) attrs = p1.GetMethod.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "p1 return type") Dim c1 = DirectCast(ns.GetMember("C1"), NamedTypeSymbol) Dim p2 = DirectCast(c1.GetMember("P2"), PropertySymbol) attrs = p2.GetMethod.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "p2 return type") Dim f2 = DirectCast(c1.GetMember("F2"), MethodSymbol) attrs = f2.GetReturnTypeAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, "f2 returns an integer") End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestAttributesUsageCasing() Dim source = <compilation> <file name="TestAttributesOnReturnType.vb"><![CDATA[ Imports System Imports System.Collections.Generic Imports CustomAttribute Namespace AttributeTest <ATTributeUSageATTribute(AttributeTargets.ReturnValue, ALLowMulTiplE:=True, InHeRIteD:=false)> Class XAttribute Inherits Attribute Sub New() End Sub End Class End Namespace ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences( source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}, TestOptions.ReleaseDll) Dim attributeValidator = Sub(m As ModuleSymbol) Dim ns = DirectCast(m.GlobalNamespace.GetMember("AttributeTest"), NamespaceSymbol) Dim xAttributeClass = DirectCast(ns.GetMember("XAttribute"), NamedTypeSymbol) Dim attributeUsage = xAttributeClass.GetAttributeUsageInfo() Assert.Equal(AttributeTargets.ReturnValue, attributeUsage.ValidTargets) Assert.Equal(True, attributeUsage.AllowMultiple) Assert.Equal(False, attributeUsage.Inherited) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(540940, "DevDiv")> <Fact> Public Sub TestAttributeWithParamArray() Dim source = <compilation> <file name="TestAttributeWithParamArray.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(ParamArray x As Integer()) End Sub End Class <A> Module M Sub Main() End Sub End Module ]]></file> </compilation> CompileAndVerify(source) End Sub <WorkItem(528469, "DevDiv")> <Fact()> Public Sub TestAttributeWithAttributeTargets() Dim source = <compilation> <file name="TestAttributeWithParamArray.vb"><![CDATA[ Imports System <System.AttributeUsage(AttributeTargets.All)> _ Class ZAttribute Inherits Attribute End Class <Z()> _ Class scen1 End Class Module M1 Sub foo() <Z()> _ Static x1 As Object End Sub End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) CompileAndVerify(compilation) End Sub <WorkItem(541277, "DevDiv")> <Fact> Public Sub TestAttributeEmitObjectValue() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System <AttributeUsageAttribute(AttributeTargets.All, AllowMultiple:=True)> Class A Inherits Attribute Public Property X As Object Public Sub New() End Sub Public Sub New(o As Object) End Sub End Class <A(1)> <A(New String() {"a", "b"})> <A(X:=1), A(X:=New String() {"a", "b"})> Class B Shared Sub Main() Dim b As New B() Dim a As A = b.GetType().GetCustomAttributes(False)(0) Console.WriteLine(a.X) End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim attrs = bClass.GetAttributes() attrs(0).VerifyValue(Of Object)(0, TypedConstantKind.Primitive, 1) attrs(1).VerifyValue(Of Object)(0, TypedConstantKind.Array, New String() {"a", "b"}) attrs(2).VerifyValue(Of Object)(0, "X", TypedConstantKind.Primitive, 1) attrs(3).VerifyValue(Of Object)(0, "X", TypedConstantKind.Array, New String() {"a", "b"}) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541278, "DevDiv")> <Fact> Public Sub TestAttributeEmitGenericEnumValue() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(x As Object) Y = x End Sub Public Property Y As Object End Class Class B(Of T) Class D End Class Enum E A = &HABCDEF End Enum End Class <A(B(Of Integer).E.A)> Class C End Class Module m1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim cClass = DirectCast(m.GlobalNamespace.GetMember("C"), NamedTypeSymbol) Dim attrs = cClass.GetAttributes() Dim tc = attrs(0).CommonConstructorArguments(0) Assert.Equal(tc.Kind, TypedConstantKind.Enum) Assert.Equal(CType(tc.Value, Int32), &HABCDEF) Assert.Equal(tc.Type.ToDisplayString, "B(Of Integer).E") End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(546380, "DevDiv")> <Fact()> Public Sub TestAttributeEmitOpenGeneric() Dim source = <compilation> <file name="TestAttributeEmitObjectValue.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(x As Object) Y = x End Sub Public Property Y As Object End Class <A(GetType(B(Of)))> Class B(Of T) End Class Module m1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B"), NamedTypeSymbol) Dim attrs = bClass.GetAttributes() attrs(0).VerifyValue(0, TypedConstantKind.Type, bClass.ConstructUnboundGenericType()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541278, "DevDiv")> <Fact> Public Sub TestAttributeToString() Dim source = <compilation> <file name="TestAttributeToString.vb"><![CDATA[ Imports System <AttributeUsageAttribute(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=True)> Class A Inherits Attribute Public Property X As Object Public Property T As Type Public Sub New() End Sub Public Sub New(ByVal o As Object) End Sub Public Sub New(ByVal y As Y) End Sub End Class Public Enum Y One = 1 Two = 2 Three = 3 End Enum <A()> Class B1 Shared Sub Main() End Sub End Class <A(1)> Class B2 End Class <A(New String() {"a", "b"})> Class B3 End Class <A(X:=1)> Class B4 End Class <A(T:=GetType(String))> Class B5 End Class <A(1, X:=1, T:=GetType(String))> Class B6 End Class <A(Y.Three)> Class B7 End Class <A(DirectCast(5, Y))> Class B8 End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.Class Or System.AttributeTargets.Struct, AllowMultiple:=True)", attrs(0).ToString()) Dim bClass = DirectCast(m.GlobalNamespace.GetMember("B1"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B2"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(1)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B3"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A({""a"", ""b""})", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B4"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(X:=1)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B5"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(T:=GetType(String))", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B6"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(1, X:=1, T:=GetType(String))", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B7"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(Y.Three)", attrs(0).ToString()) bClass = DirectCast(m.GlobalNamespace.GetMember("B8"), NamedTypeSymbol) attrs = bClass.GetAttributes() Assert.Equal("A(5)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(541687, "DevDiv")> <Fact> Public Sub Bug_8524_NullAttributeArrayArument() Dim source = <compilation> <file name="Bug_8524_NullAttributeArrayArument.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Property X As Object End Class <A(X:=CStr(Nothing))> Class B Shared Sub Main() Dim b As New B() Dim a As A = b.GetType().GetCustomAttributes(False)(0) Console.Write(a.X Is Nothing) End Sub End Class ]]> </file> </compilation> CompileAndVerify(source, expectedOutput:="True") End Sub <WorkItem(541964, "DevDiv")> <Fact> Public Sub TestApplyNamedArgumentTwice() Dim source = <compilation> <file name="TestApplyNamedArgumentTwice.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=False, AllowMultiple:=True), A, A> Class A Inherits Attribute End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple:=False, AllowMultiple:=True)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <Fact> Public Sub TestApplyNamedArgumentCasing() Dim source = <compilation> <file name="TestApplyNamedArgumentTwice.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, ALLOWMULTIPLE:=True), A, A> Class A Inherits Attribute End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) Dim attributeValidator = Sub(m As ModuleSymbol) Dim aClass = DirectCast(m.GlobalNamespace.GetMember("A"), NamedTypeSymbol) Dim attrs = aClass.GetAttributes() Assert.Equal("System.AttributeUsageAttribute(System.AttributeTargets.All, AllowMultiple:=True)", attrs(0).ToString()) End Sub CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub <WorkItem(542123, "DevDiv")> <Fact> Public Sub TestApplyNestedDerivedAttribute() Dim source = <compilation> <file name="TestApplyNestedDerivedAttribute.vb"><![CDATA[ Imports System <First.Second.Third()> Class First : Inherits Attribute Class Second : Inherits First End Class Class Third : Inherits Second End Class End Class Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics() End Sub <WorkItem(542269, "DevDiv")> <Fact> Public Sub TestApplyNestedDerivedAttributeOnTypeAndItsMember() Dim source = <compilation> <file name="TestApplyNestedDerivedAttributeOnTypeAndItsMember.vb"><![CDATA[ Imports System Public Class First : Inherits Attribute <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Method)> Friend Class Second Inherits First End Class End Class <First.Second()> Module Module1 <First.Second()> Function ToString(x As Integer, y As Integer) As String Return Nothing End Function Public Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics() End Sub <Fact> Public Sub AttributeTargets_Method() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Method)> Class Attr Inherits Attribute End Class Public Class C <Attr()> Custom Event EvntWithAccessors As Action(Of Integer) <Attr()> AddHandler(value As Action(Of Integer)) End AddHandler <Attr()> RemoveHandler(value As Action(Of Integer)) End RemoveHandler <Attr()> RaiseEvent(obj As Integer) End RaiseEvent End Event <Attr()> Property PropertyWithAccessors As Integer <Attr()> Get Return 0 End Get <Attr()> Set(value As Integer) End Set End Property <Attr()> Shared Sub Sub1() End Sub <Attr()> Function Ftn2() As Integer Return 1 End Function <Attr()> Declare Function DeclareFtn Lib "bar" () As Integer <Attr()> Declare Sub DeclareSub Lib "bar" () <Attr()> Shared Operator -(a As C, b As C) As Integer Return 0 End Operator <Attr()> Shared Narrowing Operator CType(a As C) As Integer Return 0 End Operator <Attr()> Public Event Evnt As Action(Of Integer) <Attr()> Public Field As Integer <Attr()> Public WithEvents WE As NestedType <Attr()> Class NestedType End Class <Attr()> Interface Iface End Interface End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Evnt"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Field"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "WE"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "NestedType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Iface")) End Sub <Fact> Public Sub AttributeTargets_Field() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.Field)> Class Attr Inherits Attribute End Class Public Class C <Attr()> Custom Event EvntWithAccessors As Action(Of Integer) <Attr()> AddHandler(value As Action(Of Integer)) End AddHandler <Attr()> RemoveHandler(value As Action(Of Integer)) End RemoveHandler <Attr()> RaiseEvent(obj As Integer) End RaiseEvent End Event <Attr()> Property PropertyWithAccessors As Integer <Attr()> Get Return 0 End Get <Attr()> Set(value As Integer) End Set End Property <Attr()> Shared Sub Sub1() End Sub <Attr()> Function Ftn2() As Integer Return 1 End Function <Attr()> Declare Function DeclareFtn Lib "bar" () As Integer <Attr()> Declare Sub DeclareSub Lib "bar" () <Attr()> Shared Operator -(a As C, b As C) As Integer Return 0 End Operator <Attr()> Shared Narrowing Operator CType(a As C) As Integer Return 0 End Operator <Attr()> Public Event Evnt As Action(Of Integer) <Attr()> Public Field As Integer <Attr()> Public WithEvents WE As NestedType <Attr()> Class NestedType End Class <Attr()> Interface Iface End Interface End Class ]]> </file> </compilation> CreateCompilationWithMscorlib(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "AddHandler", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "RemoveHandler", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "RaiseEvent", "EvntWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "Get", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsageOnAccessor, "Attr").WithArguments("Attr", "Set", "PropertyWithAccessors"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Sub1"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Ftn2"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "DeclareFtn"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "DeclareSub"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "-"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "CType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Evnt"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "NestedType"), Diagnostic(ERRID.ERR_InvalidAttributeUsage2, "Attr").WithArguments("Attr", "Iface")) End Sub <Fact> Public Sub AttributeTargets_WithEvents() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class A Inherits Attribute End Class Class D <A> Public WithEvents myButton As Button End Class Class Button Public Event OnClick() End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim myButton = DirectCast(d.GetMembers("myButton").Single(), PropertySymbol) Assert.Equal(0, myButton.GetAttributes().Length) Dim attr = myButton.GetFieldAttributes().Single() Assert.Equal("A", attr.AttributeClass.Name) End Sub <Fact> Public Sub AttributeTargets_WithEventsGenericInstantiation() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class A Inherits Attribute End Class Class D(Of T As Button) <A> Public WithEvents myButton As T End Class Class Button Public Event OnClick() End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim button = DirectCast(c.GlobalNamespace.GetMembers("Button").Single(), NamedTypeSymbol) Dim dOfButton = d.Construct(button) Dim myButton = DirectCast(dOfButton.GetMembers("myButton").Single(), PropertySymbol) Assert.Equal(0, myButton.GetAttributes().Length) Dim attr = myButton.GetFieldAttributes().Single() Assert.Equal("A", attr.AttributeClass.Name) End Sub <Fact> Public Sub AttributeTargets_Events() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Class A Inherits Attribute End Class <Serializable> Class D <A, NonSerialized> Public Event OnClick As Action End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) c.VerifyDiagnostics() Dim d = DirectCast(c.GlobalNamespace.GetMembers("D").Single(), NamedTypeSymbol) Dim onClick = DirectCast(d.GetMembers("OnClick").Single(), EventSymbol) ' TODO (tomat): move NonSerialized attribute onto the associated field Assert.Equal(2, onClick.GetAttributes().Length) ' should be 1 Assert.Equal(0, onClick.GetFieldAttributes().Length) ' should be 1 End Sub <Fact, WorkItem(546769, "DevDiv"), WorkItem(546770, "DevDiv")> Public Sub DiagnosticsOnEventParameters() Dim source = <compilation> <file name="a.vb"><![CDATA[ Imports System Imports System.Runtime.InteropServices Class C Event E(<MarshalAs()> x As Integer) End Class ]]> </file> </compilation> Dim c = CreateCompilationWithMscorlib(source) c.AssertTheseDiagnostics(<![CDATA[ BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments. Event E(<MarshalAs()> x As Integer) ~~~~~~~~~ ]]>) End Sub <Fact, WorkItem(528748, "DevDiv")> Public Sub TestNonPublicConstructor() Dim source = <compilation> <file name="TestNonPublicConstructor.vb"><![CDATA[ <Fred(1)> Class Class1 End Class Class FredAttribute : Inherits System.Attribute Public Sub New(x As Integer, Optional y As Integer = 1) End Sub Friend Sub New(x As Integer) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeNonPublicConstructor, "Fred")) End Sub <WorkItem(542223, "DevDiv")> <Fact> Public Sub AttributeArgumentAsEnumFromMetadata() Dim metadata1 = VisualBasicCompilation.Create("bar.dll", references:={MscorlibRef}, syntaxTrees:={Parse("Public Enum Bar : Baz : End Enum")}).EmitToArray(New EmitOptions(metadataOnly:=True)) Dim ref1 = MetadataReference.CreateFromImage(metadata1) Dim metadata2 = VisualBasicCompilation.Create( "foo.dll", references:={MscorlibRef, ref1}, syntaxTrees:={ VisualBasicSyntaxTree.ParseText(<![CDATA[ Public Class Ca : Inherits System.Attribute Public Sub New(o As Object) End Sub End Class <Ca(Bar.Baz)> Public Class Foo End Class]]>.Value)}).EmitToArray(options:=New EmitOptions(metadataOnly:=True)) Dim ref2 = MetadataReference.CreateFromImage(metadata2) Dim comp = VisualBasicCompilation.Create("moo.dll", references:={MscorlibRef, ref1, ref2}) Dim foo = comp.GetTypeByMetadataName("Foo") Dim ca = foo.GetAttributes().First().CommonConstructorArguments.First() Assert.Equal("Bar", ca.Type.Name) End Sub <Fact> Public Sub TestAttributeWithNestedUnboundGeneric() Dim library = <file name="Library.vb"><![CDATA[ Namespace ClassLibrary1 Public Class C1(Of T1) Public Class C2(Of T2, T3) End Class End Class End Namespace ]]> </file> Dim compilation1 = VisualBasicCompilation.Create("library.dll", {VisualBasicSyntaxTree.ParseText(library.Value)}, {MscorlibRef}, TestOptions.ReleaseDll) Dim classLibrary = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source = <compilation> <file name="TestAttributeWithNestedUnboundGeneric.vb"><![CDATA[ Imports System Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(ClassLibrary1.C1(Of )))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef, classLibrary}) compilation2.VerifyDiagnostics() Dim a = compilation2.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, UnboundGenericType) Assert.Equal("ClassLibrary1.C1(Of )", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithAliasToUnboundGeneric() Dim library = <file name="Library.vb"><![CDATA[ Namespace ClassLibrary1 Public Class C1(Of T1) Public Class C2(Of T2, T3) End Class End Class End Namespace ]]> </file> Dim compilation1 = VisualBasicCompilation.Create("library.dll", {VisualBasicSyntaxTree.ParseText(library.Value)}, {MscorlibRef}, TestOptions.ReleaseDll) Dim classLibrary = MetadataReference.CreateFromImage(compilation1.EmitToArray()) Dim source = <compilation> <file name="TestAttributeWithAliasToUnboundGeneric.vb"><![CDATA[ Imports System Imports x = ClassLibrary1 Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(x.C1(Of )))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef, classLibrary}) compilation2.VerifyDiagnostics() Dim a = compilation2.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, UnboundGenericType) Assert.Equal("ClassLibrary1.C1(Of )", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithArrayOfUnboundGeneric() Dim source = <compilation> <file name="TestAttributeWithArrayOfUnboundGeneric.vb"><![CDATA[ Imports System Class C1(of T) End Class Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(C1(Of )()))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef}) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ArrayOfRawGenericInvalid, "()")) Dim a = compilation.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, ArrayTypeSymbol) Assert.Equal("C1(Of ?)()", arg.ToDisplayString) End Sub <Fact> Public Sub TestAttributeWithNullableUnboundGeneric() Dim source = <compilation> <file name="TestAttributeWithNullableUnboundGeneric.vb"><![CDATA[ Imports System Class C1(of T) End Class Class A Inherits Attribute Public Sub New(o As Object) End Sub End Class <A(GetType(C1(Of )?))> Module Module1 Sub Main() End Sub End Module ]]> </file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndReferences(source, {SystemRef, MsvbRef}) CompilationUtils.AssertTheseDiagnostics(compilation, <errors><![CDATA[ BC33101: Type 'C1(Of ?)' must be a value type or a type argument constrained to 'Structure' in order to be used with 'Nullable' or nullable modifier '?'. <A(GetType(C1(Of )?))> ~~~~~~~ BC30182: Type expected. <A(GetType(C1(Of )?))> ~ ]]> </errors>) Dim a = compilation.GetTypeByMetadataName("Module1") Dim gt = a.GetAttributes().First().CommonConstructorArguments.First() Assert.False(DirectCast(gt.Value, TypeSymbol).IsErrorType) Dim arg = DirectCast(gt.Value, SubstitutedNamedType) Assert.Equal("C1(Of ?)?", arg.ToDisplayString) End Sub <Fact()> Public Sub TestConstantValueInsideAttributes() Dim tree = VisualBasicSyntaxTree.ParseText(<![CDATA[ Class c1 const A as integer = 1; const B as integer = 2; class MyAttribute : inherits Attribute Sub New(i as integer) End Sub end class <MyAttribute(A + B + 3)> Sub Foo() End Sub End Class"]]>.Value) Dim expr = tree.GetRoot().DescendantNodes().OfType(Of BinaryExpressionSyntax).First() Dim comp = CreateCompilationWithMscorlib({tree}) Dim constantValue = comp.GetSemanticModel(tree).GetConstantValue(expr) Assert.True(constantValue.HasValue) Assert.Equal(constantValue.Value, 6) End Sub <Fact> Public Sub TestArrayTypeInAttributeArgument() Dim source = <compilation> <file name="TestArrayTypeInAttributeArgument.vb"><![CDATA[ Imports System Public Class W End Class Public Class Y(Of T) Public Class F End Class Public Class Z(Of U) End Class End Class Public Class XAttribute Inherits Attribute Public Sub New(y As Object) End Sub End Class <X(GetType(W()))> _ Public Class C1 End Class <X(GetType(W(,)))> _ Public Class C2 End Class <X(GetType(W(,)()))> _ Public Class C3 End Class <X(GetType(Y(Of W)()(,)))> _ Public Class C4 End Class <X(GetType(Y(Of Integer).F(,)()(,,)))> _ Public Class C5 End Class <X(GetType(Y(Of Integer).Z(Of W)(,)()))> _ Public Class C6 End Class ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim classW As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("W") Dim classY As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("Y") Dim classF As NamedTypeSymbol = classY.GetTypeMember("F") Dim classZ As NamedTypeSymbol = classY.GetTypeMember("Z") Dim classX As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("XAttribute") Dim classC1 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C1") Dim classC2 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C2") Dim classC3 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C3") Dim classC4 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C4") Dim classC5 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C5") Dim classC6 As NamedTypeSymbol = m.GlobalNamespace.GetTypeMember("C6") Dim attrs = classC1.GetAttributes() Assert.Equal(1, attrs.Length) Dim typeArg = New ArrayTypeSymbol(classW, Nothing, 1, m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC2.GetAttributes() Assert.Equal(1, attrs.Length) typeArg = New ArrayTypeSymbol(classW, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC3.GetAttributes() Assert.Equal(1, attrs.Length) typeArg = New ArrayTypeSymbol(classW, Nothing, 1, m.ContainingAssembly) typeArg = New ArrayTypeSymbol(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC4.GetAttributes() Assert.Equal(1, attrs.Length) Dim classYOfW As NamedTypeSymbol = classY.Construct(ImmutableArray.Create(Of TypeSymbol)(classW)) typeArg = New ArrayTypeSymbol(classYOfW, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) typeArg = New ArrayTypeSymbol(typeArg, Nothing, 1, m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC5.GetAttributes() Assert.Equal(1, attrs.Length) Dim classYOfInt As NamedTypeSymbol = classY.Construct(ImmutableArray.Create(Of TypeSymbol)(m.ContainingAssembly.GetSpecialType(SpecialType.System_Int32))) Dim substNestedF As NamedTypeSymbol = classYOfInt.GetTypeMember("F") typeArg = New ArrayTypeSymbol(substNestedF, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=3, declaringAssembly:=m.ContainingAssembly) typeArg = New ArrayTypeSymbol(typeArg, Nothing, 1, m.ContainingAssembly) typeArg = New ArrayTypeSymbol(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) attrs = classC6.GetAttributes() Assert.Equal(1, attrs.Length) Dim substNestedZ As NamedTypeSymbol = classYOfInt.GetTypeMember("Z").Construct(ImmutableArray.Create(Of TypeSymbol)(classW)) typeArg = New ArrayTypeSymbol(substNestedZ, Nothing, 1, m.ContainingAssembly) typeArg = New ArrayTypeSymbol(typeArg, CType(Nothing, ImmutableArray(Of CustomModifier)), rank:=2, declaringAssembly:=m.ContainingAssembly) attrs.First().VerifyValue(Of Object)(0, TypedConstantKind.Type, typeArg) End Sub Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) CompileAndVerify(compilation, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub #End Region #Region "Error Tests" <Fact> Public Sub AttributeConstructorErrors1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="AttributeConstructorErrors1.vb"> <![CDATA[ Imports System Module m Function NotAConstant() as integer return 9 End Function End Module Enum e1 a End Enum <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub New() End Sub Sub New(ByVal d As Decimal) End Sub Sub New(ByRef i As Integer) End Sub Public Sub New(ByVal e As e1) End Sub End Class <XDoesNotExist> <X(1D)> <X(1)> <X(e1.a)> <X(NotAConstant() + 2)> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30002: Type 'XDoesNotExist' is not defined. <XDoesNotExist> ~~~~~~~~~~~~~ BC30045: Attribute constructor has a parameter of type 'Decimal', which is not an integral, floating-point or Enum type or one of Object, Char, String, Boolean, System.Type or 1-dimensional array of these types. <X(1D)> ~ BC36006: Attribute constructor has a 'ByRef' parameter of type 'Integer'; cannot use constructors with byref parameters to apply the attribute. <X(1)> ~ BC31516: Type 'e1' cannot be used in an attribute because it is not declared 'Public'. <X(e1.a)> ~ BC36006: Attribute constructor has a 'ByRef' parameter of type 'Integer'; cannot use constructors with byref parameters to apply the attribute. <X(NotAConstant() + 2)> ~ BC30059: Constant expression is required. <X(NotAConstant() + 2)> ~~~~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeConversionsErrors() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="AttributeConversionsErrors.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub New() End Sub Sub New(i As Integer) End Sub End Class <X("a")> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors><![CDATA[ BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute. <X("a")> ~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeNamedArgumentErrors1() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="AttributeNamedArgumentErrors1.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, allowMultiple:=True)> Class XAttribute Inherits Attribute Sub F1(i as integer) End Sub private PrivateField as integer shared Property SharedProperty as integer ReadOnly Property ReadOnlyProperty As Integer Get Return Nothing End Get End Property Property BadDecimalType as decimal Property BadDateType as date Property BadArrayType As Attribute() End Class <X(NotFound := nothing)> <X(F1 := nothing)> <X(PrivateField := nothing)> <X(SharedProperty := nothing)> <X(ReadOnlyProperty := nothing)> <X(BadDecimalType := nothing)> <X(BadDateType := nothing)> <X(BadArrayType:=Nothing)> Class A End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30661: Field or property 'NotFound' is not found. <X(NotFound := nothing)> ~~~~~~~~ BC32010: 'F1' cannot be named as a parameter in an attribute specifier because it is not a field or property. <X(F1 := nothing)> ~~ BC30389: 'XAttribute.PrivateField' is not accessible in this context because it is 'Private'. <X(PrivateField := nothing)> ~~~~~~~~~~~~ BC31500: 'Shared' attribute property 'SharedProperty' cannot be the target of an assignment. <X(SharedProperty := nothing)> ~~~~~~~~~~~~~~ BC31501: 'ReadOnly' attribute property 'ReadOnlyProperty' cannot be the target of an assignment. <X(ReadOnlyProperty := nothing)> ~~~~~~~~~~~~~~~~ BC30659: Property or field 'BadDecimalType' does not have a valid attribute type. <X(BadDecimalType := nothing)> ~~~~~~~~~~~~~~ BC30659: Property or field 'BadDateType' does not have a valid attribute type. <X(BadDateType := nothing)> ~~~~~~~~~~~ BC30659: Property or field 'BadArrayType' does not have a valid attribute type. <X(BadArrayType:=Nothing)> ~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(540939, "DevDiv")> <Fact> Public Sub AttributeProtectedConstructorError() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <A()> Class A Inherits Attribute Protected Sub New() End Sub End Class <B("foo")> Class B Inherits Attribute Protected Sub New() End Sub End Class <C("foo")> Class C Inherits Attribute Protected Sub New() End Sub Protected Sub New(b as string) End Sub End Class <D(1S)> Class D Inherits Attribute Protected Sub New() End Sub protected Sub New(b as Integer) End Sub protected Sub New(b as Long) End Sub End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30517: Overload resolution failed because no 'New' is accessible. <A()> ~~~ BC30517: Overload resolution failed because no 'New' is accessible. <B("foo")> ~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. <C("foo")> ~~~~~~~~ BC30517: Overload resolution failed because no 'New' is accessible. <D(1S)> ~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) ' TODO: after fixing LookupResults and changing the error handling for inaccessible attribute constructors, ' the error messages from above are expected to change to something like: ' Error BC30390 'A.Protected Sub New()' is not accessible in this context because it is 'Protected'. End Sub <WorkItem(540624, "DevDiv")> <Fact> Public Sub AttributeNoMultipleAndInvalidTarget() Dim source = <compilation> <file name="AttributeNoMultipleAndInvalidTarget.vb"><![CDATA[ Imports System Imports CustomAttribute <Base(1)> <Base("SOS")> Module AttributeMod <Derived("Q"c)> <Derived("C"c)> Public Class Foo End Class End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {MetadataReference.CreateFromImage(TestResources.SymbolsTests.Metadata.AttributeTestDef01)}) ' BC30663, BC30662 Dim expectedErrors = <errors> <![CDATA[ BC30663: Attribute 'BaseAttribute' cannot be applied multiple times. <Base("SOS")> ~~~~~~~~~~~ BC30662: Attribute 'DerivedAttribute' cannot be applied to 'Foo' because the attribute is not valid on this declaration type. <Derived("Q"c)> ~~~~~~~ BC30663: Attribute 'DerivedAttribute' cannot be applied multiple times. <Derived("C"c)> ~~~~~~~~~~~~~ ]]> </errors> CompilationUtils.AssertTheseDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub AttributeNameScoping() Dim source = <compilation> <file name="AttributeNameScoping.vb"><![CDATA[ Imports System ' X1 should not be visible without qualification <clscompliant(x1)> Module m1 Const X1 as boolean = true ' C1 should not be visible without qualification <clscompliant(C1)> Public Class CFoo Public Const C1 as Boolean = true <clscompliant(c1)> public Sub s() end sub End Class ' C1 should not be visible without qualification <clscompliant(C1)> Public Structure SFoo Public Const C1 as Boolean = true <clscompliant(c1)> public Sub s() end sub End Structure ' s should not be visible without qualification <clscompliant(s.GetType() isnot nothing)> Public Interface IFoo Sub s() End Interface ' C1 should not be visible without qualification <clscompliant(a = 1)> Public Enum EFoo A = 1 End Enum End Module ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_InaccessibleSymbol2, "x1").WithArguments("m1.X1", "Private"), Diagnostic(ERRID.ERR_NameNotDeclared1, "C1").WithArguments("C1"), Diagnostic(ERRID.ERR_NameNotDeclared1, "C1").WithArguments("C1"), Diagnostic(ERRID.ERR_NameNotDeclared1, "s").WithArguments("s"), Diagnostic(ERRID.ERR_RequiredConstExpr, "s.GetType() isnot nothing"), Diagnostic(ERRID.ERR_NameNotDeclared1, "a").WithArguments("a"), Diagnostic(ERRID.ERR_RequiredConstExpr, "a = 1")) End Sub <WorkItem(541279, "DevDiv")> <Fact> Public Sub AttributeArrayMissingInitializer() Dim source = <compilation> <file name="AttributeArrayMissingInitializer.vb"><![CDATA[ Imports System <AttributeUsage(AttributeTargets.All, AllowMultiple:=true)> Class A Inherits Attribute Public Sub New(x As Object()) End Sub End Class <A(New Object(5) {})> <A(New Object(5) {1})> Class B Shared Sub Main() End Sub End Class ]]></file> </compilation> Dim compilation = CreateCompilationWithMscorlib(source) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_MissingValuesForArraysInApplAttrs, "{}"), Diagnostic(ERRID.ERR_InitializerTooFewElements1, "{1}").WithArguments("5") ) End Sub <Fact> Public Sub Bug8642() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System <foo(Type.EmptyTypes)> Module Program Sub Main(args As String()) End Sub End Module ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30002: Type 'foo' is not defined. <foo(Type.EmptyTypes)> ~~~ BC30059: Constant expression is required. <foo(Type.EmptyTypes)> ~~~~~~~~~~~~~~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ErrorsInMultipleSyntaxTrees() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <Module: A> <AttributeUsage(AttributeTargets.Class)> Class A Inherits Attribute End Class <AttributeUsage(AttributeTargets.Method)> Class B Inherits Attribute End Class ]]> </file> <file name="b.vb"> <![CDATA[ <Module: B> ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30549: Attribute 'A' cannot be applied to a module. <Module: A> ~ BC30549: Attribute 'B' cannot be applied to a module. <Module: B> ~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub ErrorsInMultiplePartialDeclarations() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class)> Class A1 Inherits Attribute End Class <AttributeUsage(AttributeTargets.Method)> Class A2 Inherits Attribute End Class <A1> Class B End Class ]]> </file> <file name="b.vb"> <![CDATA[ <A1, A2> Partial Class B End Class ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30663: Attribute 'A1' cannot be applied multiple times. <A1, A2> ~~ BC30662: Attribute 'A2' cannot be applied to 'B' because the attribute is not valid on this declaration type. <A1, A2> ~~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <Fact> Public Sub PartialMethods() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"><![CDATA[ Imports System Public Class A Inherits Attribute End Class Public Class B Inherits Attribute End Class Partial Class C <A> Private Partial Sub Foo() End Sub <B> Private Sub Foo() End Sub End Class ]]> </file> </compilation>) CompileAndVerify(compilation, sourceSymbolValidator:= Sub(moduleSymbol) Dim c = DirectCast(moduleSymbol.GlobalNamespace.GetMembers("C").Single(), NamedTypeSymbol) Dim foo = DirectCast(c.GetMembers("Foo").Single(), MethodSymbol) Dim attrs = foo.GetAttributes() Assert.Equal(2, attrs.Length) Assert.Equal("A", attrs(0).AttributeClass.Name) Assert.Equal("B", attrs(1).AttributeClass.Name) End Sub) End Sub <WorkItem(542020, "DevDiv")> <Fact> Public Sub ErrorsAttributeNameResolutionWithNamespace() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class CAttribute Inherits Attribute End Class Namespace Y.CAttribute End Namespace Namespace Y Namespace X <C> Class C Inherits Attribute End Class End Namespace End Namespace ]]> </file> </compilation>) Dim expectedErrors = <errors> <![CDATA[ BC30182: Type expected. <C> ~ ]]></errors> CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors) End Sub <WorkItem(542170, "DevDiv")> <Fact> Public Sub GenericTypeParameterUsedAsAttribute() Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Module M <T> Sub Foo(Of T) End Sub Class T : Inherits Attribute End Class End Module ]]> </file> </compilation>) 'BC32067: Type parameters, generic types or types contained in generic types cannot be used as attributes. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_AttrCannotBeGenerics, "T").WithArguments("T")) End Sub <WorkItem(542273, "DevDiv")> <Fact()> Public Sub AnonymousTypeFieldAsAttributeNamedArgValue() Dim compilation = CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> <![CDATA[ Imports System <AttributeUsage(AttributeTargets.Class, AllowMultiple:=New With {.anonymousField = False}.anonymousField)> Class ExtensionAttribute Inherits Attribute End Class ]]> </file> </compilation>) 'BC30059: Constant expression is required. compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RequiredConstExpr, "New With {.anonymousField = False}.anonymousField")) End Sub <WorkItem(545073, "DevDiv")> <Fact> Public Sub AttributeOnDelegateReturnTypeError() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class ReturnTypeAttribute Inherits System.Attribute End Class Class C Public Delegate Function D() As <ReturnTypeAttribute(0)> Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_TooManyArgs1, "0").WithArguments("Public Sub New()")) End Sub <Fact> Public Sub AttributeOnDelegateParameterError() Dim source = <compilation> <file name="a.vb"><![CDATA[ Public Class ReturnTypeAttribute Inherits System.Attribute End Class Class C Public Delegate Function D(<ReturnTypeAttribute(0)>ByRef a As Integer) As Integer End Class ]]> </file> </compilation> CreateCompilationWithMscorlibAndVBRuntime(source).VerifyDiagnostics( Diagnostic(ERRID.ERR_TooManyArgs1, "0").WithArguments("Public Sub New()")) End Sub <WorkItem(545073, "DevDiv")> <Fact> Public Sub AttributesOnDelegate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Public Class A Inherits System.Attribute End Class Public Class B Inherits System.Attribute End Class Public Class C Inherits System.Attribute End Class <A> Public Delegate Function D(<C>a As Integer, <C>ByRef b As Integer) As <B> Integer ]]> </file> </compilation> Dim attributeValidator = Sub(m As ModuleSymbol) Dim d = m.GlobalNamespace.GetTypeMember("D") Dim invoke = DirectCast(d.GetMember("Invoke"), MethodSymbol) Dim beginInvoke = DirectCast(d.GetMember("BeginInvoke"), MethodSymbol) Dim endInvoke = DirectCast(d.GetMember("EndInvoke"), MethodSymbol) Dim ctor = DirectCast(d.Constructors.Single(), MethodSymbol) Dim p As ParameterSymbol ' no attributes on methods: Assert.Equal(0, invoke.GetAttributes().Length) Assert.Equal(0, beginInvoke.GetAttributes().Length) Assert.Equal(0, endInvoke.GetAttributes().Length) Assert.Equal(0, ctor.GetAttributes().Length) ' attributes on return types: Assert.Equal(0, beginInvoke.GetReturnTypeAttributes().Length) Assert.Equal(0, endInvoke.GetReturnTypeAttributes().Length) Assert.Equal(0, ctor.GetReturnTypeAttributes().Length) Dim attrs = invoke.GetReturnTypeAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "B") ' ctor parameters: Assert.Equal(2, ctor.Parameters.Length) Assert.Equal(0, ctor.Parameters(0).GetAttributes().Length) Assert.Equal(0, ctor.Parameters(0).GetAttributes().Length) ' Invoke parameters: Assert.Equal(2, invoke.Parameters.Length) attrs = invoke.Parameters(0).GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") attrs = invoke.Parameters(1).GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") ' BeginInvoke parameters: Assert.Equal(4, beginInvoke.Parameters.Length) p = beginInvoke.Parameters(0) Assert.Equal("a", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.False(p.IsExplicitByRef) Assert.False(p.IsByRef) p = beginInvoke.Parameters(1) Assert.Equal("b", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.True(p.IsExplicitByRef) Assert.True(p.IsByRef) Assert.Equal(0, beginInvoke.Parameters(2).GetAttributes().Length) Assert.Equal(0, beginInvoke.Parameters(3).GetAttributes().Length) ' EndInvoke parameters: Assert.Equal(2, endInvoke.Parameters.Length) p = endInvoke.Parameters(0) Assert.Equal("b", p.Name) attrs = p.GetAttributes() Assert.Equal(1, attrs.Length) Assert.Equal(attrs(0).AttributeClass.Name, "C") Assert.Equal(1, p.GetAttributes(attrs(0).AttributeClass).Count) Assert.True(p.IsExplicitByRef) Assert.True(p.IsByRef) p = endInvoke.Parameters(1) attrs = p.GetAttributes() Assert.Equal(0, attrs.Length) End Sub ' Verify attributes from source and then load metadata to see attributes are written correctly. CompileAndVerify(source, sourceSymbolValidator:=attributeValidator, symbolValidator:=attributeValidator) End Sub #End Region ''' <summary> ''' Verify that inaccessible friend AAttribute is preferred over accessible A ''' </summary> <Fact()> Public Sub TestAttributeLookupInaccessibleFriend() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Class A Inherits System.Attribute End Class <A()> Class C End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> Dim sourceWithAAttribute As XElement = <compilation> <file name="library.vb"> <![CDATA[ Class AAttribute End Class ]]></file> </compilation> Dim compWithAAttribute = VisualBasicCompilation.Create( "library.dll", {VisualBasicSyntaxTree.ParseText(sourceWithAAttribute.Value)}, {MsvbRef, MscorlibRef, SystemCoreRef}, TestOptions.ReleaseDll) Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {compWithAAttribute.ToMetadataReference()}) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "A").WithArguments("AAttribute", "Friend")) End Sub ''' <summary> ''' Verify that inaccessible inherited private is preferred ''' </summary> <Fact()> Public Sub TestAttributeLookupInaccessibleInheritedPrivate() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Class C Private Class NSAttribute Inherits Attribute End Class End Class Class d Inherits C <NS()> Sub d() End Sub End Class Module Module1 Sub Main() End Sub End Module]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_InaccessibleSymbol2, "NS").WithArguments("C.NSAttribute", "Private")) End Sub ''' <summary> ''' Verify that ambiguous error is reported when A binds to two Attributes. ''' </summary> ''' <remarks>If this is run in the IDE make sure global namespace is empty or add ''' global namespace prefix to N1 and N2 or run test at command line.</remarks> <Fact()> Public Sub TestAttributeLookupAmbiguousAttributesWithPrefix() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports N1 Imports N2 Namespace N1 Class AAttribute End Class End Namespace Namespace N2 Class AAttribute End Class End Namespace Class A Inherits Attribute End Class <A()> Class C End Class]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousInImports2, "A").WithArguments("AAttribute", "N1, N2")) End Sub ''' <summary> ''' Verify that source attribute takes precedence over metadata attribute with the same name ''' </summary> <Fact()> Public Sub TestAttributeLookupSourceOverridesMetadata() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Assembly Or AttributeTargets.Class Or AttributeTargets.Method)> Public Class extensionattribute : Inherits Attribute End Class End Namespace Module m <System.Runtime.CompilerServices.extension()> Sub Test1(x As Integer) System.Console.WriteLine(x) End Sub Sub Main() Dim x = New System.Runtime.CompilerServices.extensionattribute() End Sub End Module]]> </file> </compilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source) comp.VerifyDiagnostics() End Sub <WorkItem(543855, "DevDiv")> <Fact()> Public Sub VariantArrayConversionInAttribute() Dim vbCompilation = CreateVisualBasicCompilation("VariantArrayConversion", <![CDATA[ Imports System <Assembly: AObject(new Type() {GetType(string)})> <AttributeUsage(AttributeTargets.All)> Public Class AObjectAttribute Inherits Attribute Sub New(b As Object) End Sub Sub New(b As Object()) End Sub End Class ]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompileAndVerify(vbCompilation).VerifyDiagnostics() End Sub <Fact(), WorkItem(544199, "DevDiv")> Public Sub EnumsAllowedToViolateAttributeUsage() CompilationUtils.CreateCompilationWithMscorlib( <compilation> <file name="a.vb"> Imports System Imports System.Runtime.InteropServices &lt;ComVisible(True)&gt; _ &lt;Guid("6f4eb02b-3469-424c-bbcc-2672f653e646")&gt; _ &lt;BestFitMapping(False)&gt; _ &lt;StructLayout(LayoutKind.Auto)&gt; _ &lt;TypeLibType(TypeLibTypeFlags.FRestricted)&gt; _ &lt;Flags()&gt; _ Public Enum EnumHasAllSupportedAttributes ID1 ID2 End Enum </file> </compilation>).VerifyDiagnostics() End Sub <Fact, WorkItem(544367, "DevDiv")> Public Sub AttributeOnPropertyParameter() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim classAType As Type = GetType(A) Dim itemGetter = classAType.GetMethod("get_Item") ShowAttributes(itemGetter.GetParameters()(0)) Dim itemSetter = classAType.GetMethod("set_Item") ShowAttributes(itemSetter.GetParameters()(0)) End Sub Sub ShowAttributes(p As Reflection.ParameterInfo) Dim attrs = p.GetCustomAttributes(False) Console.WriteLine("param {1} in {0} has {2} attributes", p.Member, p.Name, attrs.Length) For Each a In attrs Console.WriteLine(" attribute of type {0}", a.GetType()) Next End Sub End Module Class A Default Public Property Item( &lt;MyAttr(A.C)&gt; index As Integer) As String Get Return "" End Get Set(value As String) End Set End Property Public Const C as Integer = 4 End Class Class MyAttr Inherits Attribute Public Sub New(x As Integer) End Sub End Class </file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(comp, <![CDATA[ param index in System.String get_Item(Int32) has 1 attributes attribute of type MyAttr param index in Void set_Item(Int32, System.String) has 1 attributes attribute of type MyAttr ]]>) End Sub <Fact, WorkItem(544367, "DevDiv")> Public Sub AttributeOnPropertyParameterWithError() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports System Module Module1 Sub Main() End Sub End Module Class A Default Public Property Item(<MyAttr> index As Integer) As String Get Return "" End Get Set(value As String) End Set End Property End Class Class MyAttr ' Does not intherit attribute End Class ]]> </file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(comp, <expected> BC31504: 'MyAttr' cannot be used as an attribute because it does not inherit from 'System.Attribute'. Default Public Property Item(&lt;MyAttr&gt; index As Integer) As String ~~~~~~ </expected>) End Sub <Fact, WorkItem(543810, "DevDiv")> Public Sub AttributeNamedArgumentWithEvent() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Class Base Event myEvent End Class Class Program Inherits Base <MyAttribute(t:=myEvent)> Event MyEvent2 Sub Main(args As String()) End Sub End Class Class MyAttribute Inherits Attribute Public t As Object Sub New(t As Integer, Optional x As Integer = 1.0D, Optional y As String = Nothing) End Sub End Class Module m Sub Main() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC30455: Argument not specified for parameter 't' of 'Public Sub New(t As Integer, [x As Integer = 1], [y As String = Nothing])'. <MyAttribute(t:=myEvent)> ~~~~~~~~~~~ BC30369: Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class. <MyAttribute(t:=myEvent)> ~~~~~~~ ]]></expected>) End Sub <Fact, WorkItem(543955, "DevDiv")> Public Sub StringParametersInDeclareMethods_1() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Reflection Module Module1 Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Unicode Function GetWindowsDirectory2 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Auto Function GetWindowsDirectory3 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, ByVal buffer As Integer) As Integer Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Declare Unicode Function GetWindowsDirectory5 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Declare Auto Function GetWindowsDirectory6 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Delegate Function D(ByRef buffer As String, ByVal buffer As Integer) As Integer Sub Main() Dim t = GetType(Module1) Print(t.GetMethod("GetWindowsDirectory1")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory2")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory3")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory4")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory5")) System.Console.WriteLine() Print(t.GetMethod("GetWindowsDirectory6")) System.Console.WriteLine() End Sub Private Sub Print(m As MethodInfo) System.Console.WriteLine(m.Name) For Each p In m.GetParameters() System.Console.WriteLine("{0} As {1}", p.Name, p.ParameterType) For Each marshal In p.GetCustomAttributes(GetType(Runtime.InteropServices.MarshalAsAttribute), False) System.Console.WriteLine(DirectCast(marshal, Runtime.InteropServices.MarshalAsAttribute).Value.ToString()) Next Next End Sub Sub Test1(ByRef x As String) GetWindowsDirectory1(x, 0) End Sub Sub Test2(ByRef x As String) GetWindowsDirectory2(x, 0) End Sub Sub Test3(ByRef x As String) GetWindowsDirectory3(x, 0) End Sub Sub Test4(ByRef x As String) GetWindowsDirectory4(x, 0) End Sub Sub Test5(ByRef x As String) GetWindowsDirectory5(x, 0) End Sub Sub Test6(ByRef x As String) GetWindowsDirectory6(x, 0) End Sub Function Test11() As D Return AddressOf GetWindowsDirectory1 End Function Function Test12() As D Return AddressOf GetWindowsDirectory2 End Function Function Test13() As D Return AddressOf GetWindowsDirectory3 End Function Function Test14() As D Return AddressOf GetWindowsDirectory4 End Function Function Test15() As D Return AddressOf GetWindowsDirectory5 End Function Function Test16() As D Return AddressOf GetWindowsDirectory6 End Function End Module ]]></file> </compilation>, TestOptions.ReleaseExe) Dim verifier = CompileAndVerify(comp, expectedOutput:= <![CDATA[ GetWindowsDirectory1 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory2 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory3 buffer As System.String& VBByRefStr buffer As System.Int32 GetWindowsDirectory4 buffer As System.String& AnsiBStr buffer As System.Int32 GetWindowsDirectory5 buffer As System.String& BStr buffer As System.Int32 GetWindowsDirectory6 buffer As System.String& TBStr buffer As System.Int32 ]]>) verifier.VerifyIL("Module1.Test1", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Ansi Function Module1.GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test2", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Unicode Function Module1.GetWindowsDirectory2 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test3", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Auto Function Module1.GetWindowsDirectory3 Lib "kernel32" Alias "GetWindowsDirectoryW" (String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test4", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Ansi Function Module1.GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test5", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Unicode Function Module1.GetWindowsDirectory5 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) verifier.VerifyIL("Module1.Test6", <![CDATA[ { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.0 IL_0002: call "Declare Auto Function Module1.GetWindowsDirectory6 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef String, Integer) As Integer" IL_0007: pop IL_0008: ret } ]]>) End Sub <Fact, WorkItem(543955, "DevDiv")> Public Sub StringParametersInDeclareMethods_3() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"> <![CDATA[ Imports System Imports System.Reflection Module Module1 Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByVal buffer As String, ByVal buffer As Integer) As Integer Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, ByVal buffer As Integer) As Integer Delegate Function D3(buffer As String, ByVal buffer As Integer) As Integer Delegate Function D4(buffer As Integer, ByVal buffer As Integer) As Integer Function Test19() As D3 Return AddressOf GetWindowsDirectory1 ' 1 End Function Function Test20() As D3 Return AddressOf GetWindowsDirectory4 ' 2 End Function Function Test21() As D4 Return AddressOf GetWindowsDirectory1 ' 3 End Function Function Test22() As D4 Return AddressOf GetWindowsDirectory4 ' 4 End Function Sub Main() End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) AssertTheseDiagnostics(comp, <expected> BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D3(buffer As String, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory1 ' 1 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D3(buffer As String, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory4 ' 2 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory1 Lib "kernel32" Alias "GetWindowsDirectoryW" (buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D4(buffer As Integer, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory1 ' 3 ~~~~~~~~~~~~~~~~~~~~ BC31143: Method 'Public Declare Ansi Function GetWindowsDirectory4 Lib "kernel32" Alias "GetWindowsDirectoryW" (ByRef buffer As String, buffer As Integer) As Integer' does not have a signature compatible with delegate 'Delegate Function Module1.D4(buffer As Integer, buffer As Integer) As Integer'. Return AddressOf GetWindowsDirectory4 ' 4 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <WorkItem(529620, "DevDiv")> <Fact()> Public Sub TestFriendEnumInAttribute() Dim source = <conpilation> <file name="a.vb"> <![CDATA[ ' Friend Enum in an array in an attribute should be an error. Imports System Friend Enum e2 r g b End Enum Namespace Test2 <MyAttr1(New e2() {e2.g})> Class C End Class Class MyAttr1 Inherits Attribute Sub New(ByVal B As e2()) End Sub End Class End Namespace ]]> </file> </conpilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlib(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadAttributeNonPublicType1, "MyAttr1").WithArguments("e2()")) End Sub <WorkItem(545558, "DevDiv")> <Fact()> Public Sub TestUndefinedEnumInAttribute() Dim source = <conpilation> <file name="a.vb"> <![CDATA[ Imports System.ComponentModel Module Program <EditorBrowsable(EditorBrowsableState.n)> Sub Main(args As String()) End Sub End Module ]]> </file> </conpilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(source) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotMember2, "EditorBrowsableState.n").WithArguments("n", "System.ComponentModel.EditorBrowsableState")) End Sub <WorkItem(545697, "DevDiv")> <Fact> Public Sub TestUnboundLambdaInNamedAttributeArgument() Dim source = <conpilation> <file name="a.vb"> <![CDATA[ Imports System Module Program <A(F:=Sub() Dim x = Mid("1", 1) End Sub)> Sub Main(args As String()) Dim a As Action = Sub() Dim x = Mid("1", 1) End Sub End Sub End Module ]]> </file> </conpilation> Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, additionalRefs:={SystemCoreRef}) comp.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "A").WithArguments("A"), Diagnostic(ERRID.ERR_NameNotDeclared1, "Mid").WithArguments("Mid"), Diagnostic(ERRID.ERR_PropertyOrFieldNotDefined1, "F").WithArguments("F"), Diagnostic(ERRID.ERR_NameNotDeclared1, "Mid").WithArguments("Mid")) End Sub <Fact> Public Sub SpecialNameAttributeFromSource() Dim source = <conpilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <SpecialName()> Public Structure S <SpecialName()> Friend Event E As Action(Of String) <SpecialName()> Default Property P(b As Byte) As Byte Get Return b End Get Set(value As Byte) End Set End Property End Structure ]]> </file> </conpilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source) Dim globalNS = comp.SourceAssembly.GlobalNamespace Dim typesym = DirectCast(globalNS.GetMember("S"), NamedTypeSymbol) Assert.NotNull(typesym) Assert.True(typesym.HasSpecialName) Dim e = DirectCast(typesym.GetMember("E"), EventSymbol) Assert.NotNull(e) Assert.True(e.HasSpecialName) Dim p = DirectCast(typesym.GetMember("P"), PropertySymbol) Assert.NotNull(p) Assert.True(p.HasSpecialName) Assert.True(e.HasSpecialName) Assert.Equal("Private EEvent As Action", e.AssociatedField.ToString) Assert.True(e.HasAssociatedField) Assert.Equal(ImmutableArray.Create(Of VisualBasicAttributeData)(), e.GetFieldAttributes) Assert.Null(e.OverriddenEvent) Assert.NotNull(p) Assert.True(p.HasSpecialName) Assert.Equal(ImmutableArray.Create(Of VisualBasicAttributeData)(), p.GetFieldAttributes) End Sub ''' <summary> ''' Verify that attributeusage from base class is used by derived class ''' </summary> <Fact()> Public Sub TestAttributeUsageInheritedBaseAttribute() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System Module Module1 <DerivedAllowsMultiple()> <DerivedAllowsMultiple()> ' Should allow multiple Sub Main() End Sub End Module]]> </file> </compilation> Dim sourceWithAttribute As XElement = <compilation> <file name="library.vb"> <![CDATA[ Imports System Public Class DerivedAllowsMultiple Inherits Base End Class <AttributeUsage(AttributeTargets.All, AllowMultiple:=True, Inherited:=true)> Public Class Base Inherits Attribute End Class ]]></file> </compilation> Dim compWithAttribute = VisualBasicCompilation.Create( "library.dll", {VisualBasicSyntaxTree.ParseText(sourceWithAttribute.Value)}, {MsvbRef, MscorlibRef, SystemCoreRef}, TestOptions.ReleaseDll) Dim sourceLibRef = compWithAttribute.ToMetadataReference() Dim comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {sourceLibRef}) comp.AssertNoDiagnostics() Dim metadataLibRef As MetadataReference = compWithAttribute.ToMetadataReference() comp = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(source, {metadataLibRef}) comp.AssertNoDiagnostics() Dim attributesOnMain = comp.GlobalNamespace.GetModuleMembers("Module1").Single().GetMembers("Main").Single().GetAttributes() Assert.Equal(2, attributesOnMain.Length()) Assert.NotEqual(attributesOnMain(0).ApplicationSyntaxReference, attributesOnMain(1).ApplicationSyntaxReference) Assert.NotNull(attributesOnMain(0).ApplicationSyntaxReference) End Sub <Fact(), WorkItem(546490, "DevDiv")> Public Sub Bug15984() Dim customIL = <![CDATA[ .assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) } .assembly extern FSharp.Core {} .assembly '<<GeneratedFileName>>' { } .class public abstract auto ansi sealed Library1.Foo extends [mscorlib]System.Object { .custom instance void [FSharp.Core]Microsoft.FSharp.Core.CompilationMappingAttribute::.ctor(valuetype [FSharp.Core]Microsoft.FSharp.Core.SourceConstructFlags) = ( 01 00 07 00 00 00 00 00 ) .method public static int32 inc(int32 x) cil managed { // Code size 5 (0x5) .maxstack 8 IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.1 IL_0003: add IL_0004: ret } // end of method Foo::inc } // end of class Library1.Foo ]]> Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource( <compilation> <file name="a.vb"> </file> </compilation>, customIL.Value, appendDefaultHeader:=False) Dim type = compilation.GetTypeByMetadataName("Library1.Foo") Assert.Equal(0, type.GetAttributes()(0).ConstructorArguments.Count) End Sub <Fact> <WorkItem(569089, "DevDiv")> Public Sub NullArrays() Dim source = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(a As Object(), b As Integer()) End Sub Public Property P As Object() Public F As Integer() End Class <A(Nothing, Nothing, P:=Nothing, F:=Nothing)> Class C End Class ]]></file> </compilation> CompileAndVerify(source, emitters:=TestEmitters.RefEmitBug, symbolValidator:= Sub(m) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.True(args(0).IsNull) Assert.Equal("Object()", args(0).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(0).Value) Assert.True(args(1).IsNull) Assert.Equal("Integer()", args(1).Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() args(1).Value) Dim named = attr.NamedArguments.ToDictionary(Function(e) e.Key, Function(e) e.Value) Assert.True(named("P").IsNull) Assert.Equal("Object()", named("P").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("P").Value) Assert.True(named("F").IsNull) Assert.Equal("Integer()", named("F").Type.ToDisplayString()) Assert.Throws(Of InvalidOperationException)(Function() named("F").Value) End Sub) End Sub <Fact> <WorkItem(688268, "DevDiv")> Public Sub Bug688268() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Runtime.InteropServices Imports System.Security Public Interface I Sub _VtblGap1_30() Sub _VtblGaX1_30() End Interface ]]></file> </compilation> Dim metadataValidator As System.Action(Of ModuleSymbol) = Sub([module] As ModuleSymbol) Dim metadata = DirectCast([module], PEModuleSymbol).Module Dim typeI = DirectCast([module].GlobalNamespace.GetTypeMembers("I").Single(), PENamedTypeSymbol) Dim methods = metadata.GetMethodsOfTypeOrThrow(typeI.Handle) Assert.Equal(2, methods.Count) Dim e = methods.GetEnumerator() e.MoveNext() Dim flags = metadata.GetMethodDefFlagsOrThrow(e.Current) Assert.Equal( MethodAttributes.PrivateScope Or MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.VtableLayoutMask Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.Abstract Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName, flags) e.MoveNext() flags = metadata.GetMethodDefFlagsOrThrow(e.Current) Assert.Equal( MethodAttributes.PrivateScope Or MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.VtableLayoutMask Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.Abstract, flags) End Sub CompileAndVerify(source, symbolValidator:=metadataValidator) End Sub <Fact> Public Sub NullTypeAndString() Dim source = <compilation> <file><![CDATA[ Imports System Public Class A Inherits Attribute Public Sub New(t As Type, s As String) End Sub End Class <A(Nothing, Nothing)> Class C End Class ]]></file> </compilation> CompileAndVerify(source, emitters:=TestEmitters.RefEmitBug, symbolValidator:= Sub(m) Dim c = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim attr = c.GetAttributes().Single() Dim args = attr.ConstructorArguments.ToArray() Assert.Null(args(0).Value) Assert.Equal("Type", args(0).Type.Name) Assert.Throws(Of InvalidOperationException)(Function() args(0).Values) Assert.Null(args(1).Value) Assert.Equal("String", args(1).Type.Name) Assert.Throws(Of InvalidOperationException)(Function() args(1).Values) End Sub) End Sub <Fact> <WorkItem(728865, "DevDiv")> Public Sub Repro728865() Dim source = <compilation> <file><![CDATA[ Imports System Imports System.Collections Imports System.Collections.Generic Imports System.Reflection Imports Microsoft.Yeti Namespace PFxIntegration Public Class ProducerConsumerScenario Shared Sub Main() Dim program = GetType(ProducerConsumerScenario) Dim methodInfo = program.GetMethod("ProducerConsumer") Dim myAttributes = methodInfo.GetCustomAttributes(False) If myAttributes.Length > 0 Then Console.WriteLine() Console.WriteLine("The attributes for the method - {0} - are: ", methodInfo) Console.WriteLine() For j = 0 To myAttributes.Length - 1 Console.WriteLine("The type of the attribute is {0}", myAttributes(j)) Next End If End Sub Public Enum CollectionType [Default] Queue Stack Bag End Enum Public Sub New() End Sub <CartesianRowData({5, 100, 100000}, {CollectionType.Default, CollectionType.Queue, CollectionType.Stack, CollectionType.Bag})> Public Sub ProducerConsumer() Console.WriteLine("Hello") End Sub End Class End Namespace Namespace Microsoft.Yeti <AttributeUsage(AttributeTargets.Method, AllowMultiple:=True)> Public Class CartesianRowDataAttribute Inherits Attribute Public Sub New() End Sub Public Sub New(ParamArray data As Object()) Dim asEnum As IEnumerable(Of Object)() = New IEnumerable(Of Object)(data.Length) {} For i = 0 To data.Length - 1 WrapEnum(DirectCast(data(i), IEnumerable)) Next End Sub Shared Sub WrapEnum(x As IEnumerable) For Each a In x Console.WriteLine(" - {0} -", a) Next End Sub End Class End Namespace ]]></file> </compilation> CompileAndVerify(source, emitters:=TestEmitters.RefEmitBug, expectedOutput:=<![CDATA[ - 5 - - 100 - - 100000 - - Default - - Queue - - Stack - - Bag - The attributes for the method - Void ProducerConsumer() - are: The type of the attribute is Microsoft.Yeti.CartesianRowDataAttribute]]>) End Sub <Fact> <WorkItem(728865, "DevDiv")> Public Sub ParamArrayAttributeConstructor() Dim source = <compilation> <file><![CDATA[ Imports System Public Class MyAttribute Inherits Attribute Public Sub New(ParamArray array As Object()) End Sub End Class Public Class Test <My({1, 2, 3})> Sub M1() End Sub <My(1, 2, 3)> Sub M2() End Sub <My({"A", "B", "C"})> Sub M3() End Sub <My("A", "B", "C")> Sub M4() End Sub <My({{1, 2, 3}, {"A", "B", "C"}})> Sub M5() End Sub <My({1, 2, 3}, {"A", "B", "C"})> Sub M6() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim methods = Enumerable.Range(1, 6).Select(Function(i) type.GetMember(Of MethodSymbol)("M" & i)).ToArray() methods(0).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Integer() {1, 2, 3}) methods(1).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {1, 2, 3}) methods(2).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New String() {"A", "B", "C"}) methods(3).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {"A", "B", "C"}) methods(4).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {}) ' Value was invalid. methods(5).GetAttributes().Single().VerifyValue(0, TypedConstantKind.Array, New Object() {DirectCast({1, 2, 3}, Object), DirectCast({"A", "B", "C"}, Object)}) comp.AssertTheseDiagnostics(<errors><![CDATA[ BC30934: Conversion from 'Object(*,*)' to 'Object' cannot occur in a constant expression used as an argument to an attribute. <My({{1, 2, 3}, {"A", "B", "C"}})> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ]]></errors>) End Sub <Fact> <WorkItem(737021, "DevDiv")> Public Sub NothingVersusEmptyArray() Dim source = <compilation> <file><![CDATA[ Imports System Public Class ArrayAttribute Inherits Attribute Public field As Integer() Public Sub New(array As Integer()) End Sub End Class Public Class Test <Array(Nothing)> Sub M0() End Sub <Array({})> Sub M1() End Sub <Array(Nothing, field:=Nothing)> Sub M2() End Sub <Array({}, field:=Nothing)> Sub M3() End Sub <Array(Nothing, field:={})> Sub M4() End Sub <Array({}, field:={})> Sub M5() End Sub End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim methods = Enumerable.Range(0, 6).Select(Function(i) type.GetMember(Of MethodSymbol)("M" & i)) Dim attrs = methods.Select(Function(m) m.GetAttributes().Single()).ToArray() Const fieldName = "field" Dim nullArray As Integer() = Nothing Dim emptyArray As Integer() = {} Assert.NotEqual(nullArray, emptyArray) attrs(0).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(1).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(2).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(2).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray) attrs(3).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(3).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, nullArray) attrs(4).VerifyValue(0, TypedConstantKind.Array, nullArray) attrs(4).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray) attrs(5).VerifyValue(0, TypedConstantKind.Array, emptyArray) attrs(5).VerifyNamedArgumentValue(0, fieldName, TypedConstantKind.Array, emptyArray) End Sub <Fact> <WorkItem(530266, "DevDiv")> Public Sub UnboundGenericTypeInTypedConstant() Dim source = <compilation> <file><![CDATA[ Imports System Public Class TestAttribute Inherits Attribute Sub New(x as Type) End Sub End Class <TestAttribute(GetType(Target(Of )))> Class Target(Of T) End Class ]]></file> </compilation> Dim comp = CreateCompilationWithMscorlib(source, TestOptions.ReleaseDll) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Target") Dim typeInAttribute = DirectCast(type.GetAttributes()(0).ConstructorArguments(0).Value, NamedTypeSymbol) Assert.True(typeInAttribute.IsUnboundGenericType) Assert.True(DirectCast(typeInAttribute, INamedTypeSymbol).IsUnboundGenericType) Assert.Equal("Target(Of )", typeInAttribute.ToTestDisplayString()) Dim comp2 = CreateCompilationWithMscorlibAndReferences(<compilation><file></file></compilation>, {comp.EmitToImageReference()}) type = comp2.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Target") Assert.IsAssignableFrom(Of PENamedTypeSymbol)(type) typeInAttribute = DirectCast(type.GetAttributes()(0).ConstructorArguments(0).Value, NamedTypeSymbol) Assert.True(typeInAttribute.IsUnboundGenericType) Assert.True(DirectCast(typeInAttribute, INamedTypeSymbol).IsUnboundGenericType) Assert.Equal("Target(Of )", typeInAttribute.ToTestDisplayString()) End Sub <Fact, WorkItem(879792, "DevDiv")> Public Sub Bug879792() Dim source2 = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Z> Module Program Sub Main() End Sub End Module Interface ZatTribute(Of T) End Interface Class Z Inherits Attribute End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlibAndVBRuntime(source2) CompilationUtils.AssertNoDiagnostics(comp) Dim program = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program") Assert.Equal("Z", program.GetAttributes()(0).AttributeClass.ToTestDisplayString()) End Sub <Fact, WorkItem(1020038, "DevDiv")> Public Sub Bug1020038() Dim source1 = <compilation name="Bug1020038"> <file name="a.vb"><![CDATA[ Public Class CTest End Class ]]> </file> </compilation> Dim validator = Sub(m As ModuleSymbol) Assert.Equal(2, m.ReferencedAssemblies.Length) Assert.Equal("Bug1020038", m.ReferencedAssemblies(1).Name) End Sub Dim compilation1 = CreateCompilationWithMscorlib(source1) Dim source2 = <compilation> <file name="a.vb"><![CDATA[ Class CAttr Inherits System.Attribute Sub New(x as System.Type) End Sub End Class <CAttr(GetType(CTest))> Class Test End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source2, {New VisualBasicCompilationReference(compilation1)}) CompileAndVerify(compilation2, symbolValidator:=validator) Dim source3 = <compilation> <file name="a.vb"><![CDATA[ Class CAttr Inherits System.Attribute Sub New(x as System.Type) End Sub End Class <CAttr(GetType(System.Func(Of System.Action(Of CTest))))> Class Test End Class ]]> </file> </compilation> Dim compilation3 = CreateCompilationWithMscorlibAndReferences(source3, {New VisualBasicCompilationReference(compilation1)}) CompileAndVerify(compilation3, symbolValidator:=validator) End Sub <Fact, WorkItem(1144603, "DevDiv")> Public Sub EmitMetadataOnlyInPresenceOfErrors() Dim source1 = <compilation> <file name="a.vb"><![CDATA[ Public Class DiagnosticAnalyzerAttribute Inherits System.Attribute Public Sub New(firstLanguage As String, ParamArray additionalLanguages As String()) End Sub End Class Public Class LanguageNames Public Const CSharp As xyz = "C#" End Class ]]> </file> </compilation> Dim compilation1 = CreateCompilationWithMscorlib(source1, options:=TestOptions.DebugDll) AssertTheseDiagnostics(compilation1, <![CDATA[ BC30002: Type 'xyz' is not defined. Public Const CSharp As xyz = "C#" ~~~ ]]>) Dim source2 = <compilation> <file name="a.vb"><![CDATA[ <DiagnosticAnalyzer(LanguageNames.CSharp)> Class CSharpCompilerDiagnosticAnalyzer End Class ]]> </file> </compilation> Dim compilation2 = CreateCompilationWithMscorlibAndReferences(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.DebugDll.WithModuleName("Test.dll")) Assert.Same(compilation1.Assembly, compilation2.SourceModule.ReferencedAssemblySymbols(1)) AssertTheseDiagnostics(compilation2) Dim emitResult2 = compilation2.Emit(peStream:=New MemoryStream(), options:=New EmitOptions(metadataOnly:=True)) Assert.False(emitResult2.Success) AssertTheseDiagnostics(emitResult2.Diagnostics, <![CDATA[ BC36970: Failed to emit module 'Test.dll'. ]]>) ' Use different mscorlib to test retargeting scenario Dim compilation3 = CreateCompilationWithMscorlib45AndVBRuntime(source2, {New VisualBasicCompilationReference(compilation1)}, options:=TestOptions.DebugDll) Assert.NotSame(compilation1.Assembly, compilation3.SourceModule.ReferencedAssemblySymbols(1)) AssertTheseDiagnostics(compilation3, <![CDATA[ BC30002: Type 'xyz' is not defined. <DiagnosticAnalyzer(LanguageNames.CSharp)> ~~~~~~~~~~~~~~~~~~~~ ]]>) Dim emitResult3 = compilation3.Emit(peStream:=New MemoryStream(), options:=New EmitOptions(metadataOnly:=True)) Assert.False(emitResult3.Success) AssertTheseDiagnostics(emitResult3.Diagnostics, <![CDATA[ BC30002: Type 'xyz' is not defined. <DiagnosticAnalyzer(LanguageNames.CSharp)> ~~~~~~~~~~~~~~~~~~~~ ]]>) End Sub End Class End Namespace
dsplaisted/roslyn
src/Compilers/VisualBasic/Test/Emit/Attributes/AttributeTests.vb
Visual Basic
apache-2.0
151,329
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmLeaderboard Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim DataGridViewCellStyle1 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle2 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle3 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle4 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle5 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle6 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle7 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle8 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle9 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle10 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle11 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle12 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle13 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle14 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim DataGridViewCellStyle15 As System.Windows.Forms.DataGridViewCellStyle = New System.Windows.Forms.DataGridViewCellStyle() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(frmLeaderboard)) Me.gbGridcoinProjectFactors = New System.Windows.Forms.GroupBox() Me.dgvNetworkStats = New System.Windows.Forms.DataGridView() Me.GroupBox1 = New System.Windows.Forms.GroupBox() Me.dgvLeaders = New System.Windows.Forms.DataGridView() Me.GroupBox2 = New System.Windows.Forms.GroupBox() Me.dgvLeadersByProject = New System.Windows.Forms.DataGridView() Me.gbGridcoinProjectFactors.SuspendLayout() CType(Me.dgvNetworkStats, System.ComponentModel.ISupportInitialize).BeginInit() Me.GroupBox1.SuspendLayout() CType(Me.dgvLeaders, System.ComponentModel.ISupportInitialize).BeginInit() Me.GroupBox2.SuspendLayout() CType(Me.dgvLeadersByProject, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'gbGridcoinProjectFactors ' Me.gbGridcoinProjectFactors.Controls.Add(Me.dgvNetworkStats) Me.gbGridcoinProjectFactors.ForeColor = System.Drawing.Color.Lime Me.gbGridcoinProjectFactors.Location = New System.Drawing.Point(12, 12) Me.gbGridcoinProjectFactors.Name = "gbGridcoinProjectFactors" Me.gbGridcoinProjectFactors.Size = New System.Drawing.Size(954, 213) Me.gbGridcoinProjectFactors.TabIndex = 2 Me.gbGridcoinProjectFactors.TabStop = False Me.gbGridcoinProjectFactors.Text = "Gridcoin Network Project Stats" ' 'dgvNetworkStats ' DataGridViewCellStyle1.BackColor = System.Drawing.Color.Black DataGridViewCellStyle1.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle1.SelectionBackColor = System.Drawing.Color.Gray DataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Me.dgvNetworkStats.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle1 Me.dgvNetworkStats.BackgroundColor = System.Drawing.Color.Black DataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle2.BackColor = System.Drawing.Color.Black DataGridViewCellStyle2.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle2.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvNetworkStats.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle2 Me.dgvNetworkStats.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize DataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle3.BackColor = System.Drawing.Color.Black DataGridViewCellStyle3.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle3.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle3.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle3.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.dgvNetworkStats.DefaultCellStyle = DataGridViewCellStyle3 Me.dgvNetworkStats.EnableHeadersVisualStyles = False Me.dgvNetworkStats.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.dgvNetworkStats.Location = New System.Drawing.Point(6, 19) Me.dgvNetworkStats.Name = "dgvNetworkStats" DataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle4.BackColor = System.Drawing.Color.Black DataGridViewCellStyle4.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle4.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle4.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) DataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvNetworkStats.RowHeadersDefaultCellStyle = DataGridViewCellStyle4 DataGridViewCellStyle5.BackColor = System.Drawing.Color.Black DataGridViewCellStyle5.ForeColor = System.Drawing.Color.Lime Me.dgvNetworkStats.RowsDefaultCellStyle = DataGridViewCellStyle5 Me.dgvNetworkStats.Size = New System.Drawing.Size(942, 188) Me.dgvNetworkStats.TabIndex = 0 ' 'GroupBox1 ' Me.GroupBox1.Controls.Add(Me.dgvLeaders) Me.GroupBox1.ForeColor = System.Drawing.Color.Lime Me.GroupBox1.Location = New System.Drawing.Point(12, 231) Me.GroupBox1.Name = "GroupBox1" Me.GroupBox1.Size = New System.Drawing.Size(954, 250) Me.GroupBox1.TabIndex = 3 Me.GroupBox1.TabStop = False Me.GroupBox1.Text = "Gridcoin Network Leaders" ' 'dgvLeaders ' DataGridViewCellStyle6.BackColor = System.Drawing.Color.Black DataGridViewCellStyle6.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle6.SelectionBackColor = System.Drawing.Color.Gray DataGridViewCellStyle6.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Me.dgvLeaders.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle6 Me.dgvLeaders.BackgroundColor = System.Drawing.Color.Black DataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle7.BackColor = System.Drawing.Color.Black DataGridViewCellStyle7.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle7.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle7.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle7.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvLeaders.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle7 Me.dgvLeaders.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize DataGridViewCellStyle8.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle8.BackColor = System.Drawing.Color.Black DataGridViewCellStyle8.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle8.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle8.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle8.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle8.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.dgvLeaders.DefaultCellStyle = DataGridViewCellStyle8 Me.dgvLeaders.EnableHeadersVisualStyles = False Me.dgvLeaders.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.dgvLeaders.Location = New System.Drawing.Point(6, 19) Me.dgvLeaders.Name = "dgvLeaders" DataGridViewCellStyle9.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle9.BackColor = System.Drawing.Color.Black DataGridViewCellStyle9.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle9.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle9.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle9.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) DataGridViewCellStyle9.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvLeaders.RowHeadersDefaultCellStyle = DataGridViewCellStyle9 DataGridViewCellStyle10.BackColor = System.Drawing.Color.Black DataGridViewCellStyle10.ForeColor = System.Drawing.Color.Lime Me.dgvLeaders.RowsDefaultCellStyle = DataGridViewCellStyle10 Me.dgvLeaders.Size = New System.Drawing.Size(942, 218) Me.dgvLeaders.TabIndex = 0 ' 'GroupBox2 ' Me.GroupBox2.Controls.Add(Me.dgvLeadersByProject) Me.GroupBox2.ForeColor = System.Drawing.Color.Lime Me.GroupBox2.Location = New System.Drawing.Point(12, 487) Me.GroupBox2.Name = "GroupBox2" Me.GroupBox2.Size = New System.Drawing.Size(954, 250) Me.GroupBox2.TabIndex = 4 Me.GroupBox2.TabStop = False Me.GroupBox2.Text = "Gridcoin Network Leaders by Project" ' 'dgvLeadersByProject ' DataGridViewCellStyle11.BackColor = System.Drawing.Color.Black DataGridViewCellStyle11.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle11.SelectionBackColor = System.Drawing.Color.Gray DataGridViewCellStyle11.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(128, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(128, Byte), Integer)) Me.dgvLeadersByProject.AlternatingRowsDefaultCellStyle = DataGridViewCellStyle11 Me.dgvLeadersByProject.BackgroundColor = System.Drawing.Color.Black DataGridViewCellStyle12.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle12.BackColor = System.Drawing.Color.Black DataGridViewCellStyle12.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle12.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle12.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle12.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle12.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvLeadersByProject.ColumnHeadersDefaultCellStyle = DataGridViewCellStyle12 Me.dgvLeadersByProject.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize DataGridViewCellStyle13.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle13.BackColor = System.Drawing.Color.Black DataGridViewCellStyle13.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle13.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle13.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle13.SelectionForeColor = System.Drawing.SystemColors.HighlightText DataGridViewCellStyle13.WrapMode = System.Windows.Forms.DataGridViewTriState.[False] Me.dgvLeadersByProject.DefaultCellStyle = DataGridViewCellStyle13 Me.dgvLeadersByProject.EnableHeadersVisualStyles = False Me.dgvLeadersByProject.GridColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(64, Byte), Integer)) Me.dgvLeadersByProject.Location = New System.Drawing.Point(6, 19) Me.dgvLeadersByProject.Name = "dgvLeadersByProject" DataGridViewCellStyle14.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft DataGridViewCellStyle14.BackColor = System.Drawing.Color.Black DataGridViewCellStyle14.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) DataGridViewCellStyle14.ForeColor = System.Drawing.Color.Lime DataGridViewCellStyle14.SelectionBackColor = System.Drawing.SystemColors.Highlight DataGridViewCellStyle14.SelectionForeColor = System.Drawing.Color.FromArgb(CType(CType(0, Byte), Integer), CType(CType(64, Byte), Integer), CType(CType(0, Byte), Integer)) DataGridViewCellStyle14.WrapMode = System.Windows.Forms.DataGridViewTriState.[True] Me.dgvLeadersByProject.RowHeadersDefaultCellStyle = DataGridViewCellStyle14 DataGridViewCellStyle15.BackColor = System.Drawing.Color.Black DataGridViewCellStyle15.ForeColor = System.Drawing.Color.Lime Me.dgvLeadersByProject.RowsDefaultCellStyle = DataGridViewCellStyle15 Me.dgvLeadersByProject.Size = New System.Drawing.Size(942, 218) Me.dgvLeadersByProject.TabIndex = 0 ' 'frmLeaderboard ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.Color.Black Me.ClientSize = New System.Drawing.Size(978, 758) Me.Controls.Add(Me.GroupBox2) Me.Controls.Add(Me.GroupBox1) Me.Controls.Add(Me.gbGridcoinProjectFactors) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.Name = "frmLeaderboard" Me.Text = "Gridcoin Leaderboard" Me.gbGridcoinProjectFactors.ResumeLayout(False) CType(Me.dgvNetworkStats, System.ComponentModel.ISupportInitialize).EndInit() Me.GroupBox1.ResumeLayout(False) CType(Me.dgvLeaders, System.ComponentModel.ISupportInitialize).EndInit() Me.GroupBox2.ResumeLayout(False) CType(Me.dgvLeadersByProject, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents gbGridcoinProjectFactors As System.Windows.Forms.GroupBox Friend WithEvents dgvNetworkStats As System.Windows.Forms.DataGridView Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox Friend WithEvents dgvLeaders As System.Windows.Forms.DataGridView Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox Friend WithEvents dgvLeadersByProject As System.Windows.Forms.DataGridView End Class
gridcoin/Gridcoin-master
src/boinc/boinc/frmLeaderboard.Designer.vb
Visual Basic
mit
18,239
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Editor.Implementation.Outlining Imports Microsoft.CodeAnalysis.Editor.UnitTests.Outlining Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class OverallOutliningTests Inherits AbstractSyntaxOutlinerTests Protected Overrides ReadOnly Property LanguageName As String Get Return LanguageNames.VisualBasic End Get End Property Friend Overrides Async Function GetRegionsAsync(document As Document, position As Integer) As Task(Of OutliningSpan()) Dim outliningService = document.Project.LanguageServices.GetService(Of IOutliningService)() Return (Await outliningService.GetOutliningSpansAsync(document, CancellationToken.None)) _ .WhereNotNull() _ .ToArray() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function DirectivesAtEndOfFile() As Task Const code = " $${|span1:Class C End Class|} {|span2:#Region ""Something"" #End Region|} " Await VerifyRegionsAsync(code, Region("span1", "Class C ...", autoCollapse:=False), Region("span2", "Something", autoCollapse:=False, isDefaultCollapsed:=True)) End Function End Class End Namespace
ericfe-ms/roslyn
src/EditorFeatures/VisualBasicTest/Outlining/OverallOutliningTests.vb
Visual Basic
apache-2.0
1,577
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSEvents_AddDelegate() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.Goo += Bar; } private void Bar(object sender, System.EventArgs e) { } public event System.EventHandler Goo; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Bar</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSEvents_AddDelegateForNonExistentEventHandler1() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.Goo += Bar; } public event System.EventHandler Goo; } </Document> </Project> </Workspace> ' Note: The expected result below is slightly different than Dev10 behavior. ' In Dev10, the NameRef for Bar will have a variablekind of "local", but ' "unknown" is really more correct and shouldn't impact the designer. Dim expected = <Block> <ExpressionStatement line="5"><Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="unknown"> <Name>Bar</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSEvents_AddDelegateForNonExistentEventHandler2() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.Goo += this.Bar; } public event System.EventHandler Goo; } </Document> </Project> </Workspace> ' Note: The expected result below is slightly different than Dev10 behavior. ' In Dev10, the NameRef for Bar will have a variablekind of "property", but ' "unknown" is really more correct and shouldn't impact the designer. Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Expression> <NameRef variablekind="unknown"> <Expression> <ThisReference/> </Expression> <Name>Bar</Name> </NameRef> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestCSEvents_AddDelegateForNonExistentEventHandler3() Dim definition = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class C { $$void M() { this.Goo += new System.EventHandler(this.Bar); } public event System.EventHandler Goo; } </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="5"> <Expression> <Assignment binaryoperator="adddelegate"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> <Expression> <NewClass> <Type>System.EventHandler</Type> <Argument> <Expression> <NameRef variablekind="unknown"> <Expression> <ThisReference/> </Expression> <Name>Bar</Name> </NameRef> </Expression> </Argument> </NewClass> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub End Class End Namespace
AlekseyTs/roslyn
src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_CSEvents.vb
Visual Basic
mit
6,438
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers Partial Friend Class ImplementsClauseCompletionProvider Inherits AbstractSymbolCompletionProvider Friend Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options) End Function Protected Overrides Function IsExclusive() As Boolean Return True End Function Protected Overrides Function GetSymbolsWorker( context As SyntaxContext, position As Integer, options As OptionSet, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of ISymbol)) If context.TargetToken.Kind = SyntaxKind.None Then Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)() End If If context.SyntaxTree.IsInNonUserCode(position, cancellationToken) OrElse context.SyntaxTree.IsInSkippedText(position, cancellationToken) Then Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)() End If ' We only care about Methods, Properties, and Events Dim memberKindKeyword As SyntaxKind = Nothing Dim methodDeclaration = context.TargetToken.GetAncestor(Of MethodStatementSyntax)() If methodDeclaration IsNot Nothing Then memberKindKeyword = methodDeclaration.DeclarationKeyword.Kind End If Dim propertyDeclaration = context.TargetToken.GetAncestor(Of PropertyStatementSyntax)() If propertyDeclaration IsNot Nothing Then memberKindKeyword = propertyDeclaration.DeclarationKeyword.Kind End If Dim eventDeclaration = context.TargetToken.GetAncestor(Of EventStatementSyntax)() If eventDeclaration IsNot Nothing Then memberKindKeyword = eventDeclaration.DeclarationKeyword.Kind End If ' We couldn't find a declaration. Bail. If memberKindKeyword = Nothing Then Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)() End If Dim result = ImmutableArray(Of ISymbol).Empty ' Valid positions: Immediately after 'Implements, after ., or after a , If context.TargetToken.Kind = SyntaxKind.ImplementsKeyword AndAlso context.TargetToken.Parent.IsKind(SyntaxKind.ImplementsClause) Then result = GetInterfacesAndContainers(position, context.TargetToken.Parent, context.SemanticModel, memberKindKeyword, cancellationToken) End If If context.TargetToken.Kind = SyntaxKind.CommaToken AndAlso context.TargetToken.Parent.IsKind(SyntaxKind.ImplementsClause) Then result = GetInterfacesAndContainers(position, context.TargetToken.Parent, context.SemanticModel, memberKindKeyword, cancellationToken) End If If context.TargetToken.IsKindOrHasMatchingText(SyntaxKind.DotToken) AndAlso WalkUpQualifiedNames(context.TargetToken) Then result = GetDottedMembers(position, DirectCast(context.TargetToken.Parent, QualifiedNameSyntax), context.SemanticModel, memberKindKeyword, cancellationToken) End If If result.Length > 0 Then Return Task.FromResult(result.WhereAsArray(Function(s) MatchesMemberKind(s, memberKindKeyword))) End If Return SpecializedTasks.EmptyImmutableArray(Of ISymbol)() End Function Private Function MatchesMemberKind(symbol As ISymbol, memberKindKeyword As SyntaxKind) As Boolean If symbol.Kind = SymbolKind.Alias Then symbol = DirectCast(symbol, IAliasSymbol).Target End If If TypeOf symbol Is INamespaceOrTypeSymbol Then Return True End If Dim method = TryCast(symbol, IMethodSymbol) If method IsNot Nothing Then If Not method.ReturnsVoid Then Return memberKindKeyword = SyntaxKind.FunctionKeyword End If Return memberKindKeyword = SyntaxKind.SubKeyword End If Dim [property] = TryCast(symbol, IPropertySymbol) If [property] IsNot Nothing Then Return memberKindKeyword = SyntaxKind.PropertyKeyword End If Return memberKindKeyword = SyntaxKind.EventKeyword End Function Private Function GetDottedMembers(position As Integer, qualifiedName As QualifiedNameSyntax, semanticModel As SemanticModel, memberKindKeyword As SyntaxKind, cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol) Dim containingType = semanticModel.GetEnclosingNamedType(position, cancellationToken) If containingType Is Nothing Then Return ImmutableArray(Of ISymbol).Empty End If Dim unimplementedInterfacesAndMembers = From item In containingType.GetAllUnimplementedMembersInThis(containingType.Interfaces, cancellationToken) Select New With {.interface = item.Item1, .members = item.Item2.Where(Function(s) MatchesMemberKind(s, memberKindKeyword))} Dim interfaces = unimplementedInterfacesAndMembers.Where(Function(i) i.members.Any()) _ .Select(Function(i) i.interface) Dim members = unimplementedInterfacesAndMembers.SelectMany(Function(i) i.members) Dim interfacesAndContainers = New HashSet(Of ISymbol)(interfaces) For Each [interface] In interfaces AddAliasesAndContainers([interface], interfacesAndContainers, Nothing, Nothing) Next Dim namespaces = interfacesAndContainers.OfType(Of INamespaceSymbol)() Dim left = qualifiedName.Left Dim leftHandTypeInfo = semanticModel.GetTypeInfo(left, cancellationToken) Dim leftHandBinding = semanticModel.GetSymbolInfo(left, cancellationToken) Dim container As INamespaceOrTypeSymbol = leftHandTypeInfo.Type If container Is Nothing OrElse container.IsErrorType Then container = TryCast(leftHandBinding.Symbol, INamespaceOrTypeSymbol) End If If container Is Nothing Then container = TryCast(leftHandBinding.CandidateSymbols.FirstOrDefault(), INamespaceOrTypeSymbol) End If If container Is Nothing Then Return ImmutableArray(Of ISymbol).Empty End If Dim symbols = semanticModel.LookupSymbols(position, container) Dim hashSet = New HashSet(Of ISymbol)(symbols.ToArray() _ .Where(Function(s As ISymbol) interfacesAndContainers.Contains(s, SymbolEquivalenceComparer.Instance) OrElse (TypeOf (s) Is INamespaceSymbol AndAlso namespaces.Contains(TryCast(s, INamespaceSymbol), INamespaceSymbolExtensions.EqualityComparer)) OrElse members.Contains(s))) Return hashSet.ToImmutableArray() End Function Private Function interfaceMemberGetter([interface] As ITypeSymbol, within As ISymbol) As ImmutableArray(Of ISymbol) Return ImmutableArray.CreateRange(Of ISymbol)([interface].AllInterfaces.SelectMany(Function(i) i.GetMembers()).Where(Function(s) s.IsAccessibleWithin(within))) _ .AddRange([interface].GetMembers()) End Function Private Function GetInterfacesAndContainers(position As Integer, node As SyntaxNode, semanticModel As SemanticModel, kind As SyntaxKind, cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol) Dim containingType = semanticModel.GetEnclosingNamedType(position, cancellationToken) If containingType Is Nothing Then Return ImmutableArray(Of ISymbol).Empty End If Dim interfaceWithUnimplementedMembers = containingType.GetAllUnimplementedMembersInThis(containingType.Interfaces, AddressOf interfaceMemberGetter, cancellationToken) _ .Where(Function(i) i.Item2.Any(Function(interfaceOrContainer) MatchesMemberKind(interfaceOrContainer, kind))) _ .Select(Function(i) i.Item1) Dim interfacesAndContainers = New HashSet(Of ISymbol)(interfaceWithUnimplementedMembers) For Each i In interfaceWithUnimplementedMembers AddAliasesAndContainers(i, interfacesAndContainers, node, semanticModel) Next Dim symbols = New HashSet(Of ISymbol)(semanticModel.LookupSymbols(position)) Dim availableInterfacesAndContainers = interfacesAndContainers.Where( Function(interfaceOrContainer) symbols.Contains(interfaceOrContainer.OriginalDefinition)).ToImmutableArray() Dim result = TryAddGlobalTo(availableInterfacesAndContainers) ' Even if there's not anything left to implement, we'll show the list of interfaces, ' the global namespace, and the project root namespace (if any), as long as the class implements something. If Not result.Any() AndAlso containingType.Interfaces.Any() Then Dim defaultListing = New List(Of ISymbol)(containingType.Interfaces.ToArray()) defaultListing.Add(semanticModel.Compilation.GlobalNamespace) If containingType.ContainingNamespace IsNot Nothing Then defaultListing.Add(containingType.ContainingNamespace) AddAliasesAndContainers(containingType.ContainingNamespace, defaultListing, node, semanticModel) End If Return defaultListing.ToImmutableArray() End If Return result End Function Private Sub AddAliasesAndContainers(symbol As ISymbol, interfacesAndContainers As ICollection(Of ISymbol), node As SyntaxNode, semanticModel As SemanticModel) ' Add aliases, if any for 'symbol' AddAlias(symbol, interfacesAndContainers, node, semanticModel) ' Add containers for 'symbol' Dim containingSymbol = symbol.ContainingSymbol If containingSymbol IsNot Nothing AndAlso Not interfacesAndContainers.Contains(containingSymbol) Then interfacesAndContainers.Add(containingSymbol) ' Add aliases, if any for 'containingSymbol' AddAlias(containingSymbol, interfacesAndContainers, node, semanticModel) If Not IsGlobal(containingSymbol) Then AddAliasesAndContainers(containingSymbol, interfacesAndContainers, node, semanticModel) End If End If End Sub Private Shared Sub AddAlias(symbol As ISymbol, interfacesAndContainers As ICollection(Of ISymbol), node As SyntaxNode, semanticModel As SemanticModel) If node IsNot Nothing AndAlso semanticModel IsNot Nothing AndAlso TypeOf symbol Is INamespaceOrTypeSymbol Then Dim aliasSymbol = DirectCast(symbol, INamespaceOrTypeSymbol).GetAliasForSymbol(node, semanticModel) If aliasSymbol IsNot Nothing AndAlso Not interfacesAndContainers.Contains(aliasSymbol) Then interfacesAndContainers.Add(aliasSymbol) End If End If End Sub Private Function IsGlobal(containingSymbol As ISymbol) As Boolean Dim [namespace] = TryCast(containingSymbol, INamespaceSymbol) Return [namespace] IsNot Nothing AndAlso [namespace].IsGlobalNamespace End Function Private Function TryAddGlobalTo(symbols As ImmutableArray(Of ISymbol)) As ImmutableArray(Of ISymbol) Dim withGlobalContainer = symbols.FirstOrDefault(Function(s) s.ContainingNamespace.IsGlobalNamespace) If withGlobalContainer IsNot Nothing Then Return symbols.Concat(ImmutableArray.Create(Of ISymbol)(withGlobalContainer.ContainingNamespace)) End If Return symbols End Function Private Function WalkUpQualifiedNames(token As SyntaxToken) As Boolean Dim parent = token.Parent While parent IsNot Nothing AndAlso parent.IsKind(SyntaxKind.QualifiedName) parent = parent.Parent End While Return parent IsNot Nothing AndAlso parent.IsKind(SyntaxKind.ImplementsClause) End Function Protected Overrides Function GetDisplayAndInsertionText(symbol As ISymbol, context As SyntaxContext) As (displayText As String, insertionText As String) If IsGlobal(symbol) Then Return ("Global", "Global") End If Dim displayText As String = Nothing Dim insertionText As String = Nothing If IsGenericType(symbol) Then displayText = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position) insertionText = displayText Else Dim displayAndInsertionText = CompletionUtilities.GetDisplayAndInsertionText(symbol, context) displayText = displayAndInsertionText.Item1 insertionText = displayAndInsertionText.Item2 End If Return (displayText, insertionText) End Function Private Shared Function IsGenericType(symbol As ISymbol) As Boolean Return symbol.MatchesKind(SymbolKind.NamedType) AndAlso symbol.GetAllTypeArguments().Any() End Function Private Shared ReadOnly MinimalFormatWithoutGenerics As SymbolDisplayFormat = SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions(SymbolDisplayGenericsOptions.None) Private Const InsertionTextOnOpenParen As String = NameOf(InsertionTextOnOpenParen) Protected Overrides Async Function CreateContext(document As Document, position As Integer, cancellationToken As CancellationToken) As Task(Of SyntaxContext) Dim semanticModel = Await document.GetSemanticModelForSpanAsync(New TextSpan(position, 0), cancellationToken).ConfigureAwait(False) Return Await VisualBasicSyntaxContext.CreateContextAsync(document.Project.Solution.Workspace, semanticModel, position, cancellationToken).ConfigureAwait(False) End Function Protected Overrides Function CreateItem(displayText As String, insertionText As String, symbols As List(Of ISymbol), context As SyntaxContext, preselect As Boolean, supportedPlatformData As SupportedPlatformData) As CompletionItem Dim item = MyBase.CreateItem(displayText, insertionText, symbols, context, preselect, supportedPlatformData) If IsGenericType(symbols(0)) Then Dim text = symbols(0).ToMinimalDisplayString(context.SemanticModel, context.Position, MinimalFormatWithoutGenerics) item = item.AddProperty(InsertionTextOnOpenParen, text) End If Return item End Function Protected Overrides Function GetInsertionText(item As CompletionItem, ch As Char) As String If ch = "("c Then Dim insertionText As String = Nothing If item.Properties.TryGetValue(InsertionTextOnOpenParen, insertionText) Then Return insertionText End If End If Return CompletionUtilities.GetInsertionTextAtInsertionTime(item, ch) End Function End Class End Namespace
OmarTawfik/roslyn
src/Features/VisualBasic/Portable/Completion/CompletionProviders/ImplementsClauseCompletionProvider.vb
Visual Basic
apache-2.0
16,482
Option Strict On Option Explicit On Option Infer Off Imports AudiopoLib Public Class AdminUnlockWrapper Inherits ContainerControl Private InnerContainer As New Control Private HeaderControl As FullWidthControl Private Lab As New Label Private TB As New TextBox Private LoggInn As FullWidthControl Private TSL As ThreadStarterLight Private LG As LoadingGraphics(Of PictureBox) Private LoadingSurface As New PictureBox Private ValidityChecker As MySqlAdminLogin Private CPath, FName As String Public Event IncorrectKey(Sender As Object, e As EventArgs) Public Event CorrectKey(Sender As Object, ConnectionSucceeded As Boolean) Public Sub New(CredPath As String, FileName As String) Hide() DoubleBuffered = True Size = New Size(250, 120) BackColor = Color.Gray With InnerContainer .Parent = Me .Width = Width - 2 .Height = Height - 2 .Location = New Point(1, 1) .BackColor = Color.White .TabStop = False End With CPath = CredPath FName = FileName HeaderControl = New FullWidthControl(InnerContainer) With HeaderControl .Text = "Lås opp (administrator)" .Height = 20 .TextAlign = ContentAlignment.MiddleLeft .BackColor = Color.FromArgb(80, 80, 80) .TabStop = False End With With Lab .Parent = InnerContainer .Top = HeaderControl.Bottom + 8 .Width = Width - 20 .Left = 10 .Text = "Skriv inn nøkkel for å låse opp systemet" .TabStop = False End With With TB .TabIndex = 0 .Parent = InnerContainer .Width = Width - 20 .Left = 10 .Top = Lab.Bottom .UseSystemPasswordChar = True .Focus() End With Height = TB.Bottom + 40 InnerContainer.Height = Height - 2 LoggInn = New FullWidthControl(InnerContainer, True, FullWidthControl.SnapType.Bottom) With LoggInn .Text = "Lås opp" .TabIndex = 1 End With AddHandler LoggInn.Click, AddressOf LoggInn_Click With LoadingSurface .TabStop = False .Hide() .Size = New Size(40, 40) .Location = New Point(Width \ 2 - .Width \ 2, Height \ 2 - .Height \ 2) .SendToBack() .Parent = InnerContainer End With LG = New LoadingGraphics(Of PictureBox)(LoadingSurface) With LG .Pen.Color = Color.FromArgb(230, 50, 80) .Stroke = 3 End With Show() End Sub Private Sub LoggInn_Click(Sender As Object, e As EventArgs) SuspendLayout() LoggInn.Enabled = False If TSL IsNot Nothing Then TSL.Dispose() End If TSL = New ThreadStarterLight(AddressOf CredManager_Decode) TSL.WhenFinished = AddressOf CredManager_Finished TSL.Start(New String() {CPath, FName, TB.Text}) For Each C As Control In InnerContainer.Controls C.Hide() Next LG.Spin(30, 10) ResumeLayout() End Sub Private Function CredManager_Decode(Data As Object) As Object Dim CredManager As New AdminCredentials Dim ArgsArr() As String = DirectCast(Data, String()) Dim CredPath As String = ArgsArr(0) Dim FileName As String = ArgsArr(1) Dim Key As String = ArgsArr(2) Dim GottenString As String = CredManager.Decode(CredPath, FileName, Key) Dim RetString() As String = Nothing If GottenString IsNot Nothing AndAlso GottenString <> "" Then RetString = CredManager.Decode(CredPath, FileName, Key).Split("%".ToCharArray) End If 'CredManager.Dispose Return RetString End Function Private Sub CredManager_Finished(Decoded As Object) Dim DecodedString() As String = DirectCast(Decoded, String()) If TSL IsNot Nothing Then TSL.Dispose() End If OnDecodeFinished((DecodedString IsNot Nothing AndAlso DecodedString(0) <> ""), DecodedString) End Sub Private Sub OnDecodeFinished(ByVal CorrectKey As Boolean, Data() As String) If CorrectKey Then Credentials = New DatabaseCredentials(Data(0), Data(1), Data(2), Data(3)) If ValidityChecker IsNot Nothing Then ValidityChecker.Dispose() End If ValidityChecker = New MySqlAdminLogin(Data(0), Data(1)) ValidityChecker.WhenFinished = AddressOf OnCheckFinished ValidityChecker.LoginAsync(Data(2), Data(3)) Else Credentials = Nothing LoggInn.Enabled = True LG.StopSpin() LoadingSurface.SendToBack() TB.Clear() For Each C As Control In InnerContainer.Controls C.Show() Next TB.Focus() RaiseEvent IncorrectKey(Me, EventArgs.Empty) End If End Sub Private Sub OnCheckFinished(Valid As Boolean) LoggInn.Enabled = True LG.StopSpin() LoadingSurface.SendToBack() TB.Clear() If Not Valid Then For Each C As Control In InnerContainer.Controls C.Show() Next End If 'If Valid Then ' TB.Hide() 'End If RaiseEvent CorrectKey(Me, Valid) End Sub Protected Overrides Sub Dispose(disposing As Boolean) If disposing Then 'HeaderControl.Dispose() 'Lab.Dispose() 'TB.Dispose() 'LoggInn.Dispose() If TSL IsNot Nothing Then TSL.Dispose() End If LG.Dispose() 'LoadingSurface.Dispose() If ValidityChecker IsNot Nothing Then ValidityChecker.Dispose() End If 'InnerContainer.Dispose() End If MyBase.Dispose(disposing) End Sub End Class
Audiopolis/Gruppe21-prosjekt
Gruppe21-Prosjekt-Alpha/AdminUnlock.vb
Visual Basic
mit
6,147
 Imports System.ComponentModel Public Enum OutFileTypes ''' <summary> ''' write mzXML format ''' </summary> <Description("--mzXML")> mzXML ''' <summary> ''' write mzML format [default] ''' </summary> <Description("--mzML")> mzML ''' <summary> ''' write mz5 format ''' </summary> <Description("--mz5")> mz5 ''' <summary> ''' write Mascot generic format ''' </summary> <Description("--mgf")> mgf ''' <summary> ''' write ProteoWizard internal text format ''' </summary> <Description("--text")> text ''' <summary> ''' write MS1 format ''' </summary> <Description("--ms1")> ms1 ''' <summary> ''' write CMS1 format ''' </summary> <Description("--cms1")> cms1 ''' <summary> ''' write MS2 format ''' </summary> <Description("--ms2")> ms2 ''' <summary> ''' write CMS2 format ''' </summary> <Description("--cms2")> cms2 End Enum
xieguigang/spectrum
src/assembly/ProteoWizard.Interop/OutFileTypes.vb
Visual Basic
mit
967
Imports System.IO Public Module Func Public DefaultServerName As String = "버들실험실 공식 서버 I" Public DefaultServerURL As String = "http://library.willowslab.com/lib/" Dim PathDialog = New FolderBrowserDialog() Public Function webClient(ByVal fileURL, ByVal Dir, ByVal filename) Try Dim Down As New Net.WebClient If Not Directory.Exists(Dir) Then Directory.CreateDirectory(Dir) End If Down.DownloadFile(fileURL, Dir & filename) Return True Catch ex As Exception Return False End Try End Function Public Function rgb(ByVal r As Integer, ByVal g As Integer, ByVal b As Integer) As Color Return System.Drawing.Color.FromArgb(CType(CType(r, Byte), Integer), CType(CType(g, Byte), Integer), CType(CType(b, Byte), Integer)) End Function Public Function getReg(ByVal regPath As String, ByVal regKey As String) As String Return My.Computer.Registry.GetValue(regPath, regKey, "") End Function Public Sub setReg(ByVal regPath As String, ByVal regKey As String, ByVal regValue As Object) My.Computer.Registry.SetValue(regPath, regKey, regValue) End Sub Public Function setMabiPath() As Boolean If PathDialog.ShowDialog() <> DialogResult.Cancel Then Dim path As String = PathDialog.SelectedPath If ExistsFile(path & "\client.exe") And ExistsFile(path & "\version.dat") And (ExistsFile(path & "\mabinogi.exe") Or ExistsFile(path & "\mabinogi_test.exe")) Then setReg("HKEY_CURRENT_USER\Software\Nexon\Mabinogi", "", path) FSmsg("등록되었습니다. [" & path & "]") Setting.Mabi = getReg("HKEY_CURRENT_USER\Software\Nexon\Mabinogi", "") Return True Else FSmsg("뭔가 이상한 곳을 고르지 않았나요?") setMabiPath() End If End If Return False End Function Public Function setMabiTestPath() As Boolean If PathDialog.ShowDialog() <> DialogResult.Cancel Then Dim path As String = PathDialog.SelectedPath If ExistsFile(path & "\client.exe") And ExistsFile(path & "\version.dat") And ExistsFile(path & "\mabinogi_test.exe") Then setReg("HKEY_CURRENT_USER\Software\Nexon\Mabinogi_test", "", path) FSmsg("등록되었습니다. [" & path & "]") Setting.MabiTest = getReg("HKEY_CURRENT_USER\Software\Nexon\Mabinogi_test", "") Return True Else FSmsg("뭔가 이상한 곳을 고르지 않았나요?") setMabiTestPath() End If End If Return False End Function Public Sub readSet() End Sub Public Sub FSmsg(ByVal message As String) MsgBox(message, MsgBoxStyle.Information Or vbMsgBoxSetForeground, "지니나리마스!") End Sub Public Sub ServerSetChange(ByVal Name As String, ByVal URL As String) DefaultServerName = Name DefaultServerURL = URL End Sub Public Function ExistsFile(ByVal path As String) As Boolean If IO.File.Exists(path) Then Return True Else Return False End If End Function Public Sub ExistsDir(ByVal path As String) If Not IO.Directory.Exists(path) Then IO.Directory.CreateDirectory(path) End If End Sub Public Function getVersion(ByVal path As String) As Integer Dim fs As IO.FileStream = Nothing Dim br As IO.BinaryReader = Nothing Dim mVersion As UInteger = 0 Dim FilePath As String = path Try If My.Computer.FileSystem.FileExists(FilePath) = True Then fs = New IO.FileStream(FilePath, IO.FileMode.Open, IO.FileAccess.Read) br = New IO.BinaryReader(fs) mVersion = br.ReadUInt32() End If Catch ex As Exception Finally If br Is Nothing = False Then br.Close() End If If fs Is Nothing = False Then fs.Close() End If End Try Return mVersion End Function End Module
willowslaboratory/WLABV3
library.willowslab.net/Library_v3/Modules/Func.vb
Visual Basic
mit
4,298
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '<summary> ' A strongly-typed resource class, for looking up localized strings, etc. '</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '<summary> ' Returns the cached ResourceManager instance used by this class. '</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("Sample.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '<summary> ' Overrides the current thread's CurrentUICulture property for all ' resource lookups using this strongly typed resource class. '</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set(ByVal value As Global.System.Globalization.CultureInfo) resourceCulture = value End Set End Property End Module End Namespace
Ico093/TelerikAcademy
JavaScript#2/Exams/JavaScript#2-Sample/Sample/Sample/My Project/Resources.Designer.vb
Visual Basic
mit
2,695
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class ConnectionDataBaseForm Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Label1 = New System.Windows.Forms.Label Me.butAcept = New System.Windows.Forms.Button Me.butCancel = New System.Windows.Forms.Button Me.txtServerName = New System.Windows.Forms.TextBox Me.Label3 = New System.Windows.Forms.Label Me.cmbAuthentication = New System.Windows.Forms.ComboBox Me.lblUsername = New System.Windows.Forms.Label Me.lblPassword = New System.Windows.Forms.Label Me.txtUsername = New System.Windows.Forms.TextBox Me.txtPassword = New System.Windows.Forms.TextBox Me.Label2 = New System.Windows.Forms.Label Me.txtDataBase = New System.Windows.Forms.TextBox Me.rbtConnectMDF = New System.Windows.Forms.RadioButton Me.rbtConnectSQLServer = New System.Windows.Forms.RadioButton Me.SuspendLayout() ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(52, 96) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(72, 13) Me.Label1.TabIndex = 0 Me.Label1.Text = "Server Name:" ' 'butAcept ' Me.butAcept.Anchor = System.Windows.Forms.AnchorStyles.Top Me.butAcept.DialogResult = System.Windows.Forms.DialogResult.OK Me.butAcept.Location = New System.Drawing.Point(86, 312) Me.butAcept.Name = "butAcept" Me.butAcept.Size = New System.Drawing.Size(75, 23) Me.butAcept.TabIndex = 6 Me.butAcept.Text = "Acept" Me.butAcept.UseVisualStyleBackColor = True ' 'butCancel ' Me.butCancel.Anchor = System.Windows.Forms.AnchorStyles.Top Me.butCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel Me.butCancel.Location = New System.Drawing.Point(197, 312) Me.butCancel.Name = "butCancel" Me.butCancel.Size = New System.Drawing.Size(75, 23) Me.butCancel.TabIndex = 7 Me.butCancel.Text = "Cancel" Me.butCancel.UseVisualStyleBackColor = True ' 'txtServerName ' Me.txtServerName.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtServerName.Enabled = False Me.txtServerName.Location = New System.Drawing.Point(146, 93) Me.txtServerName.Name = "txtServerName" Me.txtServerName.Size = New System.Drawing.Size(168, 20) Me.txtServerName.TabIndex = 1 ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.Location = New System.Drawing.Point(52, 164) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(78, 13) Me.Label3.TabIndex = 6 Me.Label3.Text = "Authentication:" ' 'cmbAuthentication ' Me.cmbAuthentication.AllowDrop = True Me.cmbAuthentication.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.cmbAuthentication.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList Me.cmbAuthentication.Enabled = False Me.cmbAuthentication.FormattingEnabled = True Me.cmbAuthentication.Items.AddRange(New Object() {"Windows Authentication", "Server Authentication"}) Me.cmbAuthentication.Location = New System.Drawing.Point(146, 161) Me.cmbAuthentication.Name = "cmbAuthentication" Me.cmbAuthentication.Size = New System.Drawing.Size(168, 21) Me.cmbAuthentication.TabIndex = 3 ' 'lblUsername ' Me.lblUsername.AutoSize = True Me.lblUsername.Enabled = False Me.lblUsername.Location = New System.Drawing.Point(52, 220) Me.lblUsername.Name = "lblUsername" Me.lblUsername.Size = New System.Drawing.Size(58, 13) Me.lblUsername.TabIndex = 8 Me.lblUsername.Text = "Username:" ' 'lblPassword ' Me.lblPassword.AutoSize = True Me.lblPassword.Enabled = False Me.lblPassword.Location = New System.Drawing.Point(52, 260) Me.lblPassword.Name = "lblPassword" Me.lblPassword.Size = New System.Drawing.Size(56, 13) Me.lblPassword.TabIndex = 9 Me.lblPassword.Text = "Passwrod:" ' 'txtUsername ' Me.txtUsername.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtUsername.Enabled = False Me.txtUsername.Location = New System.Drawing.Point(146, 220) Me.txtUsername.Name = "txtUsername" Me.txtUsername.Size = New System.Drawing.Size(168, 20) Me.txtUsername.TabIndex = 4 ' 'txtPassword ' Me.txtPassword.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtPassword.Enabled = False Me.txtPassword.Location = New System.Drawing.Point(146, 260) Me.txtPassword.Name = "txtPassword" Me.txtPassword.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42) Me.txtPassword.Size = New System.Drawing.Size(168, 20) Me.txtPassword.TabIndex = 5 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.Location = New System.Drawing.Point(52, 130) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(60, 13) Me.Label2.TabIndex = 12 Me.Label2.Text = "Data Base:" ' 'txtDataBase ' Me.txtDataBase.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.txtDataBase.Enabled = False Me.txtDataBase.Location = New System.Drawing.Point(146, 127) Me.txtDataBase.Name = "txtDataBase" Me.txtDataBase.Size = New System.Drawing.Size(168, 20) Me.txtDataBase.TabIndex = 2 ' 'rbtConnectMDF ' Me.rbtConnectMDF.AutoSize = True Me.rbtConnectMDF.Checked = True Me.rbtConnectMDF.Location = New System.Drawing.Point(105, 24) Me.rbtConnectMDF.Name = "rbtConnectMDF" Me.rbtConnectMDF.Size = New System.Drawing.Size(167, 17) Me.rbtConnectMDF.TabIndex = 13 Me.rbtConnectMDF.TabStop = True Me.rbtConnectMDF.Text = "Connect using Instance Mode" Me.rbtConnectMDF.UseVisualStyleBackColor = True ' 'rbtConnectSQLServer ' Me.rbtConnectSQLServer.AutoSize = True Me.rbtConnectSQLServer.Location = New System.Drawing.Point(105, 47) Me.rbtConnectSQLServer.Name = "rbtConnectSQLServer" Me.rbtConnectSQLServer.Size = New System.Drawing.Size(135, 17) Me.rbtConnectSQLServer.TabIndex = 14 Me.rbtConnectSQLServer.Text = "Connect to SQL Server" Me.rbtConnectSQLServer.UseVisualStyleBackColor = True ' 'ConnectionDataBaseForm ' Me.AcceptButton = Me.butAcept Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.CancelButton = Me.butCancel Me.ClientSize = New System.Drawing.Size(370, 351) Me.Controls.Add(Me.rbtConnectSQLServer) Me.Controls.Add(Me.rbtConnectMDF) Me.Controls.Add(Me.txtDataBase) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.txtPassword) Me.Controls.Add(Me.txtUsername) Me.Controls.Add(Me.lblPassword) Me.Controls.Add(Me.lblUsername) Me.Controls.Add(Me.cmbAuthentication) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.txtServerName) Me.Controls.Add(Me.butCancel) Me.Controls.Add(Me.butAcept) Me.Controls.Add(Me.Label1) Me.MaximizeBox = False Me.MinimizeBox = False Me.MinimumSize = New System.Drawing.Size(355, 382) Me.Name = "ConnectionDataBaseForm" Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent Me.Text = "DataBase Connection " Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents butAcept As System.Windows.Forms.Button Friend WithEvents butCancel As System.Windows.Forms.Button Friend WithEvents txtServerName As System.Windows.Forms.TextBox Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents cmbAuthentication As System.Windows.Forms.ComboBox Friend WithEvents lblUsername As System.Windows.Forms.Label Friend WithEvents lblPassword As System.Windows.Forms.Label Friend WithEvents txtUsername As System.Windows.Forms.TextBox Friend WithEvents txtPassword As System.Windows.Forms.TextBox Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents txtDataBase As System.Windows.Forms.TextBox Friend WithEvents rbtConnectMDF As System.Windows.Forms.RadioButton Friend WithEvents rbtConnectSQLServer As System.Windows.Forms.RadioButton End Class
QMDevTeam/QMDesigner
DataManager/Dialogs/ConnectionDataBaseForm.Designer.vb
Visual Basic
apache-2.0
10,458
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("AuthorizeVault")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("AuthorizeVault")> <Assembly: AssemblyCopyright("Copyright © 2018")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("873646b3-e712-43d8-ab84-a3c1ef3f04a6")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
Cayan-LLC/developer-docs
examples/merchantware/Credit/vb/AuthorizeVault/AuthorizeVault/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,133
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.Cci Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Reflection.Metadata Imports System.Runtime.InteropServices Imports Roslyn.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class EEAssemblyBuilder Inherits PEAssemblyBuilderBase Friend ReadOnly Methods As ImmutableArray(Of MethodSymbol) Friend Sub New( sourceAssembly As SourceAssemblySymbol, emitOptions As EmitOptions, methods As ImmutableArray(Of MethodSymbol), serializationProperties As ModulePropertiesForSerialization, additionalTypes As ImmutableArray(Of NamedTypeSymbol), testData As CompilationTestData) MyBase.New( sourceAssembly, emitOptions, outputKind:=OutputKind.DynamicallyLinkedLibrary, serializationProperties:=serializationProperties, manifestResources:=SpecializedCollections.EmptyEnumerable(Of ResourceDescription)(), additionalTypes:=additionalTypes) Me.Methods = methods If testData IsNot Nothing Then SetMethodTestData(testData.Methods) testData.Module = Me End If End Sub Protected Overrides Function TranslateModule(symbol As ModuleSymbol, diagnostics As DiagnosticBag) As IModuleReference Dim moduleSymbol = TryCast(symbol, PEModuleSymbol) If moduleSymbol IsNot Nothing Then Dim [module] = moduleSymbol.Module ' Expose the individual runtime Windows.*.winmd modules as assemblies. ' (The modules were wrapped in a placeholder Windows.winmd assembly ' in MetadataUtilities.MakeAssemblyReferences.) If MetadataUtilities.IsWindowsComponent([module].MetadataReader, [module].Name) AndAlso MetadataUtilities.IsWindowsAssemblyName(moduleSymbol.ContainingAssembly.Name) Then Dim identity = [module].ReadAssemblyIdentityOrThrow() Return New Microsoft.CodeAnalysis.ExpressionEvaluator.AssemblyReference(identity) End If End If Return MyBase.TranslateModule(symbol, diagnostics) End Function Friend Overrides ReadOnly Property IgnoreAccessibility As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property CurrentGenerationOrdinal As Integer Get Return 0 End Get End Property Friend Overrides Function TryCreateVariableSlotAllocator(symbol As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Dim method = TryCast(symbol, EEMethodSymbol) If method IsNot Nothing Then Dim defs = GetLocalDefinitions(method.Locals) Return New SlotAllocator(defs) End If Return Nothing End Function Private Shared Function GetLocalDefinitions(locals As ImmutableArray(Of LocalSymbol)) As ImmutableArray(Of LocalDefinition) Dim builder = ArrayBuilder(Of LocalDefinition).GetInstance() For Each local In locals Select Case local.DeclarationKind Case LocalDeclarationKind.Constant, LocalDeclarationKind.Static Continue For Case Else Dim def = ToLocalDefinition(local, builder.Count) Debug.Assert(DirectCast(local, EELocalSymbol).Ordinal = def.SlotIndex) builder.Add(def) End Select Next Return builder.ToImmutableAndFree() End Function Private Shared Function ToLocalDefinition(local As LocalSymbol, index As Integer) As LocalDefinition Dim constraints = If(local.IsPinned, LocalSlotConstraints.Pinned, LocalSlotConstraints.None) Or If(local.IsByRef, LocalSlotConstraints.ByRef, LocalSlotConstraints.None) Return New LocalDefinition( local, local.Name, DirectCast(local.Type, ITypeReference), slot:=index, synthesizedKind:=local.SynthesizedKind, id:=Nothing, pdbAttributes:=LocalVariableAttributes.None, constraints:=constraints, dynamicTransformFlags:=ImmutableArray(Of TypedConstant).Empty, tupleElementNames:=ImmutableArray(Of TypedConstant).Empty) End Function Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Get Return False End Get End Property Private NotInheritable Class SlotAllocator Inherits VariableSlotAllocator Private ReadOnly _locals As ImmutableArray(Of LocalDefinition) Friend Sub New(locals As ImmutableArray(Of LocalDefinition)) _locals = locals End Sub Public Overrides Sub AddPreviousLocals(builder As ArrayBuilder(Of ILocalDefinition)) builder.AddRange(_locals) End Sub Public Overrides Function GetPreviousLocal( type As ITypeReference, symbol As ILocalSymbolInternal, nameOpt As String, synthesizedKind As SynthesizedLocalKind, id As LocalDebugId, pdbAttributes As LocalVariableAttributes, constraints As LocalSlotConstraints, dynamicTransformFlags As ImmutableArray(Of TypedConstant), tupleElementNames As ImmutableArray(Of TypedConstant)) As LocalDefinition Dim local = TryCast(symbol, EELocalSymbol) If local Is Nothing Then Return Nothing End If Return _locals(local.Ordinal) End Function Public Overrides ReadOnly Property PreviousHoistedLocalSlotCount As Integer Get Return 0 End Get End Property Public Overrides ReadOnly Property PreviousAwaiterSlotCount As Integer Get Return 0 End Get End Property Public Overrides Function TryGetPreviousHoistedLocalSlotIndex(currentDeclarator As SyntaxNode, currentType As ITypeReference, synthesizedKind As SynthesizedLocalKind, currentId As LocalDebugId, diagnostics As DiagnosticBag, <Out> ByRef slotIndex As Integer) As Boolean slotIndex = -1 Return False End Function Public Overrides Function TryGetPreviousAwaiterSlotIndex(currentType As ITypeReference, diagnostics As DiagnosticBag, <Out> ByRef slotIndex As Integer) As Boolean slotIndex = -1 Return False End Function Public Overrides Function TryGetPreviousClosure(scopeSyntax As SyntaxNode, <Out> ByRef closureId As DebugId) As Boolean closureId = Nothing Return False End Function Public Overrides Function TryGetPreviousLambda(lambdaOrLambdaBodySyntax As SyntaxNode, isLambdaBody As Boolean, <Out> ByRef lambdaId As DebugId) As Boolean lambdaId = Nothing Return False End Function Public Overrides ReadOnly Property PreviousStateMachineTypeName As String Get Return Nothing End Get End Property Public Overrides ReadOnly Property MethodId As DebugId? Get Return Nothing End Get End Property End Class End Class End Namespace
weltkante/roslyn
src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/EEAssemblyBuilder.vb
Visual Basic
apache-2.0
8,506
' ' DotNetNuke® - https://www.dnnsoftware.com ' Copyright (c) 2002-2018 ' by DotNetNuke Corporation ' ' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated ' documentation files (the "Software"), to deal in the Software without restriction, including without limitation ' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and ' to permit persons to whom the Software is furnished to do so, subject to the following conditions: ' ' The above copyright notice and this permission notice shall be included in all copies or substantial portions ' of the Software. ' ' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED ' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF ' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ' DEALINGS IN THE SOFTWARE. ' Imports System.Web 'Copied from DotNetNuke Core Namespace DotNetNuke.UI.Utilities Public Class DataCache Public Shared Function GetCache(ByVal CacheKey As String) As Object Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache Return objCache(CacheKey) End Function Public Shared Sub SetCache(ByVal CacheKey As String, ByVal objObject As Object) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache objCache.Insert(CacheKey, objObject) End Sub Public Shared Sub SetCache(ByVal CacheKey As String, ByVal objObject As Object, ByVal objDependency As System.Web.Caching.CacheDependency) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache objCache.Insert(CacheKey, objObject, objDependency) End Sub Public Shared Sub SetCache(ByVal CacheKey As String, ByVal objObject As Object, ByVal objDependency As System.Web.Caching.CacheDependency, ByVal AbsoluteExpiration As Date, ByVal SlidingExpiration As System.TimeSpan) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache objCache.Insert(CacheKey, objObject, objDependency, AbsoluteExpiration, SlidingExpiration) End Sub Public Shared Sub SetCache(ByVal CacheKey As String, ByVal objObject As Object, ByVal SlidingExpiration As Integer) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache objCache.Insert(CacheKey, objObject, Nothing, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(SlidingExpiration)) End Sub Public Shared Sub SetCache(ByVal CacheKey As String, ByVal objObject As Object, ByVal AbsoluteExpiration As Date) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache objCache.Insert(CacheKey, objObject, Nothing, AbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration) End Sub Public Shared Sub RemoveCache(ByVal CacheKey As String) Dim objCache As System.Web.Caching.Cache = HttpRuntime.Cache If Not objCache(CacheKey) Is Nothing Then objCache.Remove(CacheKey) End If End Sub End Class End Namespace
RichardHowells/Dnn.Platform
DNN Platform/DotNetNuke.WebUtility/DataCache.vb
Visual Basic
mit
3,288
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Imports System.Runtime.InteropServices Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Enum GeneratedNameKind None = 0 HoistedMeField HoistedSynthesizedLocalField HoistedUserVariableField IteratorCurrentField IteratorInitialThreadIdField IteratorParameterProxyField StateMachineAwaiterField StateMachineStateField StateMachineHoistedUserVariableField StaticLocalField TransparentIdentifier AnonymousTransparentIdentifier AnonymousType LambdaCacheField LambdaDisplayClass End Enum End Namespace
CyrusNajmabadi/roslyn
src/Compilers/VisualBasic/Portable/Symbols/SynthesizedSymbols/GeneratedNameKind.vb
Visual Basic
mit
878
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.FullyQualify Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.FullyQualify Public Class FullyQualifyTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicFullyQualifyCodeFixProvider()) End Function Protected Overrides Function MassageActions(actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction) Return FlattenActions(actions) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestParameterType() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String(), f As [|FileMode|]) End Sub End Module", "Module Program Sub Main(args As String(), f As System.IO.FileMode) End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestSimpleQualifyFromSameFile() As Task Await TestInRegularAndScriptAsync( "Class Class1 Dim v As [|SomeClass1|] End Class Namespace SomeNamespace Public Class SomeClass1 End Class End Namespace", "Class Class1 Dim v As SomeNamespace.SomeClass1 End Class Namespace SomeNamespace Public Class SomeClass1 End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestOrdering() As Task Dim code = " namespace System.Windows.Controls public class TextBox end class end namespace namespace System.Windows.Forms public class TextBox end class end namespace namespace System.Windows.Forms.VisualStyles.VisualStyleElement public class TextBox end class end namespace Public Class TextBoxEx Inherits [|TextBox|] End Class" Await TestExactActionSetOfferedAsync( code, {"System.Windows.Controls.TextBox", "System.Windows.Forms.TextBox", "System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox"}) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestSimpleQualifyFromReference() As Task Await TestInRegularAndScriptAsync( "Class Class1 Dim v As [|Thread|] End Class", "Class Class1 Dim v As System.Threading.Thread End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericClassDefinitionAsClause() As Task Await TestInRegularAndScriptAsync( "Namespace SomeNamespace Class Base End Class End Namespace Class SomeClass(Of x As [|Base|]) End Class", "Namespace SomeNamespace Class Base End Class End Namespace Class SomeClass(Of x As SomeNamespace.Base) End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericClassInstantiationOfClause() As Task Await TestInRegularAndScriptAsync( "Namespace SomeNamespace Class SomeClass End Class End Namespace Class GenericClass(Of T) End Class Class Goo Sub Method1() Dim q As GenericClass(Of [|SomeClass|]) End Sub End Class", "Namespace SomeNamespace Class SomeClass End Class End Namespace Class GenericClass(Of T) End Class Class Goo Sub Method1() Dim q As GenericClass(Of SomeNamespace.SomeClass) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericMethodDefinitionAsClause() As Task Await TestInRegularAndScriptAsync( "Namespace SomeNamespace Class SomeClass End Class End Namespace Class Goo Sub Method1(Of T As [|SomeClass|]) End Sub End Class", "Namespace SomeNamespace Class SomeClass End Class End Namespace Class Goo Sub Method1(Of T As SomeNamespace.SomeClass) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericMethodInvocationOfClause() As Task Await TestInRegularAndScriptAsync( "Namespace SomeNamespace Class SomeClass End Class End Namespace Class Goo Sub Method1(Of T) End Sub Sub Method2() Method1(Of [|SomeClass|]) End Sub End Class", "Namespace SomeNamespace Class SomeClass End Class End Namespace Class Goo Sub Method1(Of T) End Sub Sub Method2() Method1(Of SomeNamespace.SomeClass) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestAttributeApplication() As Task Await TestInRegularAndScriptAsync( "<[|Something|]()> Class Goo End Class Namespace SomeNamespace Class SomethingAttribute Inherits System.Attribute End Class End Namespace", "<SomeNamespace.Something()> Class Goo End Class Namespace SomeNamespace Class SomethingAttribute Inherits System.Attribute End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestMultipleAttributeApplicationBelow() As Task Await TestInRegularAndScriptAsync( "Imports System <Existing()> <[|Something|]()> Class Goo End Class Class ExistingAttribute Inherits System.Attribute End Class Namespace SomeNamespace Class SomethingAttribute Inherits Attribute End Class End Namespace", "Imports System <Existing()> <SomeNamespace.Something()> Class Goo End Class Class ExistingAttribute Inherits System.Attribute End Class Namespace SomeNamespace Class SomethingAttribute Inherits Attribute End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestMultipleAttributeApplicationAbove() As Task Await TestInRegularAndScriptAsync( "<[|Something|]()> <Existing()> Class Goo End Class Class ExistingAttribute Inherits System.Attribute End Class Namespace SomeNamespace Class SomethingAttribute Inherits System.Attribute End Class End Namespace", "<SomeNamespace.Something()> <Existing()> Class Goo End Class Class ExistingAttribute Inherits System.Attribute End Class Namespace SomeNamespace Class SomethingAttribute Inherits System.Attribute End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestQualifierIsEscapedWhenNamespaceMatchesKeyword() As Task Await TestInRegularAndScriptAsync( "Class SomeClass Dim x As [|Something|] End Class Namespace [Namespace] Class Something End Class End Namespace", "Class SomeClass Dim x As [Namespace].Something End Class Namespace [Namespace] Class Something End Class End Namespace") End Function <WorkItem(540559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540559")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestQualifierIsNOTEscapedWhenNamespaceMatchesKeywordButIsNested() As Task Await TestInRegularAndScriptAsync( "Class SomeClass Dim x As [|Something|] End Class Namespace Outer Namespace [Namespace] Class Something End Class End Namespace End Namespace", "Class SomeClass Dim x As Outer.Namespace.Something End Class Namespace Outer Namespace [Namespace] Class Something End Class End Namespace End Namespace") End Function <WorkItem(540560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540560")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestFullyQualifyInImportsStatement() As Task Await TestInRegularAndScriptAsync( "Imports [|InnerNamespace|] Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace", "Imports SomeNamespace.InnerNamespace Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestFullyQualifyNotSuggestedForGenericTypeParametersOfClause() As Task Await TestMissingInRegularAndScriptAsync( "Class SomeClass Sub Goo(Of [|SomeClass|])(x As SomeClass) End Sub End Class Namespace SomeNamespace Class SomeClass End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestFullyQualifyNotSuggestedForGenericTypeParametersAsClause() As Task Await TestMissingInRegularAndScriptAsync( "Class SomeClass Sub Goo(Of SomeClass)(x As [|SomeClass|]) End Sub End Class Namespace SomeNamespace Class SomeClass End Class End Namespace") End Function <WorkItem(540673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540673")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestCaseSensitivityForNestedNamespace() As Task Await TestInRegularAndScriptAsync( "Class Goo Sub bar() Dim q As [|innernamespace|].someClass End Sub End Class Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace", "Class Goo Sub bar() Dim q As SomeNamespace.InnerNamespace.someClass End Sub End Class Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace") End Function <WorkItem(540543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540543")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestCaseSensitivity1() As Task Await TestInRegularAndScriptAsync( "Class Goo Dim x As [|someclass|] End Class Namespace SomeNamespace Class SomeClass End Class End Namespace", "Class Goo Dim x As SomeNamespace.SomeClass End Class Namespace SomeNamespace Class SomeClass End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestTypeFromMultipleNamespaces1() As Task Await TestInRegularAndScriptAsync( "Class Goo Function F() As [|IDictionary|] End Function End Class", "Class Goo Function F() As System.Collections.IDictionary End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestTypeFromMultipleNamespaces2() As Task Await TestInRegularAndScriptAsync( "Class Goo Function F() As [|IDictionary|] End Function End Class", "Class Goo Function F() As System.Collections.Generic.IDictionary End Function End Class", index:=1) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericWithNoArgs() As Task Await TestInRegularAndScriptAsync( "Class Goo Function F() As [|List|] End Function End Class", "Class Goo Function F() As System.Collections.Generic.List End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericWithCorrectArgs() As Task Await TestInRegularAndScriptAsync( "Class Goo Function F() As [|List(Of Integer)|] End Function End Class", "Class Goo Function F() As System.Collections.Generic.List(Of Integer) End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericWithWrongArgs() As Task Await TestMissingInRegularAndScriptAsync( "Class Goo Function F() As [|List(Of Integer, String)|] End Function End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericInLocalDeclaration() As Task Await TestInRegularAndScriptAsync( "Class Goo Sub Test() Dim x As New [|List(Of Integer)|] End Sub End Class", "Class Goo Sub Test() Dim x As New System.Collections.Generic.List(Of Integer) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenericItemType() As Task Await TestInRegularAndScriptAsync( "Class Goo Sub Test() Dim x As New List(Of [|Int32|]) End Sub End Class", "Class Goo Sub Test() Dim x As New List(Of System.Int32) End Sub End Class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestGenerateInNamespace() As Task Await TestInRegularAndScriptAsync( "Imports System Namespace NS Class Goo Sub Test() Dim x As New [|List(Of Integer)|] End Sub End Class End Namespace", "Imports System Namespace NS Class Goo Sub Test() Dim x As New Collections.Generic.List(Of Integer) End Sub End Class End Namespace") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestMinimalQualify() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Dim q As [|List(Of Integer)|] End Module", "Imports System Module Program Dim q As Collections.Generic.List(Of Integer) End Module") End Function <WorkItem(540559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540559")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestEscaping1() As Task Await TestInRegularAndScriptAsync( "Class SomeClass Dim x As [|Something|] End Class Namespace Outer Namespace [Namespace] Class Something End Class End Namespace End Namespace", "Class SomeClass Dim x As Outer.Namespace.Something End Class Namespace Outer Namespace [Namespace] Class Something End Class End Namespace End Namespace") End Function <WorkItem(540559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540559")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestEscaping2() As Task Await TestInRegularAndScriptAsync( "Class SomeClass Dim x As [|Something|] End Class Namespace [Namespace] Namespace Inner Class Something End Class End Namespace End Namespace", "Class SomeClass Dim x As [Namespace].Inner.Something End Class Namespace [Namespace] Namespace Inner Class Something End Class End Namespace End Namespace") End Function <WorkItem(540559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540559")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestEscaping3() As Task Await TestInRegularAndScriptAsync( "Class SomeClass Dim x As [|[Namespace]|] End Class Namespace Outer Namespace Inner Class [Namespace] End Class End Namespace End Namespace", "Class SomeClass Dim x As Outer.Inner.[Namespace] End Class Namespace Outer Namespace Inner Class [Namespace] End Class End Namespace End Namespace") End Function <WorkItem(540560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540560")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestInImport() As Task Await TestInRegularAndScriptAsync( "Imports [|InnerNamespace|] Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace", "Imports SomeNamespace.InnerNamespace Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace") End Function <WorkItem(540673, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540673")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestCaseInsensitivity() As Task Await TestInRegularAndScriptAsync( "Class GOo Sub bar() Dim q As [|innernamespace|].someClass End Sub End Class Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace", "Class GOo Sub bar() Dim q As SomeNamespace.InnerNamespace.someClass End Sub End Class Namespace SomeNamespace Namespace InnerNamespace Class SomeClass End Class End Namespace End Namespace") End Function <WorkItem(540706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540706")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestStandaloneMethod() As Task Await TestInRegularAndScriptAsync( "'Class [Class] Private Sub Method(i As Integer) [|[Enum]|] = 5 End Sub End Class", "'Class [Class] Private Sub Method(i As Integer) System.[Enum] = 5 End Sub End Class") End Function <WorkItem(540736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540736")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestMissingOnBoundFieldType() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Collections.Generic Class A Private field As [|List(Of C)|] Sub Main() Dim local As List(Of C) End Sub End Class") End Function <WorkItem(540736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540736")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestMissingOnBoundLocalType() As Task Await TestMissingInRegularAndScriptAsync( "Imports System.Collections.Generic Class A Private field As [|List(Of C)|] Sub Main() Dim local As List(Of C) End Sub End Class") End Function <WorkItem(540745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540745")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestCaseSensitivity2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As [|goo|] End Sub End Module Namespace OUTER Namespace INNER Friend Class GOO End Class End Namespace End Namespace", "Module Program Sub Main(args As String()) Dim x As OUTER.INNER.GOO End Sub End Module Namespace OUTER Namespace INNER Friend Class GOO End Class End Namespace End Namespace") End Function <WorkItem(821292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/821292")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestCaseSensitivity3() As Task Await TestInRegularAndScriptAsync( "Imports System Module Program Sub Main(args As String()) Dim x As [|stream|] End Sub End Module", "Imports System Module Program Sub Main(args As String()) Dim x As IO.Stream End Sub End Module") End Function <WorkItem(545993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545993")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestNotOnNamedArgument() As Task Await TestMissingInRegularAndScriptAsync( "Module Program <MethodImpl([|methodImplOptions|]:=MethodImplOptions.ForwardRef) Sub Main(args As String()) End Sub End Module") End Function <WorkItem(546107, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546107")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestDoNotQualifyNestedTypeOfGenericType() As Task Await TestMissingInRegularAndScriptAsync( "Imports System Imports System.Collections.Generic Class Program Shared Sub Main() CType(GetEnumerator(), IDisposable).Dispose() End Sub Shared Function GetEnumerator() As [|Enumerator|] Return Nothing End Function End Class") End Function <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestFormattingInFullyQualify() As Task Await TestInRegularAndScriptAsync( <Text>Module Program &lt;[|Obsolete|]&gt; Sub Main(args As String()) End Sub End Module</Text>.Value.Replace(vbLf, vbCrLf), <Text>Module Program &lt;System.Obsolete&gt; Sub Main(args As String()) End Sub End Module</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestShouldTriggerOnBC32045() As Task ' BC32045: 'A' has no type parameters and so cannot have type arguments. Await TestInRegularAndScriptAsync( <Text>Imports System.Collections Module Program Sub Main(args As String()) Dim x As [|IEnumerable(Of Integer)|] End Sub End Module</Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports System.Collections Module Program Sub Main(args As String()) Dim x As Generic.IEnumerable(Of Integer) End Sub End Module</Text>.Value.Replace(vbLf, vbCrLf)) End Function <WorkItem(947579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/947579")> <Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsFullyQualify)> Public Async Function TestAmbiguousTypeFix() As Task Await TestInRegularAndScriptAsync( <Text>Imports N1 Imports N2 Module Program Sub M1() [|Dim a As A|] End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace</Text>.Value.Replace(vbLf, vbCrLf), <Text>Imports N1 Imports N2 Module Program Sub M1() Dim a As N1.A End Sub End Module Namespace N1 Class A End Class End Namespace Namespace N2 Class A End Class End Namespace</Text>.Value.Replace(vbLf, vbCrLf)) End Function Public Class AddImportTestsWithAddImportDiagnosticProvider Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (New VisualBasicUnboundIdentifiersDiagnosticAnalyzer(), New VisualBasicFullyQualifyCodeFixProvider()) End Function <WorkItem(829970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/829970")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)> Public Async Function TestUnknownIdentifierInAttributeSyntaxWithoutTarget() As Task Await TestInRegularAndScriptAsync( "Module Program <[|Extension|]> End Module", "Module Program <System.Runtime.CompilerServices.Extension> End Module") End Function End Class End Class End Namespace
physhi/roslyn
src/EditorFeatures/VisualBasicTest/Diagnostics/FullyQualify/FullyQualifyTests.vb
Visual Basic
apache-2.0
24,971
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.ComponentModel.Composition.Hosting Imports System.Xml.Linq Imports Microsoft.CodeAnalysis.Editor.UnitTests.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Editor.VisualBasic.AutomaticCompletion Imports Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion Imports System.Threading.Tasks Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AutomaticCompletion Public Class AutomaticLessAndGreaterThanCompletionTests Inherits AbstractAutomaticBraceCompletionTests <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestCreation() As Task Using session = Await CreateSessionAsync("$$") Assert.NotNull(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestAttribute_LessThan() As Task Using session = Await CreateSessionAsync("$$") Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_LessThan() As Task Using session = Await CreateSessionAsync("Imports System$$") Assert.NotNull(session) CheckStart(session.Session, expectValidSession:=False) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_String() As Task Dim code = <code>Class C Dim s As String = "$$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_Comment() As Task Dim code = <code>Class C ' $$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestInvalidLocation_DocComment() As Task Dim code = <code>Class C ''' $$ End Class</code> Using session = Await CreateSessionAsync(code) Assert.Null(session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestAttribute_LessThan_Method() As Task Dim code = <code>Class C Sub Method($$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestXmlNamespaceImport_LessThan() As Task Dim code = <code>Imports $$</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) CheckOverType(session.Session) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.AutomaticCompletion)> Public Async Function TestBracketName_Member() As Task Dim code = <code>Class C Sub Method() Dim a = &lt;start&gt;&lt;/start&gt; a.$$ End Sub End Class</code> Using session = Await CreateSessionAsync(code) Assert.NotNull(session) CheckStart(session.Session) End Using End Function Friend Overloads Function CreateSessionAsync(code As XElement) As Threading.Tasks.Task(Of Holder) Return CreateSessionAsync(code.NormalizedValue()) End Function Friend Overloads Async Function CreateSessionAsync(code As String) As Threading.Tasks.Task(Of Holder) Return CreateSession( Await TestWorkspace.CreateVisualBasicAsync(code), BraceCompletionSessionProvider.LessAndGreaterThan.OpenCharacter, BraceCompletionSessionProvider.LessAndGreaterThan.CloseCharacter) End Function End Class End Namespace
ericfe-ms/roslyn
src/EditorFeatures/VisualBasicTest/AutomaticCompletion/AutomaticLessAndGreaterThanCompletionTests.vb
Visual Basic
apache-2.0
4,795
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.IO Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.SpecialType Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics.ConversionsTests.Parameters Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class ConversionsTests Inherits BasicTestBase Private Shared ReadOnly s_noConversion As ConversionKind = Nothing <Fact()> Public Sub TryCastDirectCastConversions() Dim dummyCode = <file> Class C1 Shared Sub MethodDecl() End Sub End Class </file> Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value) ' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is ' checked in next to the DLL. Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef}) Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol) Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol) Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol) Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef) Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef) Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single() Dim m13 = DirectCast(test.GetMembers("M13").Single(), MethodSymbol) Dim m13p = m13.Parameters.Select(Function(p) p.Type).ToArray() Assert.Equal(ConversionKind.WideningReference, ClassifyDirectCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object) Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object) Assert.Equal(ConversionKind.NarrowingReference, ClassifyDirectCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType) Assert.Equal(ConversionKind.WideningValue, ClassifyDirectCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType) Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer) Assert.Equal(ConversionKind.NarrowingValue, ClassifyDirectCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer) Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), m13p(c), methodBodyBinder))) ' Integer) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'. Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer) Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), m13p(d), methodBodyBinder))) ' Long) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) 'error BC30311: Value of type 'Integer' cannot be converted to 'Long'. Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(e), m13p(e), methodBodyBinder))) ' Enum1) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) 'error BC30311: Value of type 'Enum2' cannot be converted to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1) Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(f), m13p(f), methodBodyBinder))) ' Enum2) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30311: Value of type 'Enum4' cannot be converted to 'Enum2'. Assert.Equal(ConversionKind.WideningArray, ClassifyDirectCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8()) Assert.Equal(ConversionKind.NarrowingArray, ClassifyDirectCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9()) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'. Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(k), m13p(k), methodBodyBinder))) ' MT1) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT2' cannot be converted to 'MT1'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30311: Value of type 'MT4' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' Value of type 'MT1' cannot be converted to 'MT2'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyDirectCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1()) ' Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '2-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1()) ' error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT1' because 'Integer' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'MT1' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'System.ValueType' cannot be converted Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4) ' error BC30311: Value of type 'Integer' cannot be converted to 'MT4' Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT6'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyDirectCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT5' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of Integer' because 'MT1' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'. Dim [nothing] = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing) Dim intZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0I), m13p(c)) Dim longZero = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Create(0L), m13p(d)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(a), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(b), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(c), [nothing], methodBodyBinder)) Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(c), intZero, methodBodyBinder))) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(c), longZero, methodBodyBinder)) 'error BC30311: Value of type 'Long' cannot be converted to 'Integer'. Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30311: Value of type 'Integer' cannot be converted to 'Long'. Assert.True(Conversions.IsIdentityConversion(ClassifyDirectCastAssignment(m13p(d), longZero, methodBodyBinder))) Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyDirectCastAssignment(m13p(e), intZero, methodBodyBinder)) Assert.Equal(s_noConversion, ClassifyDirectCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30311: Value of type 'Long' cannot be converted to 'Enum1'. Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(e), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(k), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyDirectCastAssignment(m13p(q), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningReference, ClassifyTryCastAssignment(m13p(a), m13p(b), methodBodyBinder)) ' Object) Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), m13p(c), methodBodyBinder)) ' Object) Assert.Equal(ConversionKind.NarrowingReference, ClassifyTryCastAssignment(m13p(b), m13p(a), methodBodyBinder)) ' ValueType) Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(b), m13p(c), methodBodyBinder)) ' ValueType) Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(a), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(ConversionKind.NarrowingValue, ClassifyTryCastAssignment(m13p(c), m13p(b), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), m13p(c), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(c), m13p(d), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(c), m13p(e), methodBodyBinder)) ' Integer) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), m13p(d), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(d), m13p(c), methodBodyBinder)) ' Long) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(e), m13p(e), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(e), m13p(f), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), m13p(g), methodBodyBinder)) ' Enum1) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(f), m13p(f), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(f), m13p(g), methodBodyBinder)) ' Enum2) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum2' is a value type. Assert.Equal(ConversionKind.WideningArray, ClassifyTryCastAssignment(m13p(h), m13p(i), methodBodyBinder)) ' Class8()) Assert.Equal(ConversionKind.NarrowingArray, ClassifyTryCastAssignment(m13p(i), m13p(h), methodBodyBinder)) ' Class9()) Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(i), m13p(j), methodBodyBinder)) ' Class9()) ' error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(k), m13p(k), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint. Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(l), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(k), m13p(m), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint. Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(k), m13p(q), methodBodyBinder)) ' MT1) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint. Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(l), m13p(k), methodBodyBinder)) ' MT2) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT2' has no class constraint. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyTryCastAssignment(m13p(m), m13p(k), methodBodyBinder)) ' MT3) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT3' has no class constraint. Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(o), methodBodyBinder)) ' MT1()) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(p), methodBodyBinder)) ' MT1()) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(n), m13p(u), methodBodyBinder)) ' MT1()) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(k), methodBodyBinder)) ' MT4) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(b), methodBodyBinder)) ' MT4) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(q), m13p(c), methodBodyBinder)) ' MT4) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(s), methodBodyBinder)) ' MT5) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(t), methodBodyBinder)) ' MT5) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(r), m13p(w), methodBodyBinder)) ' MT5) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(s), m13p(r), methodBodyBinder)) ' MT6) Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(s), m13p(t), methodBodyBinder)) ' MT6) ' error BC30311: Value of type 'MT7' cannot be converted to 'MT6'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyTryCastAssignment(m13p(s), m13p(w), methodBodyBinder)) ' MT6) Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(t), m13p(r), methodBodyBinder)) ' MT7) Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(t), m13p(s), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT6' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(t), m13p(w), methodBodyBinder)) ' MT7) ' error BC30311: Value of type 'MT8' cannot be converted to 'MT7'. Assert.Equal(ConversionKind.Narrowing, ClassifyTryCastAssignment(m13p(u), m13p(n), methodBodyBinder)) ' Integer()) Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(u), m13p(v), methodBodyBinder)) ' Integer()) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of Integer' because 'MT4' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(v), m13p(u), methodBodyBinder)) ' MT4()) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of MT4' because 'Integer' is not derived from 'MT4'. Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(a), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningValue, ClassifyTryCastAssignment(m13p(a), intZero, methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(b), [nothing], methodBodyBinder)) Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(c), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(c), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(c), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Integer' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(d), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type. Assert.Equal(ConversionKind.Identity, ClassifyTryCastAssignment(m13p(d), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Long' is a value type. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyTryCastAssignment(m13p(e), intZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(s_noConversion, ClassifyTryCastAssignment(m13p(e), longZero, methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(e), [nothing], methodBodyBinder)) ' error BC30792: 'TryCast' operand must be reference type, but 'Enum1' is a value type. Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(k), [nothing], methodBodyBinder)) ' error BC30793: 'TryCast' operands must be class-constrained type parameter, but 'MT1' has no class constraint. Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyTryCastAssignment(m13p(q), [nothing], methodBodyBinder)) End Sub Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime Return result End Function Private Shared Function ClassifyDirectCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind Dim result As ConversionKind = Conversions.ClassifyDirectCastConversion([from], [to], binder, Nothing) Return result End Function Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As TypeSymbol, binder As Binder) As ConversionKind Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], Nothing) Return result End Function Private Shared Function ClassifyTryCastAssignment([to] As TypeSymbol, [from] As BoundLiteral, binder As Binder) As ConversionKind Dim result As ConversionKind = Conversions.ClassifyTryCastConversion([from], [to], binder, Nothing) Return result End Function Private Shared Function ClassifyConversion(source As TypeSymbol, destination As TypeSymbol) As ConversionKind Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, Nothing) Assert.Null(result.Value) Return result.Key End Function Private Shared Function ClassifyConversion(source As BoundExpression, destination As TypeSymbol, binder As Binder) As ConversionKind Dim result As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(source, destination, binder, Nothing) Assert.Null(result.Value) Return result.Key End Function <Fact()> Public Sub ConstantExpressionConversions() Dim dummyCode = <file> Class C1 Shared Sub MethodDecl() End Sub End Class </file> Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value) Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib}) Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol) Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol) Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol) Assert.True(c1.Options.CheckOverflow) Dim objectType = c1.GetSpecialType(System_Object) Dim booleanType = c1.GetSpecialType(System_Boolean) Dim byteType = c1.GetSpecialType(System_Byte) Dim sbyteType = c1.GetSpecialType(System_SByte) Dim int16Type = c1.GetSpecialType(System_Int16) Dim uint16Type = c1.GetSpecialType(System_UInt16) Dim int32Type = c1.GetSpecialType(System_Int32) Dim uint32Type = c1.GetSpecialType(System_UInt32) Dim int64Type = c1.GetSpecialType(System_Int64) Dim uint64Type = c1.GetSpecialType(System_UInt64) Dim doubleType = c1.GetSpecialType(System_Double) Dim singleType = c1.GetSpecialType(System_Single) Dim decimalType = c1.GetSpecialType(System_Decimal) Dim dateType = c1.GetSpecialType(System_DateTime) Dim stringType = c1.GetSpecialType(System_String) Dim charType = c1.GetSpecialType(System_Char) Dim intPtrType = c1.GetSpecialType(System_IntPtr) Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single() Dim allTestTypes = New TypeSymbol() { objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType, stringType, charType, intPtrType, typeCodeType} Dim convertibleTypes = New HashSet(Of TypeSymbol)({ booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType, stringType, charType, typeCodeType}) Dim integralTypes = New HashSet(Of TypeSymbol)({ byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType}) Dim unsignedTypes = New HashSet(Of TypeSymbol)({ byteType, uint16Type, uint32Type, uint64Type}) Dim numericTypes = New HashSet(Of TypeSymbol)({ byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType}) Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType}) ' -------------- NOTHING literal conversions Dim _nothing = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing) Dim resultValue As ConstantValue Dim integerOverflow As Boolean Dim literal As BoundExpression Dim constant As BoundConversion For Each testType In allTestTypes Assert.Equal(ConversionKind.WideningNothingLiteral, ClassifyConversion(_nothing, testType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(_nothing, testType, integerOverflow) If convertibleTypes.Contains(testType) Then Assert.NotNull(resultValue) Assert.Equal(If(testType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, testType.GetConstantValueTypeDiscriminator()), resultValue.Discriminator) If testType IsNot dateType Then Assert.Equal(0, Convert.ToInt64(resultValue.Value)) If testType Is stringType Then Assert.Null(resultValue.StringValue) End If Else Assert.Equal(New DateTime(), resultValue.DateTimeValue) End If Else Assert.Null(resultValue) End If Assert.False(integerOverflow) If resultValue IsNot Nothing Then Assert.False(resultValue.IsBad) End If Next ' -------------- integer literal zero to enum conversions For Each integralType In integralTypes Dim zero = ConstantValue.Default(integralType.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), zero, integralType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), literal, ConversionKind.Widening, True, True, zero, integralType, Nothing) Assert.Equal(If(integralType Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions)), ClassifyConversion(literal, typeCodeType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator) Assert.Equal(0, resultValue.Int32Value) Assert.Equal(If(integralType Is typeCodeType, ConversionKind.Identity, ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions), ClassifyConversion(constant, typeCodeType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(constant, typeCodeType, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator) Assert.Equal(0, resultValue.Int32Value) Next For Each convertibleType In convertibleTypes If Not integralTypes.Contains(convertibleType) Then Dim zero = ConstantValue.Default(If(convertibleType.IsStringType(), ConstantValueTypeDiscriminator.Nothing, convertibleType.GetConstantValueTypeDiscriminator())) If convertibleType.IsStringType() Then literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, convertibleType, Nothing) Else literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, convertibleType) End If Assert.Equal(ClassifyConversion(convertibleType, typeCodeType), ClassifyConversion(literal, typeCodeType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, typeCodeType, integerOverflow) If Not numericTypes.Contains(convertibleType) AndAlso convertibleType IsNot booleanType Then Assert.Null(resultValue) Assert.False(integerOverflow) Else Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.Equal(ConstantValueTypeDiscriminator.Int32, resultValue.Discriminator) Assert.Equal(0, resultValue.Int32Value) End If End If Next ' -------------- Numeric conversions Dim nullableType = c1.GetSpecialType(System_Nullable_T) ' Zero For Each type1 In convertibleTypes Dim zero = ConstantValue.Default(If(type1.IsStringType(), ConstantValueTypeDiscriminator.Nothing, type1.GetConstantValueTypeDiscriminator())) If type1.IsStringType() Then literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.WideningNothingLiteral, False, True, zero, type1, Nothing) Else literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), zero, type1) End If constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type), ConversionKind.Widening, True, True, zero, type1, Nothing) For Each type2 In allTestTypes Dim expectedConv As ConversionKind If numericTypes.Contains(type1) AndAlso numericTypes.Contains(type2) Then If type1 Is type2 Then expectedConv = ConversionKind.Identity ElseIf type1.IsEnumType() Then expectedConv = ClassifyConversion(type1.GetEnumUnderlyingTypeOrSelf(), type2) If Conversions.IsWideningConversion(expectedConv) Then expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions If (expectedConv And ConversionKind.Identity) <> 0 Then expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Widening Or ConversionKind.Numeric End If ElseIf Conversions.IsNarrowingConversion(expectedConv) Then expectedConv = expectedConv Or ConversionKind.InvolvesEnumTypeConversions End If ElseIf type2.IsEnumType() Then expectedConv = ClassifyConversion(type1, type2.GetEnumUnderlyingTypeOrSelf()) If Not Conversions.NoConversion(expectedConv) Then expectedConv = (expectedConv And Not ConversionKind.Widening) Or ConversionKind.Narrowing Or ConversionKind.InvolvesEnumTypeConversions If (expectedConv And ConversionKind.Identity) <> 0 Then expectedConv = (expectedConv And Not ConversionKind.Identity) Or ConversionKind.Numeric End If End If ElseIf integralTypes.Contains(type2) Then If integralTypes.Contains(type1) Then If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then expectedConv = ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant Else expectedConv = ConversionKind.WideningNumeric End If Else expectedConv = ConversionKind.NarrowingNumeric End If ElseIf floatingTypes.Contains(type2) Then If Conversions.IsNarrowingConversion(ClassifyConversion(type1, type2)) Then expectedConv = ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant Else expectedConv = ConversionKind.WideningNumeric End If Else Assert.Same(decimalType, type2) expectedConv = ClassifyConversion(type1, type2) End If Assert.Equal(If(type2.IsEnumType() AndAlso type1 Is int32Type, ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, expectedConv), ClassifyConversion(literal, type2, methodBodyBinder)) Assert.Equal(expectedConv, ClassifyConversion(constant, type2, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal(0, Convert.ToDouble(resultValue.Value)) resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal(0, Convert.ToDouble(resultValue.Value)) Dim nullableType2 = nullableType.Construct(type2) expectedConv = ClassifyConversion(type1, nullableType2) Or (expectedConv And ConversionKind.InvolvesNarrowingFromNumericConstant) If type2.IsEnumType() AndAlso type1.SpecialType = SpecialType.System_Int32 Then Assert.Equal(expectedConv Or ConversionKind.InvolvesNarrowingFromNumericConstant, ClassifyConversion(literal, nullableType2, methodBodyBinder)) Else Assert.Equal(expectedConv, ClassifyConversion(literal, nullableType2, methodBodyBinder)) End If Assert.Equal(expectedConv, ClassifyConversion(constant, nullableType2, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) ElseIf type1 Is booleanType AndAlso numericTypes.Contains(type2) Then ' Will test separately Continue For ElseIf type2 Is booleanType AndAlso numericTypes.Contains(type1) Then Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(literal, type2, methodBodyBinder)) Assert.Equal(If(type1 Is typeCodeType, ConversionKind.NarrowingBoolean Or ConversionKind.InvolvesEnumTypeConversions, ConversionKind.NarrowingBoolean), ClassifyConversion(constant, type2, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.False(DirectCast(resultValue.Value, Boolean)) resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(type2.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.False(DirectCast(resultValue.Value, Boolean)) ElseIf type1 Is stringType AndAlso type2 Is charType Then ' Will test separately Continue For ElseIf type1 Is charType AndAlso type2 Is stringType Then ' Will test separately Continue For ElseIf type2 Is typeCodeType AndAlso integralTypes.Contains(type1) Then ' Already tested Continue For ElseIf (type1 Is dateType AndAlso type2 Is dateType) OrElse (type1 Is booleanType AndAlso type2 Is booleanType) OrElse (type1 Is stringType AndAlso type2 Is stringType) OrElse (type1 Is charType AndAlso type2 Is charType) Then Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(literal, type2, methodBodyBinder))) Assert.True(Conversions.IsIdentityConversion(ClassifyConversion(constant, type2, methodBodyBinder))) resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.True(type2.IsValidForConstantValue(resultValue)) Assert.Equal(literal.ConstantValueOpt, resultValue) resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.True(type2.IsValidForConstantValue(resultValue)) Assert.Equal(constant.ConstantValueOpt, resultValue) Else Dim expectedConv1 As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(type1, type2, Nothing) Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, type2, methodBodyBinder, Nothing)) Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, type2, methodBodyBinder, Nothing)) resultValue = Conversions.TryFoldConstantConversion(literal, type2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) resultValue = Conversions.TryFoldConstantConversion(constant, type2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) If type2.IsValueType Then Dim nullableType2 = nullableType.Construct(type2) expectedConv1 = Conversions.ClassifyConversion(type1, nullableType2, Nothing) Assert.Equal(expectedConv1, Conversions.ClassifyConversion(literal, nullableType2, methodBodyBinder, Nothing)) Assert.Equal(expectedConv1, Conversions.ClassifyConversion(constant, nullableType2, methodBodyBinder, Nothing)) resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) End If End If Next Next ' -------- Numeric non-zero values Dim nonZeroValues = New TypeAndValue() { New TypeAndValue(sbyteType, SByte.MinValue), New TypeAndValue(int16Type, Int16.MinValue), New TypeAndValue(int32Type, Int32.MinValue), New TypeAndValue(int64Type, Int64.MinValue), New TypeAndValue(doubleType, Double.MinValue), New TypeAndValue(singleType, Single.MinValue), New TypeAndValue(decimalType, Decimal.MinValue), New TypeAndValue(sbyteType, SByte.MaxValue), New TypeAndValue(int16Type, Int16.MaxValue), New TypeAndValue(int32Type, Int32.MaxValue), New TypeAndValue(int64Type, Int64.MaxValue), New TypeAndValue(byteType, Byte.MaxValue), New TypeAndValue(uint16Type, UInt16.MaxValue), New TypeAndValue(uint32Type, UInt32.MaxValue), New TypeAndValue(uint64Type, UInt64.MaxValue), New TypeAndValue(doubleType, Double.MaxValue), New TypeAndValue(singleType, Single.MaxValue), New TypeAndValue(decimalType, Decimal.MaxValue), New TypeAndValue(sbyteType, CSByte(-1)), New TypeAndValue(int16Type, CShort(-2)), New TypeAndValue(int32Type, CInt(-3)), New TypeAndValue(int64Type, CLng(-4)), New TypeAndValue(sbyteType, CSByte(5)), New TypeAndValue(int16Type, CShort(6)), New TypeAndValue(int32Type, CInt(7)), New TypeAndValue(int64Type, CLng(8)), New TypeAndValue(doubleType, CDbl(-9)), New TypeAndValue(singleType, CSng(-10)), New TypeAndValue(decimalType, CDec(-11)), New TypeAndValue(doubleType, CDbl(12)), New TypeAndValue(singleType, CSng(13)), New TypeAndValue(decimalType, CDec(14)), New TypeAndValue(byteType, CByte(15)), New TypeAndValue(uint16Type, CUShort(16)), New TypeAndValue(uint32Type, CUInt(17)), New TypeAndValue(uint64Type, CULng(18)), New TypeAndValue(decimalType, CDec(-11.3)), New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)), New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)), New TypeAndValue(typeCodeType, Int32.MinValue), New TypeAndValue(typeCodeType, Int32.MaxValue), New TypeAndValue(typeCodeType, CInt(-3)), New TypeAndValue(typeCodeType, CInt(7)) } Dim resultValue2 As ConstantValue Dim integerOverflow2 As Boolean For Each mv In nonZeroValues Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator()) Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, v, mv.Type, Nothing) For Each numericType In numericTypes Dim typeConv = ClassifyConversion(mv.Type, numericType) Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder) Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder) Assert.Equal(conv, conv2) resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2) Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue IsNot Nothing AndAlso resultValue.IsBad, resultValue2 IsNot Nothing AndAlso resultValue2.IsBad) If resultValue IsNot Nothing Then Assert.Equal(resultValue2, resultValue) If Not resultValue.IsBad Then Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) End If End If Dim resultValueAsObject As Object = Nothing Dim overflow As Boolean = False Try resultValueAsObject = CheckedConvert(v.Value, numericType) Catch ex As OverflowException overflow = True End Try If Not overflow Then If Conversions.IsIdentityConversion(typeConv) Then Assert.True(Conversions.IsIdentityConversion(conv)) ElseIf Conversions.IsNarrowingConversion(typeConv) Then If mv.Type Is doubleType AndAlso numericType Is singleType Then Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv) ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv) Else Assert.Equal(typeConv, conv) End If ElseIf mv.Type.IsEnumType() Then Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv) Else Assert.Equal(ConversionKind.WideningNumeric, conv) End If Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(resultValueAsObject, resultValue.Value) If mv.Type Is doubleType AndAlso numericType Is singleType Then If v.DoubleValue = Double.MinValue Then Dim min As Single = Double.MinValue Assert.True(Single.IsNegativeInfinity(min)) Assert.Equal(resultValue.SingleValue, min) ElseIf v.DoubleValue = Double.MaxValue Then Dim max As Single = Double.MaxValue Assert.Equal(Double.MaxValue, v.DoubleValue) Assert.True(Single.IsPositiveInfinity(max)) Assert.Equal(resultValue.SingleValue, max) End If End If ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then 'Assert.Equal(typeConv, conv) If integralTypes.Contains(numericType) Then Assert.NotNull(resultValue) If resultValue.IsBad Then Assert.False(integerOverflow) Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv) Else Assert.True(integerOverflow) Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv) Dim intermediate As Object If unsignedTypes.Contains(numericType) Then intermediate = Convert.ToUInt64(mv.Value) Else intermediate = Convert.ToInt64(mv.Value) End If Dim gotException As Boolean Try gotException = False CheckedConvert(intermediate, numericType) ' Should get an overflow Catch x As Exception gotException = True End Try Assert.True(gotException) Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value) End If Else Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.True(resultValue.IsBad) Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv) End If Else ' An integer overflow case Assert.Equal(ConversionKind.FailedDueToIntegerOverflow, conv) Assert.NotNull(resultValue) Assert.True(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value) End If Dim nullableType2 = nullableType.Construct(numericType) Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing) conv = ClassifyConversion(literal, numericType, methodBodyBinder) If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then conv = ClassifyConversion(mv.Type, nullableType2) Or (ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant) End If Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder)) Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) Next Next Dim dbl As Double = -1.5 Dim doubleValue = ConstantValue.Create(dbl) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing) resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(-2, CInt(dbl)) Assert.Equal(-2, DirectCast(resultValue.Value, Int32)) dbl = -2.5 doubleValue = ConstantValue.Create(dbl) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing) resultValue = Conversions.TryFoldConstantConversion(constant, int32Type, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(-2, CInt(dbl)) Assert.Equal(-2, DirectCast(resultValue.Value, Int32)) dbl = 1.5 doubleValue = ConstantValue.Create(dbl) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing) resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(2UI, CUInt(dbl)) Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32)) dbl = 2.5 doubleValue = ConstantValue.Create(dbl) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing) resultValue = Conversions.TryFoldConstantConversion(constant, uint32Type, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(2UI, CUInt(dbl)) Assert.Equal(2UI, DirectCast(resultValue.Value, UInt32)) dbl = 2147483648.0 * 4294967296.0 + 10 doubleValue = ConstantValue.Create(dbl) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, doubleValue, doubleType, Nothing) resultValue = Conversions.TryFoldConstantConversion(constant, uint64Type, integerOverflow) Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(Convert.ToUInt64(dbl), DirectCast(resultValue.Value, UInt64)) ' ------- Boolean Dim falseValue = ConstantValue.Create(False) Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), falseValue, booleanType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, falseValue, booleanType, Nothing) For Each numericType In numericTypes Dim typeConv = ClassifyConversion(booleanType, numericType) Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder) Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder) Assert.Equal(conv, conv2) Assert.Equal(typeConv, conv) resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue.IsBad, resultValue2.IsBad) Assert.Equal(resultValue2, resultValue) Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal(0, Convert.ToInt64(resultValue.Value)) Next Dim trueValue = ConstantValue.Create(True) Assert.Equal(falseValue.Discriminator, booleanType.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), trueValue, booleanType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, trueValue, booleanType, Nothing) For Each numericType In numericTypes Dim typeConv = ClassifyConversion(booleanType, numericType) Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder) Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder) Assert.Equal(conv, conv2) Assert.Equal(typeConv, conv) resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue.IsBad, resultValue2.IsBad) Assert.Equal(resultValue2, resultValue) Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) 'The literal True converts to the literal 255 for Byte, 65535 for UShort, 4294967295 for UInteger, 18446744073709551615 for ULong, 'and to the expression -1 for SByte, Short, Integer, Long, Decimal, Single, and Double If numericType Is byteType Then Assert.Equal(255, DirectCast(resultValue.Value, Byte)) ElseIf numericType Is uint16Type Then Assert.Equal(65535, DirectCast(resultValue.Value, UInt16)) ElseIf numericType Is uint32Type Then Assert.Equal(4294967295, DirectCast(resultValue.Value, UInt32)) ElseIf numericType Is uint64Type Then Assert.Equal(18446744073709551615UL, DirectCast(resultValue.Value, UInt64)) Else Assert.Equal(-1, Convert.ToInt64(resultValue.Value)) End If Next resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue.IsBad, resultValue2.IsBad) Assert.Equal(resultValue2, resultValue) Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.True(DirectCast(resultValue.Value, Boolean)) For Each mv In nonZeroValues Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator()) Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, v, mv.Type, Nothing) Dim typeConv = ClassifyConversion(mv.Type, booleanType) Dim conv = ClassifyConversion(literal, booleanType, methodBodyBinder) Dim conv2 = ClassifyConversion(constant, booleanType, methodBodyBinder) Assert.Equal(conv, conv2) Assert.Equal(typeConv, conv) resultValue = Conversions.TryFoldConstantConversion(literal, booleanType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, booleanType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue2, resultValue) Assert.Equal(booleanType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.True(DirectCast(resultValue.Value, Boolean)) Next ' ------- String <-> Char Dim stringValue = ConstantValue.Nothing Assert.Null(stringValue.StringValue) literal = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, Nothing), ConversionKind.WideningNothingLiteral, False, True, stringValue, stringType, Nothing) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder)) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue2, resultValue) Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal(ChrW(0), CChar(stringValue.StringValue)) Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char)) stringValue = ConstantValue.Create("") Assert.Equal(0, stringValue.StringValue.Length) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder)) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue2, resultValue) Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal(ChrW(0), CChar("")) Assert.Equal(ChrW(0), DirectCast(resultValue.Value, Char)) stringValue = ConstantValue.Create("abc") literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), stringValue, stringType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, stringValue, stringType, Nothing) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(literal, charType, methodBodyBinder)) Assert.Equal(ConversionKind.NarrowingString, ClassifyConversion(constant, charType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, charType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, charType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue2, resultValue) Assert.Equal(charType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal("a"c, DirectCast(resultValue.Value, Char)) Dim charValue = ConstantValue.Create("b"c) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), charValue, charType) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, charValue, charType, Nothing) Assert.Equal(ConversionKind.WideningString, ClassifyConversion(literal, stringType, methodBodyBinder)) Assert.Equal(ConversionKind.WideningString, ClassifyConversion(constant, stringType, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, stringType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, stringType, integerOverflow2) Assert.NotNull(resultValue) Assert.NotNull(resultValue2) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(integerOverflow, integerOverflow2) Assert.Equal(resultValue2, resultValue) Assert.Equal(stringType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) Assert.Equal("b", DirectCast(resultValue.Value, String)) End Sub <Fact()> Public Sub ConstantExpressionConversions2() Dim dummyCode = <file> Class C1 Shared Sub MethodDecl() End Sub End Class </file> Dim dummyTree = VisualBasicSyntaxTree.ParseText(dummyCode.Value) Dim c1 = VisualBasicCompilation.Create("Test", syntaxTrees:={dummyTree}, references:={TestReferences.NetFx.v4_0_21006.mscorlib}, options:=TestOptions.ReleaseExe.WithOverflowChecks(False)) Dim sourceModule = DirectCast(c1.Assembly.Modules(0), SourceModuleSymbol) Dim methodDeclSymbol = DirectCast(sourceModule.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers("MethodDecl").Single(), SourceMethodSymbol) Dim methodBodyBinder = BinderBuilder.CreateBinderForMethodBody(sourceModule, dummyTree, methodDeclSymbol) Assert.False(c1.Options.CheckOverflow) Dim objectType = c1.GetSpecialType(System_Object) Dim booleanType = c1.GetSpecialType(System_Boolean) Dim byteType = c1.GetSpecialType(System_Byte) Dim sbyteType = c1.GetSpecialType(System_SByte) Dim int16Type = c1.GetSpecialType(System_Int16) Dim uint16Type = c1.GetSpecialType(System_UInt16) Dim int32Type = c1.GetSpecialType(System_Int32) Dim uint32Type = c1.GetSpecialType(System_UInt32) Dim int64Type = c1.GetSpecialType(System_Int64) Dim uint64Type = c1.GetSpecialType(System_UInt64) Dim doubleType = c1.GetSpecialType(System_Double) Dim singleType = c1.GetSpecialType(System_Single) Dim decimalType = c1.GetSpecialType(System_Decimal) Dim dateType = c1.GetSpecialType(System_DateTime) Dim stringType = c1.GetSpecialType(System_String) Dim charType = c1.GetSpecialType(System_Char) Dim intPtrType = c1.GetSpecialType(System_IntPtr) Dim typeCodeType = c1.GlobalNamespace.GetMembers("System").OfType(Of NamespaceSymbol)().Single().GetTypeMembers("TypeCode").Single() Dim allTestTypes = New TypeSymbol() { objectType, booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType, stringType, charType, intPtrType, typeCodeType} Dim convertibleTypes = New HashSet(Of TypeSymbol)({ booleanType, byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, dateType, stringType, charType, typeCodeType}) Dim integralTypes = New HashSet(Of TypeSymbol)({ byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, typeCodeType}) Dim unsignedTypes = New HashSet(Of TypeSymbol)({ byteType, uint16Type, uint32Type, uint64Type}) Dim numericTypes = New HashSet(Of TypeSymbol)({ byteType, sbyteType, int16Type, uint16Type, int32Type, uint32Type, int64Type, uint64Type, doubleType, singleType, decimalType, typeCodeType}) Dim floatingTypes = New HashSet(Of TypeSymbol)({doubleType, singleType}) Dim _nothing = New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Nothing, Nothing) Dim resultValue As ConstantValue Dim integerOverflow As Boolean Dim literal As BoundLiteral Dim constant As BoundConversion Dim nullableType = c1.GetSpecialType(System_Nullable_T) ' -------- Numeric non-zero values Dim nonZeroValues = New TypeAndValue() { New TypeAndValue(sbyteType, SByte.MinValue), New TypeAndValue(int16Type, Int16.MinValue), New TypeAndValue(int32Type, Int32.MinValue), New TypeAndValue(int64Type, Int64.MinValue), New TypeAndValue(doubleType, Double.MinValue), New TypeAndValue(singleType, Single.MinValue), New TypeAndValue(decimalType, Decimal.MinValue), New TypeAndValue(sbyteType, SByte.MaxValue), New TypeAndValue(int16Type, Int16.MaxValue), New TypeAndValue(int32Type, Int32.MaxValue), New TypeAndValue(int64Type, Int64.MaxValue), New TypeAndValue(byteType, Byte.MaxValue), New TypeAndValue(uint16Type, UInt16.MaxValue), New TypeAndValue(uint32Type, UInt32.MaxValue), New TypeAndValue(uint64Type, UInt64.MaxValue), New TypeAndValue(doubleType, Double.MaxValue), New TypeAndValue(singleType, Single.MaxValue), New TypeAndValue(decimalType, Decimal.MaxValue), New TypeAndValue(sbyteType, CSByte(-1)), New TypeAndValue(int16Type, CShort(-2)), New TypeAndValue(int32Type, CInt(-3)), New TypeAndValue(int64Type, CLng(-4)), New TypeAndValue(sbyteType, CSByte(5)), New TypeAndValue(int16Type, CShort(6)), New TypeAndValue(int32Type, CInt(7)), New TypeAndValue(int64Type, CLng(8)), New TypeAndValue(doubleType, CDbl(-9)), New TypeAndValue(singleType, CSng(-10)), New TypeAndValue(decimalType, CDec(-11)), New TypeAndValue(doubleType, CDbl(12)), New TypeAndValue(singleType, CSng(13)), New TypeAndValue(decimalType, CDec(14)), New TypeAndValue(byteType, CByte(15)), New TypeAndValue(uint16Type, CUShort(16)), New TypeAndValue(uint32Type, CUInt(17)), New TypeAndValue(uint64Type, CULng(18)), New TypeAndValue(decimalType, CDec(-11.3)), New TypeAndValue(doubleType, CDbl(&HF000000000000000UL)), New TypeAndValue(doubleType, CDbl(&H70000000000000F0L)), New TypeAndValue(typeCodeType, Int32.MinValue), New TypeAndValue(typeCodeType, Int32.MaxValue), New TypeAndValue(typeCodeType, CInt(-3)), New TypeAndValue(typeCodeType, CInt(7)) } Dim resultValue2 As ConstantValue Dim integerOverflow2 As Boolean For Each mv In nonZeroValues Dim v = ConstantValue.Create(mv.Value, mv.Type.GetConstantValueTypeDiscriminator()) Assert.Equal(v.Discriminator, mv.Type.GetConstantValueTypeDiscriminator()) literal = New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), v, mv.Type) constant = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(DirectCast(dummyTree.GetRoot(Nothing), VisualBasicSyntaxNode), ConstantValue.Null, Nothing), ConversionKind.Widening, True, True, v, mv.Type, Nothing) For Each numericType In numericTypes Dim typeConv = ClassifyConversion(mv.Type, numericType) Dim conv = ClassifyConversion(literal, numericType, methodBodyBinder) Dim conv2 = ClassifyConversion(constant, numericType, methodBodyBinder) Assert.Equal(conv, conv2) resultValue = Conversions.TryFoldConstantConversion(literal, numericType, integerOverflow) resultValue2 = Conversions.TryFoldConstantConversion(constant, numericType, integerOverflow2) Assert.Equal(resultValue Is Nothing, resultValue2 Is Nothing) Assert.Equal(integerOverflow, integerOverflow2) If resultValue IsNot Nothing Then Assert.Equal(resultValue2, resultValue) If Not resultValue.IsBad Then Assert.Equal(numericType.GetConstantValueTypeDiscriminator(), resultValue.Discriminator) End If End If Dim resultValueAsObject As Object = Nothing Dim overflow As Boolean = False Try resultValueAsObject = CheckedConvert(v.Value, numericType) Catch ex As OverflowException overflow = True End Try If Not overflow Then If Conversions.IsIdentityConversion(typeConv) Then Assert.True(Conversions.IsIdentityConversion(conv)) ElseIf Conversions.IsNarrowingConversion(typeConv) Then If mv.Type Is doubleType AndAlso numericType Is singleType Then Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv) ElseIf integralTypes.Contains(mv.Type) AndAlso numericType.IsEnumType() Then Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv) ElseIf integralTypes.Contains(mv.Type) AndAlso integralTypes.Contains(numericType) AndAlso Not mv.Type.IsEnumType() AndAlso Not numericType.IsEnumType() Then Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv) Else Assert.Equal(typeConv, conv) End If ElseIf mv.Type.IsEnumType() Then Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv) Else Assert.Equal(ConversionKind.WideningNumeric, conv) End If Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(resultValueAsObject, resultValue.Value) If mv.Type Is doubleType AndAlso numericType Is singleType Then If v.DoubleValue = Double.MinValue Then Dim min As Single = Double.MinValue Assert.True(Single.IsNegativeInfinity(min)) Assert.Equal(resultValue.SingleValue, min) ElseIf v.DoubleValue = Double.MaxValue Then Dim max As Single = Double.MaxValue Assert.Equal(Double.MaxValue, v.DoubleValue) Assert.True(Single.IsPositiveInfinity(max)) Assert.Equal(resultValue.SingleValue, max) End If End If ElseIf Not integralTypes.Contains(mv.Type) OrElse Not integralTypes.Contains(numericType) Then 'Assert.Equal(typeConv, conv) If integralTypes.Contains(numericType) Then Assert.NotNull(resultValue) If resultValue.IsBad Then Assert.False(integerOverflow) Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv) Else Assert.True(integerOverflow) Assert.Equal(typeConv, conv) Dim intermediate As Object If unsignedTypes.Contains(numericType) Then intermediate = Convert.ToUInt64(mv.Value) Else intermediate = Convert.ToInt64(mv.Value) End If Dim gotException As Boolean Try gotException = False CheckedConvert(intermediate, numericType) ' Should get an overflow Catch x As Exception gotException = True End Try Assert.True(gotException) Assert.Equal(UncheckedConvert(intermediate, numericType), resultValue.Value) End If Else Assert.NotNull(resultValue) Assert.False(integerOverflow) Assert.True(resultValue.IsBad) Assert.Equal(ConversionKind.FailedDueToNumericOverflow, conv) End If Else ' An integer overflow case If numericType.IsEnumType() OrElse mv.Type.IsEnumType() Then Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, conv) Else Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesNarrowingFromNumericConstant, conv) End If Assert.NotNull(resultValue) Assert.True(integerOverflow) Assert.False(resultValue.IsBad) Assert.Equal(UncheckedConvert(v.Value, numericType), resultValue.Value) End If Dim nullableType2 = nullableType.Construct(numericType) Dim zero = New BoundConversion(dummyTree.GetVisualBasicRoot(Nothing), New BoundLiteral(dummyTree.GetVisualBasicRoot(Nothing), ConstantValue.Default(ConstantValueTypeDiscriminator.Int32), int32Type), ConversionKind.Widening, True, True, ConstantValue.Default(mv.Type.GetConstantValueTypeDiscriminator()), mv.Type, Nothing) conv = ClassifyConversion(literal, numericType, methodBodyBinder) If (conv And ConversionKind.FailedDueToNumericOverflowMask) = 0 Then conv = ClassifyConversion(mv.Type, nullableType2) Or (ClassifyConversion(zero, nullableType2, methodBodyBinder) And ConversionKind.InvolvesNarrowingFromNumericConstant) End If Assert.Equal(conv, ClassifyConversion(literal, nullableType2, methodBodyBinder)) Assert.Equal(conv, ClassifyConversion(constant, nullableType2, methodBodyBinder)) resultValue = Conversions.TryFoldConstantConversion(literal, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) resultValue = Conversions.TryFoldConstantConversion(constant, nullableType2, integerOverflow) Assert.Null(resultValue) Assert.False(integerOverflow) Next Next End Sub Private Function CheckedConvert(value As Object, type As TypeSymbol) As Object type = type.GetEnumUnderlyingTypeOrSelf() Select Case type.SpecialType Case System_Byte : Return CByte(value) Case System_SByte : Return CSByte(value) Case System_Int16 : Return CShort(value) Case System_UInt16 : Return CUShort(value) Case System_Int32 : Return CInt(value) Case System_UInt32 : Return CUInt(value) Case System_Int64 : Return CLng(value) Case System_UInt64 : Return CULng(value) Case System_Single : Return CSng(value) Case System_Double : Return CDbl(value) Case System_Decimal : Return CDec(value) Case Else Throw New NotSupportedException() End Select End Function Private Function UncheckedConvert(value As Object, type As TypeSymbol) As Object type = type.GetEnumUnderlyingTypeOrSelf() Select Case System.Type.GetTypeCode(value.GetType()) Case TypeCode.Byte, TypeCode.UInt16, TypeCode.UInt32, TypeCode.UInt64 Dim val As UInt64 = Convert.ToUInt64(value) Select Case type.SpecialType Case System_Byte : Return UncheckedCByte(UncheckedCLng(val)) Case System_SByte : Return UncheckedCSByte(UncheckedCLng(val)) Case System_Int16 : Return UncheckedCShort(val) Case System_UInt16 : Return UncheckedCUShort(UncheckedCLng(val)) Case System_Int32 : Return UncheckedCInt(val) Case System_UInt32 : Return UncheckedCUInt(val) Case System_Int64 : Return UncheckedCLng(val) Case System_UInt64 : Return UncheckedCULng(val) Case Else Throw New NotSupportedException() End Select Case TypeCode.SByte, TypeCode.Int16, TypeCode.Int32, TypeCode.Int64 Dim val As Int64 = Convert.ToInt64(value) Select Case type.SpecialType Case System_Byte : Return UncheckedCByte(val) Case System_SByte : Return UncheckedCSByte(val) Case System_Int16 : Return UncheckedCShort(val) Case System_UInt16 : Return UncheckedCUShort(val) Case System_Int32 : Return UncheckedCInt(val) Case System_UInt32 : Return UncheckedCUInt(val) Case System_Int64 : Return UncheckedCLng(val) Case System_UInt64 : Return UncheckedCULng(val) Case Else Throw New NotSupportedException() End Select Case Else Throw New NotSupportedException() End Select Select Case type.SpecialType Case System_Byte : Return CByte(value) Case System_SByte : Return CSByte(value) Case System_Int16 : Return CShort(value) Case System_UInt16 : Return CUShort(value) Case System_Int32 : Return CInt(value) Case System_UInt32 : Return CUInt(value) Case System_Int64 : Return CLng(value) Case System_UInt64 : Return CULng(value) Case System_Single : Return CSng(value) Case System_Double : Return CDbl(value) Case System_Decimal : Return CDec(value) Case Else Throw New NotSupportedException() End Select End Function Friend Structure TypeAndValue Public ReadOnly Type As TypeSymbol Public ReadOnly Value As Object Public Sub New(type As TypeSymbol, value As Object) Me.Type = type Me.Value = value End Sub End Structure <Fact()> Public Sub PredefinedNotBuiltIn() ' Tests are based on the source code used to compile VBConversions.dll, VBConversions.vb is ' checked in next to the DLL. Dim vbConversionsRef = TestReferences.SymbolsTests.VBConversions Dim modifiersRef = TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib, vbConversionsRef, modifiersRef}) Dim asmVBConversions = c1.GetReferencedAssemblySymbol(vbConversionsRef) Dim asmModifiers = c1.GetReferencedAssemblySymbol(modifiersRef) Dim test = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Test").Single() '--------------- Identity Dim m1 = DirectCast(test.GetMembers("M1").Single(), MethodSymbol) Dim m1p = m1.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(a), m1p(b)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(a), m1p(c))) 'error BC30311: Value of type 'Class2' cannot be converted to 'Class1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(a), m1p(d))) 'error BC30311: Value of type '1-dimensional array of Class1' cannot be converted to 'Class1'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(d), m1p(e)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(d), m1p(f))) 'error BC30332: Value of type '1-dimensional array of Class2' cannot be converted to '1-dimensional array of Class1' because 'Class2' is not derived from 'Class1'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(g), m1p(h)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(g), m1p(i))) 'error BC30311: Value of type 'Class2.Class3(Of Byte)' cannot be converted to 'Class2.Class3(Of Integer)'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(g), m1p(j))) 'error BC30311: Value of type 'Class4(Of Integer)' cannot be converted to 'Class2.Class3(Of Integer)'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(j), m1p(k)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(j), m1p(l))) 'error BC30311: Value of type 'Class4(Of Byte)' cannot be converted to 'Class4(Of Integer)'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(m), m1p(n)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(m), m1p(o))) 'error BC30311: Value of type 'Class4(Of Byte).Class5(Of Integer)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(m), m1p(p))) 'error BC30311: Value of type 'Class4(Of Integer).Class5(Of Byte)' cannot be converted to 'Class4(Of Integer).Class5(Of Integer)'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(q), m1p(r)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(q), m1p(s))) 'error BC30311: Value of type 'Class4(Of Byte).Class6' cannot be converted to 'Class4(Of Integer).Class6'. Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m1p(t), m1p(u)))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(t), m1p(v))) 'error BC30311: Value of type 'Class4(Of Byte).Class6.Class7(Of Integer)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m1p(t), m1p(w))) 'error BC30311: Value of type 'Class4(Of Integer).Class6.Class7(Of Byte)' cannot be converted to 'Class4(Of Integer).Class6.Class7(Of Integer)'. Dim modifiers = asmModifiers.Modules(0).GlobalNamespace.GetTypeMembers("Modifiers").Single() Dim modifiedArrayInt32 = modifiers.GetMembers("F5").OfType(Of MethodSymbol)().Single().Parameters(0).Type Dim arrayInt32 = c1.CreateArrayTypeSymbol(c1.GetSpecialType(System_Int32)) Assert.NotEqual(modifiedArrayInt32, arrayInt32) Assert.NotEqual(arrayInt32, modifiedArrayInt32) Assert.True(arrayInt32.IsSameTypeIgnoringCustomModifiers(modifiedArrayInt32)) Assert.True(modifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(arrayInt32)) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(arrayInt32, modifiedArrayInt32))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(modifiedArrayInt32, arrayInt32))) Dim enumerable = c1.GetSpecialType(System_Collections_Generic_IEnumerable_T) Dim enumerableOfModifiedArrayInt32 = enumerable.Construct(modifiedArrayInt32) Dim enumerableOfArrayInt32 = enumerable.Construct(arrayInt32) Assert.NotEqual(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32) Assert.NotEqual(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32) Assert.True(enumerableOfArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfModifiedArrayInt32)) Assert.True(enumerableOfModifiedArrayInt32.IsSameTypeIgnoringCustomModifiers(enumerableOfArrayInt32)) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfArrayInt32, enumerableOfModifiedArrayInt32))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(enumerableOfModifiedArrayInt32, enumerableOfArrayInt32))) '--------------- Numeric Dim m2 = DirectCast(test.GetMembers("M2").Single(), MethodSymbol) Dim m2p = m2.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m2p(a), m2p(b)))) Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum3' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'Short' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(a), m2p(h))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum4' to 'Enum1'. Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(a))) Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Integer'. Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(e), m2p(d))) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(a))) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(c))) Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(f), m2p(d))) Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'Short'. Assert.Equal(ConversionKind.NarrowingNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum2' to 'Short'. Assert.Equal(ConversionKind.WideningNumeric Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m2p(g), m2p(d))) '--------------- Reference Dim m3 = DirectCast(test.GetMembers("M3").Single(), MethodSymbol) Dim m3p = m3.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(a), m3p(a)))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(d))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(b), m3p(b)))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(c))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(b), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(c), m3p(d))) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Class10'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(c), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class9'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Class10'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(d), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Class10'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(c), m3p(e))) 'error BC30311: Value of type 'Class11' cannot be converted to 'Class9'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(e), m3p(c))) 'error BC30311: Value of type 'Class9' cannot be converted to 'Class11'. Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(h))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(f), m3p(h))) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '1-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '1-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to '2-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Array' to '2-dimensional array of Integer'. Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(j), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(k), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(c))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(l), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(b))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(c))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(m), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(d))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(p), m3p(h))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(q), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(r), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(s), m3p(g))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(v), m3p(u))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m3p(i), m3p(i)))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(j))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(k))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(i), m3p(o))) Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(n), m3p(o))) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class11' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface2'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(j), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface2'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface3'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(k), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface3'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(l), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface4'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface6'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(n), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface6'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(o), m3p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'Interface7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(q), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IList(Of Integer)'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(r), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.ICollection(Of Integer)'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(s), m3p(h))) 'error BC30311: Value of type '2-dimensional array of Integer' cannot be converted to 'System.Collections.Generic.IEnumerable(Of Integer)'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(t), m3p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'System.Collections.Generic.IList(Of Long)'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(w), m3p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'System.Collections.Generic.IList(Of Class11)'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), m3p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface4' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingReference Or ConversionKind.DelegateRelaxationLevelNarrowing, ClassifyPredefinedAssignment(m3p(o), m3p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Action' to 'Interface7'. Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment(m3p(a), m3p(o))) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(x), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'System.Action'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(e), m3p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'Class11'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(g), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(h), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '2-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(u), m3p(o))) 'error BC30311: Value of type 'Interface7' cannot be converted to '1-dimensional array of Class9'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '1-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(h), m3p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to '2-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Integer)' to '1-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(h), m3p(q))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Integer)' cannot be converted to '2-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Long)' to '1-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(h), m3p(t))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Long)' cannot be converted to '2-dimensional array of Integer'. Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(g), m3p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class11)' to '1-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m3p(h), m3p(w))) 'error BC30311: Value of type 'System.Collections.Generic.IList(Of Class11)' cannot be converted to '2-dimensional array of Integer'. Dim [object] = c1.GetSpecialType(System_Object) Dim module2 = asmVBConversions.Modules(0).GlobalNamespace.GetTypeMembers("Module2").Single() Assert.Equal(ConversionKind.WideningReference, ClassifyPredefinedAssignment([object], module2)) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, [object])) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(m3p(i), module2)) Assert.Equal(ConversionKind.NarrowingReference, ClassifyPredefinedAssignment(module2, m3p(i))) ' ------------- Type Parameter Dim m6 = DirectCast(test.GetMembers("M6").Single(), MethodSymbol) Dim m6p = m6.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m6p(b), m6p(b)))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(b))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(c))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(a), m6p(d))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(d), m6p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT3'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(f))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(h))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(h), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(f), m6p(g))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(g), m6p(f))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(h), m6p(i))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(i), m6p(h))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT7'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(e), m6p(k))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(k))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(j), m6p(f))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'MT8'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT8'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(l), m6p(k))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(k))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(p), m6p(c))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class10' to 'MT8'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT8'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(n), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'Class12'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(k), m6p(n))) 'error BC30311: Value of type 'Class12' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(k), m6p(o))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(o), m6p(k))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT9'. Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(q))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(r))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(t), m6p(s))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m6p(m), m6p(s))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(q), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT10'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(r), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT11'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class9' to 'MT13'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(s), m6p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class8' to 'MT13'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(l), m6p(s))) 'error BC30311: Value of type 'MT13' cannot be converted to 'Class10'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(s), m6p(l))) 'error BC30311: Value of type 'Class10' cannot be converted to 'MT13'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT8' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(k), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT8'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(f), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(b), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT1'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(u), m6p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'Interface7'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m6p(c), m6p(u))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface7' to 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(v), m6p(q))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT14'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m6p(q), m6p(v))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT10'. Dim m7 = DirectCast(test.GetMembers("M7").Single(), MethodSymbol) Dim m7p = m7.Parameters.Select(Function(p) p.Type).ToArray() Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(a))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(p), m7p(b))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(c))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(q), m7p(d))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(r), m7p(d))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(t), m7p(g))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(j))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(v), m7p(k))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(w), m7p(n))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(x), m7p(i))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(j))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(k))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(a), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT1'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(b), m7p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'MT2'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(c), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT3'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(q))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(r))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(g), m7p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to 'MT7'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT10'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class9' to 'MT11'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(w))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT14'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(x))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.IEnumerable' to 'MT9'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT9' to 'System.Collections.Generic.IList(Of Class9)'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(i), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT9'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(j), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT10' Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(k), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT11' Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(y), m7p(z))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT15' to 'System.Collections.Generic.IList(Of Class9)' Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(z), m7p(y))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Collections.Generic.IList(Of Class9)' to 'MT15' Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(n), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT14'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(n))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(m), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT13'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT13' to 'Interface1'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(d), m7p(o))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m7p(o), m7p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT4' to 'Interface1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(r), m7p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'Enum1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(e), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(s), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'Enum2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(d), m7p(s))) 'error BC30311: Value of type 'Enum2' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(r), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'Enum1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(f), m7p(r))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(t), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to '1-dimensional array of Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(h), m7p(t))) 'error BC30311: Value of type '1-dimensional array of Integer' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(v), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to '1-dimensional array of Class9'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(i), m7p(v))) 'error BC30311: Value of type '1-dimensional array of Class9' cannot be converted to 'MT9'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(a), m7p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(b), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(g), m7p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(h), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(g), m7p(l))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(l), m7p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT12'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(c), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT3'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(d), m7p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(i), m7p(j))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT9'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(j), m7p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT10'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(a), m7p(n))) 'error BC30311: Value of type 'MT14' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(n), m7p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT14'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(d), m7p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m7p(f), m7p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT6'. Dim m8 = DirectCast(test.GetMembers("M8").Single(), MethodSymbol) Dim m8p = m8.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m8p(a), m8p(a)))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(d))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(f))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(a), m8p(c))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(b), m8p(e))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m8p(g), m8p(h))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(c), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT3'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(d), m8p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT4'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(e), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT5'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(f), m8p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT2' to 'MT6'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m8p(h), m8p(g))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT7' to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(a), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(b), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(b), m8p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(d), m8p(b))) 'error BC30311: Value of type 'MT2' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(a), m8p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m8p(g), m8p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT7'. Dim m9 = DirectCast(test.GetMembers("M9").Single(), MethodSymbol) Dim m9p = m9.Parameters.Select(Function(p) p.Type).ToArray() Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(b))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(j), m9p(a))) Assert.Equal(ConversionKind.WideningTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(j), m9p(e))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(l), m9p(e))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(m), m9p(n))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(p), m9p(q))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(u))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(t), m9p(u))) Assert.Equal(ConversionKind.WideningTypeParameter, ClassifyPredefinedAssignment(m9p(s), m9p(v))) Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(b), m9p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT1' to 'MT2'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(a), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT1'. Assert.Equal(ConversionKind.NarrowingTypeParameter Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m9p(e), m9p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer' to 'MT5'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(e), m9p(l))) 'error BC30512: Option Strict On disallows implicit conversions from 'Enum1' to 'MT5'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(n), m9p(m))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure1' to 'MT10'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(q), m9p(p))) 'error BC30512: Option Strict On disallows implicit conversions from 'Class1' to 'MT12'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT15'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(u), m9p(t))) 'error BC30512: Option Strict On disallows implicit conversions from 'MT14' to 'MT15'. Assert.Equal(ConversionKind.NarrowingTypeParameter, ClassifyPredefinedAssignment(m9p(v), m9p(s))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'MT16'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(e), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(e), m9p(g))) 'error BC30311: Value of type 'MT7' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(g), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(l))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(l), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'Enum1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(i))) 'error BC30311: Value of type 'MT9' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(c))) 'error BC30311: Value of type 'MT3' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(c), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT3'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(d))) 'error BC30311: Value of type 'MT4' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(d), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(f), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(h), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(e), m9p(f))) 'error BC30311: Value of type 'MT6' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(f), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(e), m9p(h))) 'error BC30311: Value of type 'MT8' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(h), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(a), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(k), m9p(a))) 'error BC30311: Value of type 'MT1' cannot be converted to 'UInteger'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(e), m9p(k))) 'error BC30311: Value of type 'UInteger' cannot be converted to 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(k), m9p(e))) 'error BC30311: Value of type 'MT5' cannot be converted to 'UInteger'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(n), m9p(o))) 'error BC30311: Value of type 'MT11' cannot be converted to 'MT10'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(o), m9p(n))) 'error BC30311: Value of type 'MT10' cannot be converted to 'MT11'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(q), m9p(r))) 'error BC30311: Value of type 'MT13' cannot be converted to 'MT12'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(r), m9p(q))) 'error BC30311: Value of type 'MT12' cannot be converted to 'MT13'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(v), m9p(w))) 'error BC30311: Value of type 'MT17' cannot be converted to 'MT16'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m9p(w), m9p(v))) 'error BC30311: Value of type 'MT16' cannot be converted to 'MT17'. ' ------------- Array conversions Dim m4 = DirectCast(test.GetMembers("M4").Single(), MethodSymbol) Dim m4p = m4.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(a), m4p(a)))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(l), m4p(l)))) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m4p(n), m4p(n)))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(a), m4p(d))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(b), m4p(f))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(j))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(i), m4p(k))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(l), m4p(m))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(n), m4p(o))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(p), m4p(i))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(i))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m4p(x), m4p(w))) Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(a), m4p(c))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT3' to '1-dimensional array of MT1'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(c), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT3'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(d), m4p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT4'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(b), m4p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT2'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(e), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT5'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(f), m4p(b))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT2' to '1-dimensional array of MT6'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(g), m4p(h))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT8' to '1-dimensional array of MT7'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(h), m4p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT8'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(j), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class9'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(k), m4p(i))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class8' to '1-dimensional array of Class11'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(m), m4p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '2-dimensional array of Class8' to '2-dimensional array of Class9'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(o), m4p(n))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of 1-dimensional array of Class8' to '1-dimensional array of 1-dimensional array of Class9'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Interface5' to '1-dimensional array of Class8'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(i), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of Class8'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m4p(w), m4p(x))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Object' to '1-dimensional array of System.ValueType'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(a), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT1' because 'MT2' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(b), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT2' because 'MT1' is not derived from 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(b), m4p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT2' because 'MT4' is not derived from 'MT2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(d), m4p(b))) 'error BC30332: Value of type '1-dimensional array of MT2' cannot be converted to '1-dimensional array of MT4' because 'MT2' is not derived from 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(a), m4p(g))) 'error BC30332: Value of type '1-dimensional array of MT7' cannot be converted to '1-dimensional array of MT1' because 'MT7' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(g), m4p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT7' because 'MT1' is not derived from 'MT7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(j), m4p(k))) 'error BC30332: Value of type '1-dimensional array of Class11' cannot be converted to '1-dimensional array of Class9' because 'Class11' is not derived from 'Class9'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(i), m4p(l))) 'error BC30414: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of Class8' because the array types have different numbers of dimensions. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(l), m4p(i))) 'error BC30414: Value of type '1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because the array types have different numbers of dimensions. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(l), m4p(n))) 'error BC30332: Value of type '1-dimensional array of 1-dimensional array of Class8' cannot be converted to '2-dimensional array of Class8' because '1-dimensional array of Class8' is not derived from 'Class8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(n), m4p(l))) 'error BC30332: Value of type '2-dimensional array of Class8' cannot be converted to '1-dimensional array of 1-dimensional array of Class8' because 'Class8' is not derived from '1-dimensional array of Class8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(p), m4p(q))) 'error BC30332: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of Interface5' because 'Structure1' is not derived from 'Interface5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(q), m4p(p))) 'error BC30332: Value of type '1-dimensional array of Interface5' cannot be converted to '1-dimensional array of Structure1' because 'Interface5' is not derived from 'Structure1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(q), m4p(w))) 'error BC30332: Value of type '1-dimensional array of System.ValueType' cannot be converted to '1-dimensional array of Structure1' because 'System.ValueType' is not derived from 'Structure1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(w), m4p(q))) 'error BC30333: Value of type '1-dimensional array of Structure1' cannot be converted to '1-dimensional array of System.ValueType' because 'Structure1' is not a reference type. Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(r), m4p(t))) Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(s), m4p(u))) Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(r))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of Enum1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(u), m4p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Long' to '1-dimensional array of Enum2'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(t), m4p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum4' to '1-dimensional array of Enum1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m4p(v), m4p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of Enum4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(r), m4p(s))) 'error BC30332: Value of type '1-dimensional array of Long' cannot be converted to '1-dimensional array of Integer' because 'Long' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(s), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Long' because 'Integer' is not derived from 'Long'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(r), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Integer' because 'Enum2' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(u), m4p(r))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of Enum2' because 'Integer' is not derived from 'Enum2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(t), m4p(u))) 'error BC30332: Value of type '1-dimensional array of Enum2' cannot be converted to '1-dimensional array of Enum1' because 'Enum2' is not derived from 'Enum1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m4p(u), m4p(t))) 'error BC30332: Value of type '1-dimensional array of Enum1' cannot be converted to '1-dimensional array of Enum2' because 'Enum1' is not derived from 'Enum2'. Dim m5 = DirectCast(test.GetMembers("M5").Single(), MethodSymbol) Dim m5p = m5.Parameters.Select(Function(p) p.Type).ToArray() Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(a), m5p(b))) Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(b), m5p(a))) ' error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT2'. Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(j), m5p(a))) Assert.Equal(ConversionKind.WideningArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(j), m5p(e))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(l), m5p(e))) Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of MT5'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(g))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT7' to '1-dimensional array of MT5'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(g), m5p(e))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT5' to '1-dimensional array of MT7'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(a), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(a), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(l), m5p(a))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT1' to '1-dimensional array of Enum1'. Assert.Equal(ConversionKind.NarrowingArray Or ConversionKind.InvolvesEnumTypeConversions, ClassifyPredefinedAssignment(m5p(e), m5p(j))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Integer' to '1-dimensional array of MT5'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(e), m5p(l))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Enum1' to '1-dimensional array of MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(i))) 'error BC30332: Value of type '1-dimensional array of MT9' cannot be converted to '1-dimensional array of MT1' because 'MT9' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(c))) 'error BC30332: Value of type '1-dimensional array of MT3' cannot be converted to '1-dimensional array of MT1' because 'MT3' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(c), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT3' because 'MT1' is not derived from 'MT3'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(d))) 'error BC30332: Value of type '1-dimensional array of MT4' cannot be converted to '1-dimensional array of MT1' because 'MT4' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(d), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT4' because 'MT1' is not derived from 'MT4'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT1' because 'MT6' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(f), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT6' because 'MT1' is not derived from 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT1' because 'MT8' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(h), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of MT8' because 'MT1' is not derived from 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(e), m5p(f))) 'error BC30332: Value of type '1-dimensional array of MT6' cannot be converted to '1-dimensional array of MT5' because 'MT6' is not derived from 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(f), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT6' because 'MT5' is not derived from 'MT6'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(e), m5p(h))) 'error BC30332: Value of type '1-dimensional array of MT8' cannot be converted to '1-dimensional array of MT5' because 'MT8' is not derived from 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(h), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of MT8' because 'MT5' is not derived from 'MT8'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(a), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT1' because 'UInteger' is not derived from 'MT1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(k), m5p(a))) 'error BC30332: Value of type '1-dimensional array of MT1' cannot be converted to '1-dimensional array of UInteger' because 'MT1' is not derived from 'UInteger'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(e), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of MT5' because 'UInteger' is not derived from 'MT5'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(k), m5p(e))) 'error BC30332: Value of type '1-dimensional array of MT5' cannot be converted to '1-dimensional array of UInteger' because 'MT5' is not derived from 'UInteger'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(j), m5p(k))) 'error BC30332: Value of type '1-dimensional array of UInteger' cannot be converted to '1-dimensional array of Integer' because 'UInteger' is not derived from 'Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(k), m5p(j))) 'error BC30332: Value of type '1-dimensional array of Integer' cannot be converted to '1-dimensional array of UInteger' because 'Integer' is not derived from 'UInteger'. Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(m), m5p(n))) Assert.Equal(ConversionKind.WideningArray, ClassifyPredefinedAssignment(m5p(p), m5p(q))) Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(n), m5p(m))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Structure1' to '1-dimensional array of MT10'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(q), m5p(p))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of Class1' to '1-dimensional array of MT12'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of System.ValueType'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT15'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(t), m5p(u))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT15' to '1-dimensional array of MT14'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(u), m5p(t))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT14' to '1-dimensional array of MT15'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(s), m5p(v))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of MT16' to '1-dimensional array of System.ValueType'. Assert.Equal(ConversionKind.NarrowingArray, ClassifyPredefinedAssignment(m5p(v), m5p(s))) 'error BC30512: Option Strict On disallows implicit conversions from '1-dimensional array of System.ValueType' to '1-dimensional array of MT16'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(n), m5p(o))) 'error BC30332: Value of type '1-dimensional array of MT11' cannot be converted to '1-dimensional array of MT10' because 'MT11' is not derived from 'MT10'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(o), m5p(n))) 'error BC30332: Value of type '1-dimensional array of MT10' cannot be converted to '1-dimensional array of MT11' because 'MT10' is not derived from 'MT11'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(q), m5p(r))) 'error BC30332: Value of type '1-dimensional array of MT13' cannot be converted to '1-dimensional array of MT12' because 'MT13' is not derived from 'MT12'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(r), m5p(q))) 'error BC30332: Value of type '1-dimensional array of MT12' cannot be converted to '1-dimensional array of MT13' because 'MT12' is not derived from 'MT13'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(v), m5p(w))) 'error BC30332: Value of type '1-dimensional array of MT17' cannot be converted to '1-dimensional array of MT16' because 'MT17' is not derived from 'MT16'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m5p(w), m5p(v))) 'error BC30332: Value of type '1-dimensional array of MT16' cannot be converted to '1-dimensional array of MT17' because 'MT16' is not derived from 'MT17'. ' ------------- Value Type Dim void = c1.GetSpecialType(System_Void) Dim valueType = c1.GetSpecialType(System_ValueType) Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(void, void))) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment([object], void)) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(void, [object])) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(valueType, void)) Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(void, valueType)) Dim m10 = DirectCast(test.GetMembers("M10").Single(), MethodSymbol) Dim m10p = m10.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m10p(f), m10p(f)))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(f))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(f))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(a), m10p(h))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(b), m10p(h))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(c), m10p(h))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(d), m10p(f))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m10p(i), m10p(f))) Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(h), m10p(c))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.Enum' to 'Enum1'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m10p(f), m10p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(c), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'System.Enum'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(f), m10p(c))) 'error BC30311: Value of type 'System.Enum' cannot be converted to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(d), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Interface1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(h), m10p(d))) 'error BC30311: Value of type 'Interface1' cannot be converted to 'Enum1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(e), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Interface7'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(f), m10p(e))) 'error BC30311: Value of type 'Interface7' cannot be converted to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(f), m10p(g))) 'error BC30311: Value of type 'Structure1' cannot be converted to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(g), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Structure1'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(f), m10p(h))) 'error BC30311: Value of type 'Enum1' cannot be converted to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m10p(h), m10p(f))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Enum1'. ' ------------ Nullable Dim m11 = DirectCast(test.GetMembers("M11").Single(), MethodSymbol) Dim m11p = m11.Parameters.Select(Function(p) p.Type).ToArray() Assert.True(Conversions.IsIdentityConversion(ClassifyPredefinedAssignment(m11p(d), m11p(d)))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(a), m11p(d))) Assert.Equal(ConversionKind.WideningValue, ClassifyPredefinedAssignment(m11p(b), m11p(d))) Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(d), m11p(c))) Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(e), m11p(d))) Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(f), m11p(d))) Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(i), m11p(h))) Assert.Equal(ConversionKind.WideningNullable, ClassifyPredefinedAssignment(m11p(k), m11p(i))) Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Structure2?'. Assert.Equal(ConversionKind.NarrowingValue, ClassifyPredefinedAssignment(m11p(d), m11p(b))) 'error BC30512: Option Strict On disallows implicit conversions from 'System.ValueType' to 'Structure2?'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(c), m11p(d))) 'error BC30512: Option Strict On disallows implicit conversions from 'Structure2?' to 'Structure2'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(e))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface1' to 'Structure2?'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(d), m11p(f))) 'error BC30512: Option Strict On disallows implicit conversions from 'Interface3' to 'Structure2?'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(h), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Integer'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(k))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long?' to 'Integer?'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(i), m11p(j))) 'error BC30512: Option Strict On disallows implicit conversions from 'Long' to 'Integer?'. Assert.Equal(ConversionKind.NarrowingNullable, ClassifyPredefinedAssignment(m11p(j), m11p(i))) 'error BC30512: Option Strict On disallows implicit conversions from 'Integer?' to 'Long'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(c), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(i), m11p(c))) 'error BC30311: Value of type 'Structure2' cannot be converted to 'Integer?'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(d), m11p(h))) 'error BC30311: Value of type 'Integer' cannot be converted to 'Structure2?'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(h), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(d), m11p(i))) 'error BC30311: Value of type 'Integer?' cannot be converted to 'Structure2?'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m11p(i), m11p(d))) 'error BC30311: Value of type 'Structure2?' cannot be converted to 'Integer?'. ' ------------ String Dim m12 = DirectCast(test.GetMembers("M12").Single(), MethodSymbol) Dim m12p = m12.Parameters.Select(Function(p) p.Type).ToArray() Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(b))) Assert.Equal(ConversionKind.WideningString, ClassifyPredefinedAssignment(m12p(a), m12p(c))) Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(b), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to 'Char'. Assert.Equal(ConversionKind.NarrowingString, ClassifyPredefinedAssignment(m12p(c), m12p(a))) 'error BC30512: Option Strict On disallows implicit conversions from 'String' to '1-dimensional array of Char'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m12p(b), m12p(c))) 'error BC30311: Value of type '1-dimensional array of Char' cannot be converted to 'Char'. Assert.Equal(s_noConversion, ClassifyPredefinedAssignment(m12p(c), m12p(b))) 'error BC30311: Value of type 'Char' cannot be converted to '1-dimensional array of Char'. End Sub Private Shared Function ClassifyPredefinedAssignment([to] As TypeSymbol, [from] As TypeSymbol) As ConversionKind Dim result As ConversionKind = Conversions.ClassifyPredefinedConversion([from], [to], Nothing) And Not ConversionKind.MightSucceedAtRuntime Assert.Equal(result, ClassifyConversion([from], [to])) Return result End Function Public Enum Parameters a b c d e f g h i j k l m n o p q r s t u v w x y z End Enum <Fact()> Public Sub BuiltIn() Dim c1 = VisualBasicCompilation.Create("Test", references:={TestReferences.NetFx.v4_0_21006.mscorlib}) Dim nullable = c1.GetSpecialType(System_Nullable_T) Dim types As NamedTypeSymbol() = { c1.GetSpecialType(System_Byte), c1.GetSpecialType(System_SByte), c1.GetSpecialType(System_UInt16), c1.GetSpecialType(System_Int16), c1.GetSpecialType(System_UInt32), c1.GetSpecialType(System_Int32), c1.GetSpecialType(System_UInt64), c1.GetSpecialType(System_Int64), c1.GetSpecialType(System_Decimal), c1.GetSpecialType(System_Single), c1.GetSpecialType(System_Double), c1.GetSpecialType(System_String), c1.GetSpecialType(System_Char), c1.GetSpecialType(System_Boolean), c1.GetSpecialType(System_DateTime), c1.GetSpecialType(System_Object), nullable.Construct(c1.GetSpecialType(System_Byte)), nullable.Construct(c1.GetSpecialType(System_SByte)), nullable.Construct(c1.GetSpecialType(System_UInt16)), nullable.Construct(c1.GetSpecialType(System_Int16)), nullable.Construct(c1.GetSpecialType(System_UInt32)), nullable.Construct(c1.GetSpecialType(System_Int32)), nullable.Construct(c1.GetSpecialType(System_UInt64)), nullable.Construct(c1.GetSpecialType(System_Int64)), nullable.Construct(c1.GetSpecialType(System_Decimal)), nullable.Construct(c1.GetSpecialType(System_Single)), nullable.Construct(c1.GetSpecialType(System_Double)), nullable.Construct(c1.GetSpecialType(System_Char)), nullable.Construct(c1.GetSpecialType(System_Boolean)), nullable.Construct(c1.GetSpecialType(System_DateTime)) } For i As Integer = 0 To types.Length - 1 Step 1 For j As Integer = 0 To types.Length - 1 Step 1 Dim convClass = Conversions.ClassifyPredefinedConversion(types(i), types(j), Nothing) Assert.Equal(convClass, Conversions.ConversionEasyOut.ClassifyPredefinedConversion(types(i), types(j))) Assert.Equal(convClass, ClassifyConversion(types(i), types(j))) If (i = j) Then Assert.True(Conversions.IsIdentityConversion(convClass)) Else Dim baseline = HasBuiltInWideningConversions(types(i), types(j)) If baseline = s_noConversion Then baseline = HasBuiltInNarrowingConversions(types(i), types(j)) End If Assert.Equal(baseline, convClass) End If Next Next End Sub Private Function HasBuiltInWideningConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind Dim result = HasBuiltInWideningConversions(from.SpecialType, [to].SpecialType) If result = s_noConversion Then Dim fromIsNullable = from.IsNullableType() Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing) If fromIsNullable AndAlso [to].SpecialType = System_Object Then Return ConversionKind.WideningValue End If Dim toIsNullable = [to].IsNullableType() Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing) 'Nullable Value Type conversions '• From a type T? to a type S?, where there is a widening conversion from the type T to the type S. If (fromIsNullable AndAlso toIsNullable) Then If (HasBuiltInWideningConversions(fromElement, toElement) And ConversionKind.Widening) <> 0 Then Return ConversionKind.WideningNullable End If End If If (Not fromIsNullable AndAlso toIsNullable) Then '• From a type T to the type T?. If from.Equals(toElement) Then Return ConversionKind.WideningNullable End If '• From a type T to a type S?, where there is a widening conversion from the type T to the type S. If (HasBuiltInWideningConversions(from, toElement) And ConversionKind.Widening) <> 0 Then Return ConversionKind.WideningNullable End If End If End If Return result End Function Private Function HasBuiltInNarrowingConversions(from As TypeSymbol, [to] As TypeSymbol) As ConversionKind Dim result = HasBuiltInNarrowingConversions(from.SpecialType, [to].SpecialType) If result = s_noConversion Then Dim toIsNullable = [to].IsNullableType() Dim toElement = If(toIsNullable, [to].GetNullableUnderlyingType(), Nothing) If from.SpecialType = System_Object AndAlso toIsNullable Then Return ConversionKind.NarrowingValue End If Dim fromIsNullable = from.IsNullableType() Dim fromElement = If(fromIsNullable, from.GetNullableUnderlyingType(), Nothing) 'Nullable Value Type conversions If (fromIsNullable AndAlso Not toIsNullable) Then '• From a type T? to a type T. If fromElement.Equals([to]) Then Return ConversionKind.NarrowingNullable End If '• From a type S? to a type T, where there is a conversion from the type S to the type T. If HasBuiltInWideningConversions(fromElement, [to]) <> s_noConversion OrElse HasBuiltInNarrowingConversions(fromElement, [to]) <> s_noConversion Then Return ConversionKind.NarrowingNullable End If End If '• From a type T? to a type S?, where there is a narrowing conversion from the type T to the type S. If (fromIsNullable AndAlso toIsNullable) Then If (HasBuiltInNarrowingConversions(fromElement, toElement) And ConversionKind.Narrowing) <> 0 Then Return ConversionKind.NarrowingNullable End If End If '• From a type T to a type S?, where there is a narrowing conversion from the type T to the type S. If (Not fromIsNullable AndAlso toIsNullable) Then If (HasBuiltInNarrowingConversions(from, toElement) And ConversionKind.Narrowing) <> 0 Then Return ConversionKind.NarrowingNullable End If End If End If Return result End Function Private Const s_byte = System_Byte Private Const s_SByte = System_SByte Private Const s_UShort = System_UInt16 Private Const s_short = System_Int16 Private Const s_UInteger = System_UInt32 Private Const s_integer = System_Int32 Private Const s_ULong = System_UInt64 Private Const s_long = System_Int64 Private Const s_decimal = System_Decimal Private Const s_single = System_Single Private Const s_double = System_Double Private Const s_string = System_String Private Const s_char = System_Char Private Const s_boolean = System_Boolean Private Const s_date = System_DateTime Private Const s_object = System_Object Private Function HasBuiltInWideningConversions(from As SpecialType, [to] As SpecialType) As ConversionKind Select Case CInt(from) 'Numeric conversions '• From Byte to UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double. Case s_byte Select Case CInt([to]) Case s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From SByte to Short, Integer, Long, Decimal, Single, or Double. Case s_SByte Select Case CInt([to]) Case s_short, s_integer, s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From UShort to UInteger, Integer, ULong, Long, Decimal, Single, or Double. Case s_UShort Select Case CInt([to]) Case s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From Short to Integer, Long, Decimal, Single or Double. Case s_short Select Case CInt([to]) Case s_integer, s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From UInteger to ULong, Long, Decimal, Single, or Double. Case s_UInteger Select Case CInt([to]) Case s_ULong, s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From Integer to Long, Decimal, Single or Double. Case s_integer Select Case CInt([to]) Case s_long, s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From ULong to Decimal, Single, or Double. Case s_ULong Select Case CInt([to]) Case s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From Long to Decimal, Single or Double. Case s_long Select Case CInt([to]) Case s_decimal, s_single, s_double Return ConversionKind.WideningNumeric End Select '• From Decimal to Single or Double. Case s_decimal Select Case CInt([to]) Case s_single, s_double Return ConversionKind.WideningNumeric End Select '• From Single to Double. Case s_single Select Case CInt([to]) Case s_double Return ConversionKind.WideningNumeric End Select 'Reference conversions '• From a reference type to a base type. Case s_string Select Case CInt([to]) Case s_object Return ConversionKind.WideningReference End Select 'String conversions '• From Char to String. Case s_char Select Case CInt([to]) Case s_string Return ConversionKind.WideningString End Select End Select Select Case CInt([to]) 'Value Type conversions '• From a value type to a base type. Case s_object Select Case CInt([from]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double, s_char, s_boolean, s_date Return ConversionKind.WideningValue End Select End Select Return s_noConversion End Function Private Function HasBuiltInNarrowingConversions(from As SpecialType, [to] As SpecialType) As ConversionKind Select Case CInt(from) 'Boolean conversions '• From Boolean to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double. Case s_boolean Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double Return ConversionKind.NarrowingBoolean End Select 'Numeric conversions '• From Byte to SByte. Case s_byte Select Case CInt([to]) Case s_SByte Return ConversionKind.NarrowingNumeric End Select '• From SByte to Byte, UShort, UInteger, or ULong. Case s_SByte Select Case CInt([to]) Case s_byte, s_UShort, s_UInteger, s_ULong Return ConversionKind.NarrowingNumeric End Select '• From UShort to Byte, SByte, or Short. Case s_UShort Select Case CInt([to]) Case s_byte, s_SByte, s_short Return ConversionKind.NarrowingNumeric End Select '• From Short to Byte, SByte, UShort, UInteger, or ULong. Case s_short Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_UInteger, s_ULong Return ConversionKind.NarrowingNumeric End Select '• From UInteger to Byte, SByte, UShort, Short, or Integer. Case s_UInteger Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_integer Return ConversionKind.NarrowingNumeric End Select '• From Integer to Byte, SByte, UShort, Short, UInteger, or ULong. Case s_integer Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_ULong Return ConversionKind.NarrowingNumeric End Select '• From ULong to Byte, SByte, UShort, Short, UInteger, Integer, or Long. Case s_ULong Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_long Return ConversionKind.NarrowingNumeric End Select '• From Long to Byte, SByte, UShort, Short, UInteger, Integer, or ULong. Case s_long Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong Return ConversionKind.NarrowingNumeric End Select '• From Decimal to Byte, SByte, UShort, Short, UInteger, Integer, ULong, or Long. Case s_decimal Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long Return ConversionKind.NarrowingNumeric End Select '• From Single to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, or Decimal. Case s_single Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal Return ConversionKind.NarrowingNumeric End Select '• From Double to Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, or Single. Case s_double Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single Return ConversionKind.NarrowingNumeric End Select 'String conversions '• From String to Char. '• From String to Boolean and from Boolean to String. '• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double. '• From String to Date and from Date to String. Case s_string Select Case CInt([to]) Case s_char, s_boolean, s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double, s_date Return ConversionKind.NarrowingString End Select 'VB Runtime Conversions Case s_object Select Case CInt([to]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double, s_char, s_boolean, s_date Return ConversionKind.NarrowingValue Case s_string Return ConversionKind.NarrowingReference End Select End Select Select Case CInt([to]) 'Boolean conversions '• From Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double to Boolean. Case s_boolean Select Case CInt([from]) Case s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double Return ConversionKind.NarrowingBoolean End Select 'String conversions '• From String to Boolean and from Boolean to String. '• Conversions between String and Byte, SByte, UShort, Short, UInteger, Integer, ULong, Long, Decimal, Single, or Double. '• From String to Date and from Date to String. Case s_string Select Case CInt([from]) Case s_boolean, s_byte, s_SByte, s_UShort, s_short, s_UInteger, s_integer, s_ULong, s_long, s_decimal, s_single, s_double, s_date Return ConversionKind.NarrowingString End Select End Select Return s_noConversion End Function <Fact()> Public Sub EnumConversions() CompileAndVerify( <compilation name="VBEnumConversions"> <file name="a.vb"> Option Strict Off Imports System Imports System.Globalization Imports System.Collections.Generic Module Module1 Sub Main() Dim BoFalse As Boolean Dim BoTrue As Boolean Dim SB As SByte Dim By As Byte Dim Sh As Short Dim US As UShort Dim [In] As Integer Dim UI As UInteger Dim Lo As Long Dim UL As ULong Dim De As Decimal Dim Si As Single Dim [Do] As Double Dim St As String Dim Ob As Object Dim Tc As TypeCode Dim TcAsVT As ValueType BoFalse = False BoTrue = True SB = 1 By = 2 Sh = 3 US = 4 [In] = 5 UI = 6 Lo = 7 UL = 8 Si = 10 [Do] = 11 De = 9D St = "12" Ob = 13 Tc = TypeCode.Decimal TcAsVT = Tc System.Console.WriteLine("Conversions to enum:") PrintResultTc(BoFalse) PrintResultTc(BoTrue) PrintResultTc(SB) PrintResultTc(By) PrintResultTc(Sh) PrintResultTc(US) PrintResultTc([In]) PrintResultTc(UI) PrintResultTc(Lo) PrintResultTc(UL) PrintResultTc(Si) PrintResultTc([Do]) PrintResultTc(De) PrintResultTc(Ob) PrintResultTc(St) PrintResultTc(TcAsVT) System.Console.WriteLine() System.Console.WriteLine("Conversions from enum:") PrintResultBo(Tc) PrintResultSB(Tc) PrintResultBy(Tc) PrintResultSh(Tc) PrintResultUs(Tc) PrintResultIn(Tc) PrintResultUI(Tc) PrintResultLo(Tc) PrintResultUL(Tc) PrintResultSi(Tc) PrintResultDo(Tc) PrintResultDe(Tc) PrintResultOb(Tc) PrintResultSt(Tc) PrintResultValueType(Tc) End Sub Sub PrintResultTc(val As TypeCode) System.Console.WriteLine("TypeCode: {0}", val) End Sub Sub PrintResultBo(val As Boolean) System.Console.WriteLine("Boolean: {0}", val) End Sub Sub PrintResultSB(val As SByte) System.Console.WriteLine("SByte: {0}", val) End Sub Sub PrintResultBy(val As Byte) System.Console.WriteLine("Byte: {0}", val) End Sub Sub PrintResultSh(val As Short) System.Console.WriteLine("Short: {0}", val) End Sub Sub PrintResultUs(val As UShort) System.Console.WriteLine("UShort: {0}", val) End Sub Sub PrintResultIn(val As Integer) System.Console.WriteLine("Integer: {0}", val) End Sub Sub PrintResultUI(val As UInteger) System.Console.WriteLine("UInteger: {0}", val) End Sub Sub PrintResultLo(val As Long) System.Console.WriteLine("Long: {0}", val) End Sub Sub PrintResultUL(val As ULong) System.Console.WriteLine("ULong: {0}", val) End Sub Sub PrintResultDe(val As Decimal) System.Console.WriteLine("Decimal: {0}", val) End Sub Sub PrintResultSi(val As Single) System.Console.WriteLine("Single: {0}", val) End Sub Sub PrintResultDo(val As Double) System.Console.WriteLine("Double: {0}", val) End Sub Sub PrintResultSt(val As String) System.Console.WriteLine("String: {0}", val) End Sub Sub PrintResultOb(val As Object) System.Console.WriteLine("Object: {0}", val) End Sub Sub PrintResultValueType(val As ValueType) System.Console.WriteLine("ValueType: {0}", val) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ Conversions to enum: TypeCode: Empty TypeCode: -1 TypeCode: Object TypeCode: DBNull TypeCode: Boolean TypeCode: Char TypeCode: SByte TypeCode: Byte TypeCode: Int16 TypeCode: UInt16 TypeCode: UInt32 TypeCode: Int64 TypeCode: Int32 TypeCode: Single TypeCode: UInt64 TypeCode: Decimal Conversions from enum: Boolean: True SByte: 15 Byte: 15 Short: 15 UShort: 15 Integer: 15 UInteger: 15 Long: 15 ULong: 15 Single: 15 Double: 15 Decimal: 15 Object: Decimal String: 15 ValueType: Decimal ]]>) End Sub <Fact()> Public Sub ConversionDiagnostic1() Dim compilationDef = <compilation name="VBConversionsDiagnostic1"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim [In] As Integer [In] = Console.WriteLine() [In] = CType(Console.WriteLine(), Integer) [In] = CType(1, UnknownType) [In] = CType(unknownValue, Integer) [In] = CType(unknownValue, UnknownType) Dim tr As System.TypedReference = Nothing Dim ai As System.ArgIterator = Nothing Dim ra As System.RuntimeArgumentHandle = Nothing Dim Ob As Object Ob = tr Ob = ai Ob = ra Ob = CType(tr, Object) Ob = CType(ai, Object) Ob = CType(ra, Object) Dim vt As ValueType vt = tr vt = ai vt = ra vt = CType(tr, ValueType) vt = CType(ai, ValueType) vt = CType(ra, ValueType) Dim collection As Microsoft.VisualBasic.Collection = Nothing Dim _collection As _Collection = Nothing collection = _collection _collection = collection collection = CType(_collection, Microsoft.VisualBasic.Collection) _collection = CType(collection, _Collection) Dim Si As Single Dim De As Decimal [In] = Int64.MaxValue [In] = CInt(Int64.MaxValue) Si = System.Double.MaxValue Si = CSng(System.Double.MaxValue) De = System.Double.MaxValue De = CDec(System.Double.MaxValue) De = 10.0F De = CDec(10.0F) Dim Da As DateTime = Nothing [In] = Da [In] = CInt(Da) Da = [In] Da = CDate([In]) Dim [Do] As Double = Nothing Dim Ch As Char = Nothing [Do] = Da [Do] = CDbl(Da) Da = [Do] Da = CDate([Do]) [In] = Ch [In] = CInt(Ch) Ch = [In] Ch = CChar([In]) Dim InArray As Integer() = Nothing Dim ObArray As Object() = Nothing Dim VtArray As ValueType() = Nothing ObArray = InArray ObArray = CType(InArray, Object()) VtArray = InArray VtArray = CType(InArray, ValueType()) Dim TC1Array As TestClass1() = Nothing Dim TC2Array As TestClass2() = Nothing TC1Array = TC2Array TC2Array = CType(TC1Array, TestClass2()) Dim InArray2 As Integer(,) = Nothing InArray = InArray2 InArray2 = CType(InArray, Integer(,)) Dim TI1Array As TestInterface1() = Nothing InArray = TI1Array TI1Array = CType(InArray, TestInterface1()) End Sub End Module Interface TestInterface1 End Interface Interface _Collection End Interface Class TestClass1 End Class Class TestClass2 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_NarrowingConversionCollection2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.ERR_NarrowingConversionDisallowed2, "10.0F").WithArguments("Single", "Decimal"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1")) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1")) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Custom)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "_collection").WithArguments("Implicit conversion from '_Collection' to 'Collection'."), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "collection").WithArguments("Implicit conversion from 'Collection' to '_Collection'."), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "Int64.MaxValue").WithArguments("Integer"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "System.Double.MaxValue").WithArguments("Decimal"), Diagnostic(ERRID.WRN_ImplicitConversionSubst1, "10.0F").WithArguments("Implicit conversion from 'Single' to 'Decimal'."), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC2Array").WithArguments("TestClass2()", "TestClass1()", "TestClass2", "TestClass1"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray2").WithArguments("Integer(*,*)", "Integer()"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TI1Array").WithArguments("TestInterface1()", "Integer()", "TestInterface1", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1")) End Sub <Fact()> Public Sub DirectCastDiagnostic1() Dim compilationDef = <compilation name="DirectCastDiagnostic1"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim [In] As Integer [In] = DirectCast(Console.WriteLine(), Integer) [In] = DirectCast(1, UnknownType) [In] = DirectCast(unknownValue, Integer) [In] = DirectCast(unknownValue, UnknownType) Dim tr As System.TypedReference = Nothing Dim ai As System.ArgIterator = Nothing Dim ra As System.RuntimeArgumentHandle = Nothing Dim Ob As Object Ob = DirectCast(tr, Object) Ob = DirectCast(ai, Object) Ob = DirectCast(ra, Object) Dim vt As ValueType vt = DirectCast(tr, ValueType) vt = DirectCast(ai, ValueType) vt = DirectCast(ra, ValueType) Dim collection As Microsoft.VisualBasic.Collection = Nothing Dim _collection As _Collection = Nothing collection = DirectCast(_collection, Microsoft.VisualBasic.Collection) _collection = DirectCast(collection, _Collection) Dim Si As Single Dim De As Decimal [In] = DirectCast(Int64.MaxValue, Int32) De = DirectCast(System.Double.MaxValue, System.Decimal) Dim Da As DateTime = Nothing [In] = DirectCast(Da, Int32) Da = DirectCast([In], DateTime) Dim [Do] As Double = Nothing Dim Ch As Char = Nothing [Do] = DirectCast(Da, System.Double) Da = DirectCast([Do], DateTime) [In] = DirectCast(Ch, Int32) Ch = DirectCast([In], System.Char) Dim InArray As Integer() = Nothing Dim ObArray As Object() = Nothing Dim VtArray As ValueType() = Nothing ObArray = DirectCast(InArray, Object()) VtArray = DirectCast(InArray, ValueType()) Dim TC1Array As TestClass1() = Nothing Dim TC2Array As TestClass2() = Nothing TC2Array = DirectCast(TC1Array, TestClass2()) Dim InArray2 As Integer(,) = Nothing InArray2 = DirectCast(InArray, Integer(,)) Dim TI1Array As TestInterface1() = Nothing TI1Array = DirectCast(InArray, TestInterface1()) Dim St As String = Nothing Dim ChArray As Char() = Nothing Ch = DirectCast(St, System.Char) St = DirectCast(Ch, System.String) St = DirectCast(ChArray, System.String) ChArray = DirectCast(St, System.Char()) [In] = DirectCast([In], System.Int32) Si = DirectCast(Si, System.Single) [Do] = DirectCast([Do], System.Double) [Do] = DirectCast(Si, System.Double) End Sub End Module Interface TestInterface1 End Interface Interface _Collection End Interface Class TestClass1 End Class Class TestClass2 End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"), Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"), Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"), Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"), Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"), Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double")) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_TypeMismatch2, "Int64.MaxValue").WithArguments("Long", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "System.Double.MaxValue").WithArguments("Double", "Decimal"), Diagnostic(ERRID.ERR_TypeMismatch2, "Da").WithArguments("Date", "Integer"), Diagnostic(ERRID.ERR_TypeMismatch2, "[In]").WithArguments("Integer", "Date"), Diagnostic(ERRID.ERR_DateToDoubleConversion, "Da"), Diagnostic(ERRID.ERR_DoubleToDateConversion, "[Do]"), Diagnostic(ERRID.ERR_CharToIntegralTypeMismatch1, "Ch").WithArguments("Integer"), Diagnostic(ERRID.ERR_IntegralToCharTypeMismatch1, "[In]").WithArguments("Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char"), Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"), Diagnostic(ERRID.WRN_ObsoleteIdentityDirectCastForValueType, "[In]"), Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "Si"), Diagnostic(ERRID.ERR_IdentityDirectCastForFloat, "[Do]"), Diagnostic(ERRID.ERR_TypeMismatch2, "Si").WithArguments("Single", "Double")) End Sub <Fact()> Public Sub TryCastDiagnostic1() Dim compilationDef = <compilation name="TryCastDiagnostic1"> <file name="a.vb"> Imports System Module Module1 Sub Main() Dim [In] As Integer [In] = TryCast(Console.WriteLine(), Integer) [In] = TryCast(1, UnknownType) [In] = TryCast(unknownValue, Integer) [In] = TryCast(unknownValue, UnknownType) Dim tr As System.TypedReference = Nothing Dim ai As System.ArgIterator = Nothing Dim ra As System.RuntimeArgumentHandle = Nothing Dim Ob As Object Ob = TryCast(tr, Object) Ob = TryCast(ai, Object) Ob = TryCast(ra, Object) Dim vt As ValueType vt = TryCast(tr, ValueType) vt = TryCast(ai, ValueType) vt = TryCast(ra, ValueType) Dim collection As Microsoft.VisualBasic.Collection = Nothing Dim _collection As _Collection = Nothing collection = TryCast(_collection, Microsoft.VisualBasic.Collection) _collection = TryCast(collection, _Collection) Dim De As Decimal [In] = TryCast(Int64.MaxValue, Int32) De = TryCast(System.Double.MaxValue, System.Decimal) Dim Ch As Char = Nothing Dim InArray As Integer() = Nothing Dim ObArray As Object() = Nothing Dim VtArray As ValueType() = Nothing ObArray = TryCast(InArray, Object()) VtArray = TryCast(InArray, ValueType()) Dim TC1Array As TestClass1() = Nothing Dim TC2Array As TestClass2() = Nothing TC2Array = TryCast(TC1Array, TestClass2()) Dim InArray2 As Integer(,) = Nothing InArray2 = TryCast(InArray, Integer(,)) Dim TI1Array As TestInterface1() = Nothing TI1Array = TryCast(InArray, TestInterface1()) Dim St As String = Nothing Dim ChArray As Char() = Nothing Ch = TryCast(St, System.Char) St = TryCast(Ch, System.String) St = TryCast(ChArray, System.String) ChArray = TryCast(St, System.Char()) End Sub End Module Interface TestInterface1 End Interface Interface _Collection End Interface Class TestClass1 End Class Class TestClass2 End Class Class TestClass3(Of T) Sub Test(val As Object) Dim x As T = TryCast(val, T) End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.On)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"), Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"), Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T")) compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(compilationDef, New VisualBasicCompilationOptions(OutputKind.ConsoleApplication).WithOptionStrict(OptionStrict.Off)) compilation.VerifyDiagnostics( Diagnostic(ERRID.ERR_VoidValue, "Console.WriteLine()"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_NameNotDeclared1, "unknownValue").WithArguments("unknownValue"), Diagnostic(ERRID.ERR_UndefinedType1, "UnknownType").WithArguments("UnknownType"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.ERR_RestrictedConversion1, "tr").WithArguments("System.TypedReference"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ai").WithArguments("System.ArgIterator"), Diagnostic(ERRID.ERR_RestrictedConversion1, "ra").WithArguments("System.RuntimeArgumentHandle"), Diagnostic(ERRID.WRN_InterfaceConversion2, "_collection").WithArguments("_Collection", "Microsoft.VisualBasic.Collection"), Diagnostic(ERRID.WRN_InterfaceConversion2, "collection").WithArguments("Microsoft.VisualBasic.Collection", "_Collection"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "Int32").WithArguments("Integer"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Decimal").WithArguments("Decimal"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "Object()", "Integer"), Diagnostic(ERRID.ERR_ConvertObjectArrayMismatch3, "InArray").WithArguments("Integer()", "System.ValueType()", "Integer"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "TC1Array").WithArguments("TestClass1()", "TestClass2()", "TestClass1", "TestClass2"), Diagnostic(ERRID.ERR_ConvertArrayRankMismatch2, "InArray").WithArguments("Integer()", "Integer(*,*)"), Diagnostic(ERRID.ERR_ConvertArrayMismatch4, "InArray").WithArguments("Integer()", "TestInterface1()", "Integer", "TestInterface1"), Diagnostic(ERRID.ERR_TryCastOfValueType1, "System.Char").WithArguments("Char"), Diagnostic(ERRID.ERR_TypeMismatch2, "Ch").WithArguments("Char", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "ChArray").WithArguments("Char()", "String"), Diagnostic(ERRID.ERR_TypeMismatch2, "St").WithArguments("String", "Char()"), Diagnostic(ERRID.ERR_TryCastOfUnconstrainedTypeParam1, "T").WithArguments("T")) End Sub <Fact()> Public Sub ExplicitConversions1() ' the argument past to CDate("") is following system setting, ' so "1/2/2012" could be Jan 2nd OR Feb 1st Dim currCulture = System.Threading.Thread.CurrentThread.CurrentCulture System.Threading.Thread.CurrentThread.CurrentCulture = New System.Globalization.CultureInfo("en-US") Try Dim compilationDef = <compilation name="VBExplicitConversions1"> <file name="lib.vb"> <%= My.Resources.Resource.PrintResultTestSource %> </file> <file name="a.vb"> Option Strict Off Imports System Imports System.Collections.Generic Module Module1 Sub Main() PrintResult(CObj(Nothing)) PrintResult(CBool(Nothing)) PrintResult(CByte(Nothing)) 'PrintResult(CChar(Nothing)) PrintResult(CDate(Nothing)) PrintResult(CDec(Nothing)) PrintResult(CDbl(Nothing)) PrintResult(CInt(Nothing)) PrintResult(CLng(Nothing)) PrintResult(CSByte(Nothing)) PrintResult(CShort(Nothing)) PrintResult(CSng(Nothing)) PrintResult(CStr(Nothing)) PrintResult(CUInt(Nothing)) PrintResult(CULng(Nothing)) PrintResult(CUShort(Nothing)) PrintResult(CType(Nothing, System.Object)) PrintResult(CType(Nothing, System.Boolean)) PrintResult(CType(Nothing, System.Byte)) 'PrintResult(CType(Nothing, System.Char)) PrintResult(CType(Nothing, System.DateTime)) PrintResult(CType(Nothing, System.Decimal)) PrintResult(CType(Nothing, System.Double)) PrintResult(CType(Nothing, System.Int32)) PrintResult(CType(Nothing, System.Int64)) PrintResult(CType(Nothing, System.SByte)) PrintResult(CType(Nothing, System.Int16)) PrintResult(CType(Nothing, System.Single)) PrintResult(CType(Nothing, System.String)) PrintResult(CType(Nothing, System.UInt32)) PrintResult(CType(Nothing, System.UInt64)) PrintResult(CType(Nothing, System.UInt16)) PrintResult(CType(Nothing, System.Guid)) PrintResult(CType(Nothing, System.ValueType)) PrintResult(CByte(300)) PrintResult(CObj("String")) PrintResult(CBool("False")) PrintResult(CByte("1")) PrintResult(CChar("a")) PrintResult(CDate("11/12/2001 12:00:00 AM")) PrintResult(CDec("-2")) PrintResult(CDbl("3")) PrintResult(CInt("-4")) PrintResult(CLng("5")) PrintResult(CSByte("-6")) PrintResult(CShort("7")) PrintResult(CSng("-8")) PrintResult(CStr(9)) PrintResult(CUInt("10")) PrintResult(CULng("11")) PrintResult(CUShort("12")) End Sub Function Int32ToInt32(val As System.Int32) As Int32 Return CInt(val) End Function Function SingleToSingle(val As System.Single) As Single Return CSng(val) End Function Function DoubleToDouble(val As System.Double) As Double Return CDbl(val) End Function End Module </file> </compilation> CompileAndVerify(compilationDef, options:=TestOptions.ReleaseExe.WithOverflowChecks(False), expectedOutput:=<![CDATA[ Object: [] Boolean: False Byte: 0 Date: 1/1/0001 12:00:00 AM Decimal: 0 Double: 0 Integer: 0 Long: 0 SByte: 0 Short: 0 Single: 0 String: [] UInteger: 0 ULong: 0 UShort: 0 Object: [] Boolean: False Byte: 0 Date: 1/1/0001 12:00:00 AM Decimal: 0 Double: 0 Integer: 0 Long: 0 SByte: 0 Short: 0 Single: 0 String: [] UInteger: 0 ULong: 0 UShort: 0 Guid: 00000000-0000-0000-0000-000000000000 ValueType: [] Byte: 44 Object: [String] Boolean: False Byte: 1 Char: [a] Date: 11/12/2001 12:00:00 AM Decimal: -2 Double: 3 Integer: -4 Long: 5 SByte: -6 Short: 7 Single: -8 String: [9] UInteger: 10 ULong: 11 UShort: 12 ]]>). VerifyIL("Module1.Int32ToInt32", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } ]]>). VerifyIL("Module1.SingleToSingle", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } ]]>). VerifyIL("Module1.DoubleToDouble", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } ]]>) Catch ex As Exception Finally System.Threading.Thread.CurrentThread.CurrentCulture = currCulture End Try End Sub <Fact()> Public Sub DirectCast1() Dim compilationDef = <compilation name="DirectCast1"> <file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file> <file name="a.vb"> Option Strict Off Imports System Imports System.Globalization Imports System.Collections.Generic Module Module1 Sub Main() PrintResult(DirectCast(Nothing, System.Object)) PrintResult(DirectCast(Nothing, System.Boolean)) PrintResult(DirectCast(Nothing, System.Byte)) PrintResult(DirectCast(Nothing, System.DateTime)) PrintResult(DirectCast(Nothing, System.Decimal)) PrintResult(DirectCast(Nothing, System.Double)) PrintResult(DirectCast(Nothing, System.Int32)) PrintResult(DirectCast(Nothing, System.Int64)) PrintResult(DirectCast(Nothing, System.SByte)) PrintResult(DirectCast(Nothing, System.Int16)) PrintResult(DirectCast(Nothing, System.Single)) PrintResult(DirectCast(Nothing, System.String)) PrintResult(DirectCast(Nothing, System.UInt32)) PrintResult(DirectCast(Nothing, System.UInt64)) PrintResult(DirectCast(Nothing, System.UInt16)) PrintResult(DirectCast(Nothing, System.ValueType)) PrintResult(DirectCast(1, System.Object)) PrintResult(DirectCast(3.5R, System.ValueType)) Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c") Dim guidObject As Object = guid PrintResult(DirectCast(guid, System.Object)) PrintResult(DirectCast(guidObject, System.Guid)) PrintResult(DirectCast("abc", System.IComparable)) PrintResult(GenericParamTestHelperOfString.NothingToT()) 'PrintResult(DirectCast(Nothing, System.Guid)) PrintResult(GenericParamTestHelperOfGuid.NothingToT()) PrintResult(GenericParamTestHelperOfString.TToObject("abcd")) PrintResult(GenericParamTestHelperOfString.TToObject(Nothing)) PrintResult(GenericParamTestHelperOfGuid.TToObject(guid)) PrintResult(GenericParamTestHelperOfString.TToIComparable("abcde")) PrintResult(GenericParamTestHelperOfString.TToIComparable(Nothing)) PrintResult(GenericParamTestHelperOfGuid.TToIComparable(guid)) PrintResult(GenericParamTestHelperOfGuid.ObjectToT(guidObject)) 'PrintResult(GenericParamTestHelperOfGuid.ObjectToT(Nothing)) PrintResult(GenericParamTestHelperOfString.ObjectToT("ObString")) PrintResult(GenericParamTestHelperOfString.ObjectToT(Nothing)) 'PrintResult(GenericParamTestHelper(Of System.Int32).ObjectToT(Nothing)) PrintResult(GenericParamTestHelperOfString.IComparableToT("abcde")) PrintResult(GenericParamTestHelperOfString.IComparableToT(Nothing)) PrintResult(GenericParamTestHelperOfGuid.IComparableToT(guid)) 'PrintResult(GenericParamTestHelperOfGuid.IComparableToT(Nothing)) 'PrintResult(GenericParamTestHelper(Of System.Double).IComparableToT(Nothing)) Dim [In] As Integer = 23 Dim De As Decimal = 24 PrintResult(DirectCast([In], System.Int32)) PrintResult(DirectCast(De, System.Decimal)) End Sub Function NothingToGuid() As Guid Return DirectCast(Nothing, System.Guid) End Function Function NothingToInt32() As Int32 Return DirectCast(Nothing, System.Int32) End Function Function Int32ToInt32(val As System.Int32) As Int32 Return DirectCast(val, System.Int32) End Function Class GenericParamTestHelper(Of T) Public Shared Function ObjectToT(val As Object) As T Return DirectCast(val, T) End Function Public Shared Function TToObject(val As T) As Object Return DirectCast(val, Object) End Function Public Shared Function TToIComparable(val As T) As IComparable Return DirectCast(val, IComparable) End Function Public Shared Function IComparableToT(val As IComparable) As T Return DirectCast(val, T) End Function Public Shared Function NothingToT() As T Return DirectCast(Nothing, T) End Function End Class Class GenericParamTestHelperOfString Inherits GenericParamTestHelper(Of String) End Class Class GenericParamTestHelperOfGuid Inherits GenericParamTestHelper(Of Guid) End Class End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ Object: [] Boolean: False Byte: 0 Date: 1/1/0001 12:00:00 AM Decimal: 0 Double: 0 Integer: 0 Long: 0 SByte: 0 Short: 0 Single: 0 String: [] UInteger: 0 ULong: 0 UShort: 0 ValueType: [] Object: [1] ValueType: [3.5] Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c IComparable: [abc] String: [] Guid: 00000000-0000-0000-0000-000000000000 Object: [abcd] Object: [] Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] IComparable: [abcde] IComparable: [] IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c String: [ObString] String: [] String: [abcde] String: [] Guid: 8c5dffd5-1778-4dd3-a9f5-6a9708146a7c Integer: 23 Decimal: 24 ]]>). VerifyIL("Module1.NothingToGuid", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldnull IL_0001: unbox.any "System.Guid" IL_0006: ret } ]]>). VerifyIL("Module1.NothingToInt32", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } ]]>). VerifyIL("Module1.Int32ToInt32", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper(Of T).ObjectToT", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: unbox.any "T" IL_0006: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper(Of T).TToObject", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: box "T" IL_0006: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper(Of T).TToIComparable", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: box "T" IL_0006: castclass "System.IComparable" IL_000b: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper(Of T).IComparableToT", <![CDATA[ { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: unbox.any "T" IL_0006: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper(Of T).NothingToT", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init (T V_0) IL_0000: ldloca.s V_0 IL_0002: initobj "T" IL_0008: ldloc.0 IL_0009: ret } ]]>) End Sub <Fact()> Public Sub TryCast1() Dim compilationDef = <compilation name="TryCast1"> <file name="helper.vb"><%= My.Resources.Resource.PrintResultTestSource %></file> <file name="a.vb"> Option Strict Off Imports System Imports System.Globalization Imports System.Collections.Generic Module Module1 Sub Main() PrintResult(TryCast(Nothing, System.Object)) PrintResult(TryCast(Nothing, System.String)) PrintResult(TryCast(Nothing, System.ValueType)) PrintResult(TryCast(1, System.Object)) PrintResult(TryCast(3.5R, System.ValueType)) PrintResult(TryCast(CObj("sdf"), System.String)) PrintResult(TryCast(New Object(), System.String)) Dim guid As Guid = New Guid("8c5dffd5-1778-4dd3-a9f5-6a9708146a7c") Dim guidObject As Object = guid PrintResult(TryCast(guid, System.Object)) PrintResult(TryCast("abc", System.IComparable)) PrintResult(TryCast(guid, System.IComparable)) PrintResult(GenericParamTestHelperOfString2.NothingToT()) PrintResult(GenericParamTestHelperOfString1.TToObject("abcd")) PrintResult(GenericParamTestHelperOfString1.TToObject(Nothing)) PrintResult(GenericParamTestHelperOfGuid1.TToObject(guid)) PrintResult(GenericParamTestHelperOfString1.TToIComparable("abcde")) PrintResult(GenericParamTestHelperOfString1.TToIComparable(Nothing)) PrintResult(GenericParamTestHelperOfGuid1.TToIComparable(guid)) PrintResult(GenericParamTestHelperOfString2.ObjectToT("ObString")) PrintResult(GenericParamTestHelperOfString2.ObjectToT(Nothing)) PrintResult(GenericParamTestHelperOfString2.IComparableToT("abcde")) PrintResult(GenericParamTestHelperOfString2.IComparableToT(Nothing)) End Sub Function NothingToString() As String Return DirectCast(Nothing, System.String) End Function Function StringToString(val As String) As String Return DirectCast(val, System.String) End Function Class GenericParamTestHelper1(Of T) Public Shared Function TToObject(val As T) As Object Return TryCast(val, Object) End Function Public Shared Function TToIComparable(val As T) As IComparable Return TryCast(val, IComparable) End Function End Class Class GenericParamTestHelper2(Of T As Class) Public Shared Function ObjectToT(val As Object) As T Return TryCast(val, T) End Function Public Shared Function IComparableToT(val As IComparable) As T Return TryCast(val, T) End Function Public Shared Function NothingToT() As T Return TryCast(Nothing, T) End Function End Class Class GenericParamTestHelperOfString1 Inherits GenericParamTestHelper1(Of String) End Class Class GenericParamTestHelperOfString2 Inherits GenericParamTestHelper2(Of String) End Class Class GenericParamTestHelperOfGuid1 Inherits GenericParamTestHelper1(Of Guid) End Class End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ Object: [] String: [] ValueType: [] Object: [1] ValueType: [3.5] String: [sdf] String: [] Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] IComparable: [abc] IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] String: [] Object: [abcd] Object: [] Object: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] IComparable: [abcde] IComparable: [] IComparable: [8c5dffd5-1778-4dd3-a9f5-6a9708146a7c] String: [ObString] String: [] String: [abcde] String: [] ]]>). VerifyIL("Module1.NothingToString", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret } ]]>). VerifyIL("Module1.StringToString", <![CDATA[ { // Code size 2 (0x2) .maxstack 1 IL_0000: ldarg.0 IL_0001: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper2(Of T).ObjectToT", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst "T" IL_0006: unbox.any "T" IL_000b: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper1(Of T).TToObject", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: box "T" IL_0006: isinst "Object" IL_000b: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper1(Of T).TToIComparable", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: box "T" IL_0006: isinst "System.IComparable" IL_000b: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper2(Of T).IComparableToT", <![CDATA[ { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: isinst "T" IL_0006: unbox.any "T" IL_000b: ret } ]]>). VerifyIL("Module1.GenericParamTestHelper2(Of T).NothingToT", <![CDATA[ { // Code size 10 (0xa) .maxstack 1 .locals init (T V_0) IL_0000: ldloca.s V_0 IL_0002: initobj "T" IL_0008: ldloc.0 IL_0009: ret } ]]>) End Sub <Fact()> Public Sub Bug4281_1() Dim compilationDef = <compilation name="Bug4281_1"> <file name="a.vb"> Imports System Module M Sub Main() Dim x As Object= DirectCast(1, DayOfWeek) System.Console.WriteLine(x.GetType()) System.Console.WriteLine(x) Dim y As Integer = 2 x = DirectCast(y, DayOfWeek) System.Console.WriteLine(x.GetType()) System.Console.WriteLine(x) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ System.DayOfWeek Monday System.DayOfWeek Tuesday ]]>). VerifyIL("M.Main", <![CDATA[ { // Code size 55 (0x37) .maxstack 2 IL_0000: ldc.i4.1 IL_0001: box "System.DayOfWeek" IL_0006: dup IL_0007: callvirt "Function Object.GetType() As System.Type" IL_000c: call "Sub System.Console.WriteLine(Object)" IL_0011: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0016: call "Sub System.Console.WriteLine(Object)" IL_001b: ldc.i4.2 IL_001c: box "System.DayOfWeek" IL_0021: dup IL_0022: callvirt "Function Object.GetType() As System.Type" IL_0027: call "Sub System.Console.WriteLine(Object)" IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_0031: call "Sub System.Console.WriteLine(Object)" IL_0036: ret } ]]>) End Sub <Fact()> Public Sub Bug4281_2() Dim compilationDef = <compilation name="Bug4281_2"> <file name="a.vb"> Imports System Module M Sub Main() Dim x As DayOfWeek= DirectCast(1, DayOfWeek) System.Console.WriteLine(x.GetType()) System.Console.WriteLine(x) Dim y As Integer = 2 x = DirectCast(y, DayOfWeek) System.Console.WriteLine(x.GetType()) System.Console.WriteLine(x) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ System.DayOfWeek 1 System.DayOfWeek 2 ]]>) End Sub <Fact()> Public Sub Bug4256() Dim compilationDef = <compilation name="Bug4256"> <file name="a.vb"> Option Strict On Module M Sub Main() Dim x As Object = 1 Dim y As Long = CLng(x) System.Console.WriteLine(y.GetType()) System.Console.WriteLine(y) End Sub End Module </file> </compilation> CompileAndVerify(compilationDef, expectedOutput:=<![CDATA[ System.Int64 1 ]]>) End Sub <WorkItem(11515, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub TestIdentityConversionForGenericNested() Dim vbCompilation = CreateVisualBasicCompilation("TestIdentityConversionForGenericNested", <![CDATA[Option Strict On Imports System Public Module Program Class C1(Of T) Public EnumField As E1 Structure S1 Public EnumField As E1 End Structure Enum E1 A End Enum End Class Sub Main() Dim outer As New C1(Of Integer) Dim inner As New C1(Of Integer).S1 outer.EnumField = C1(Of Integer).E1.A inner.EnumField = C1(Of Integer).E1.A Foo(inner.EnumField) End Sub Sub Foo(x As Object) Console.WriteLine(x.ToString) End Sub End Module]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication)) CompileAndVerify(vbCompilation, expectedOutput:="A").VerifyDiagnostics() End Sub <WorkItem(544919, "DevDiv")> <Fact> Public Sub TestClassifyConversion() Dim source = <text> Imports System Module Program Sub M() End Sub Sub M(l As Long) End Sub Sub M(s As Short) End Sub Sub M(i As Integer) End Sub Sub Main() Dim ii As Integer = 0 Console.WriteLine(ii) Dim jj As Short = 1 Console.WriteLine(jj) Dim ss As String = String.Empty Console.WriteLine(ss) ' Perform conversion classification here. End Sub End Module </text>.Value Dim tree = Parse(source) Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree) Dim model = c.GetSemanticModel(tree) ' Get VariableDeclaratorSyntax corresponding to variable 'ii' above. Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax) ' Get TypeSymbol corresponding to above VariableDeclaratorSyntax. Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol) Assert.Equal(1, local.Locations.Length) ' Perform ClassifyConversion for expressions from within the above SyntaxTree. Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax) Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType) Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax) conversion = model.ClassifyConversion(sourceExpression2, targetType) Assert.True(conversion.IsNarrowing) Assert.True(conversion.IsString) ' Perform ClassifyConversion for constructed expressions ' at the position identified by the comment "' Perform ..." above. Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj") Dim position = source.IndexOf("' ", StringComparison.Ordinal) conversion = model.ClassifyConversion(position, sourceExpression3, targetType) Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss") conversion = model.ClassifyConversion(position, sourceExpression4, targetType) Assert.True(conversion.IsNarrowing) Assert.True(conversion.IsString) Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L") conversion = model.ClassifyConversion(position, sourceExpression5, targetType) ' This is Widening because the numeric literal constant 100L can be converted to Integer ' without any data loss. Note: This is special for literal constants. Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <WorkItem(544919, "DevDiv")> <Fact> Public Sub TestClassifyConversionStaticLocal() Dim source = <text> Imports System Module Program Sub M() End Sub Sub M(l As Long) End Sub Sub M(s As Short) End Sub Sub M(i As Integer) End Sub Sub Main() Static ii As Integer = 0 Console.WriteLine(ii) Static jj As Short = 1 Console.WriteLine(jj) Static ss As String = String.Empty Console.WriteLine(ss) ' Perform conversion classification here. End Sub End Module </text>.Value Dim tree = Parse(source) Dim c As VisualBasicCompilation = VisualBasicCompilation.Create("MyCompilation").AddReferences(MscorlibRef).AddSyntaxTrees(tree) Dim model = c.GetSemanticModel(tree) ' Get VariableDeclaratorSyntax corresponding to variable 'ii' above. Dim variableDeclarator = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ii", StringComparison.Ordinal)).Parent.Parent, VariableDeclaratorSyntax) ' Get TypeSymbol corresponding to above VariableDeclaratorSyntax. Dim targetType As TypeSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol).Type Dim local As LocalSymbol = CType(model.GetDeclaredSymbol(variableDeclarator.Names.Single), LocalSymbol) Assert.Equal(1, local.Locations.Length) ' Perform ClassifyConversion for expressions from within the above SyntaxTree. Dim sourceExpression1 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("jj)", StringComparison.Ordinal)).Parent, ExpressionSyntax) Dim conversion As Conversion = model.ClassifyConversion(sourceExpression1, targetType) Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) Dim sourceExpression2 = CType(tree.GetCompilationUnitRoot().FindToken(source.IndexOf("ss)", StringComparison.Ordinal)).Parent, ExpressionSyntax) conversion = model.ClassifyConversion(sourceExpression2, targetType) Assert.True(conversion.IsNarrowing) Assert.True(conversion.IsString) ' Perform ClassifyConversion for constructed expressions ' at the position identified by the comment "' Perform ..." above. Dim sourceExpression3 As ExpressionSyntax = SyntaxFactory.IdentifierName("jj") Dim position = source.IndexOf("' ", StringComparison.Ordinal) conversion = model.ClassifyConversion(position, sourceExpression3, targetType) Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) Dim sourceExpression4 As ExpressionSyntax = SyntaxFactory.IdentifierName("ss") conversion = model.ClassifyConversion(position, sourceExpression4, targetType) Assert.True(conversion.IsNarrowing) Assert.True(conversion.IsString) Dim sourceExpression5 As ExpressionSyntax = SyntaxFactory.ParseExpression("100L") conversion = model.ClassifyConversion(position, sourceExpression5, targetType) ' This is Widening because the numeric literal constant 100L can be converted to Integer ' without any data loss. Note: This is special for literal constants. Assert.True(conversion.IsWidening) Assert.True(conversion.IsNumeric) End Sub <WorkItem(544620, "DevDiv")> <Fact()> Public Sub Bug13088() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Public Const Z1 As Integer = 300 Public Const Z2 As Byte = Z1 Public Const Z3 As Byte = CByte(300) Public Const Z4 As Byte = DirectCast(300, Byte) Sub Main() End Sub End Module ]]></file> </compilation>) VerifyDiagnostics(compilation, Diagnostic(ERRID.ERR_ExpressionOverflow1, "Z1").WithArguments("Byte"), Diagnostic(ERRID.ERR_ExpressionOverflow1, "300").WithArguments("Byte"), Diagnostic(ERRID.ERR_TypeMismatch2, "300").WithArguments("Integer", "Byte")) Dim symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z2").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z3").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) symbol = compilation.GlobalNamespace.GetTypeMembers("Program").Single.GetMembers("Z4").Single Assert.False(DirectCast(symbol, FieldSymbol).HasConstantValue) End Sub <WorkItem(545760, "DevDiv")> <Fact()> Public Sub Bug14409() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module M1 Sub Main() Dim x As System.DayOfWeek? = 0 Test(0) End Sub Sub Test(x As System.DayOfWeek?) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation) End Sub <WorkItem(545760, "DevDiv")> <Fact()> Public Sub Bug14409_2() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module M1 Sub Main() Test(0) End Sub Sub Test(x As System.DayOfWeek?) End Sub Sub Test(x As System.TypeCode?) End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30519: Overload resolution failed because no accessible 'Test' can be called without a narrowing conversion: 'Public Sub Test(x As DayOfWeek?)': Argument matching parameter 'x' narrows from 'Integer' to 'DayOfWeek?'. 'Public Sub Test(x As TypeCode?)': Argument matching parameter 'x' narrows from 'Integer' to 'TypeCode?'. Test(0) ~~~~ </expected>) End Sub <WorkItem(571095, "DevDiv")> <Fact()> Public Sub Bug571095() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ imports System Module Module1 Sub Main() Dim Y(10, 10) As Integer 'COMPILEERROR: BC30311, "Y" For Each x As string() In Y Console.WriteLine(x) Next x 'COMPILEERROR: BC30311, "Y" For Each x As Integer(,) In Y Console.WriteLine(x) Next x End Sub End Module ]]></file> </compilation>, TestOptions.ReleaseExe) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30311: Value of type 'Integer' cannot be converted to 'String()'. For Each x As string() In Y ~ BC30311: Value of type 'Integer' cannot be converted to 'Integer(*,*)'. For Each x As Integer(,) In Y ~ </expected>) End Sub <WorkItem(31)> <Fact()> Public Sub BugCodePlex_31() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Option Strict On Module Module1 Property Value As BooleanEx? Sub Main() If Value Then End If System.Console.WriteLine("---") Value = true System.Console.WriteLine("---") Dim x as Boolean? = Value System.Console.WriteLine("---") If Value Then End If End Sub End Module Structure BooleanEx Private b As Boolean Public Sub New(value As Boolean) b = value End Sub Public Shared Widening Operator CType(value As Boolean) As BooleanEx System.Console.WriteLine("CType(value As Boolean) As BooleanEx") Return New BooleanEx(value) End Operator Public Shared Widening Operator CType(value As BooleanEx) As Boolean System.Console.WriteLine("CType(value As BooleanEx) As Boolean") Return value.b End Operator Public Shared Widening Operator CType(value As Integer) As BooleanEx System.Console.WriteLine("CType(value As Integer) As BooleanEx") Return New BooleanEx(CBool(value)) End Operator Public Shared Widening Operator CType(value As BooleanEx) As Integer System.Console.WriteLine("CType(value As BooleanEx) As Integer") Return CInt(value.b) End Operator Public Shared Widening Operator CType(value As String) As BooleanEx System.Console.WriteLine("CType(value As String) As BooleanEx") Return New BooleanEx(CBool(value)) End Operator Public Shared Widening Operator CType(value As BooleanEx) As String System.Console.WriteLine("CType(value As BooleanEx) As String") Return CStr(value.b) End Operator Public Shared Operator =(value1 As BooleanEx, value2 As Boolean) As Boolean System.Console.WriteLine("=(value1 As BooleanEx, value2 As Boolean) As Boolean") Return False End Operator Public Shared Operator <>(value1 As BooleanEx, value2 As Boolean) As Boolean System.Console.WriteLine("<>(value1 As BooleanEx, value2 As Boolean) As Boolean") Return False End Operator End Structure ]]></file> </compilation>, TestOptions.ReleaseExe) CompileAndVerify(compilation, expectedOutput:= "--- CType(value As Boolean) As BooleanEx --- CType(value As BooleanEx) As Boolean --- CType(value As BooleanEx) As Boolean") End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_01() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Integer = Double.MaxValue End Sub End Module ]]></file> </compilation>) Dim expectedErr = <expected> BC30439: Constant expression not representable in type 'Integer'. Dim x As Integer = Double.MaxValue ~~~~~~~~~~~~~~~ </expected> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedErr) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedErr) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedErr) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedErr) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedErr) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedErr) End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_02() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Integer? = Double.MaxValue End Sub End Module ]]></file> </compilation>) Dim expectedError = <expected> BC30439: Constant expression not representable in type 'Integer?'. Dim x As Integer? = Double.MaxValue ~~~~~~~~~~~~~~~ </expected> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_03() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Short = Integer.MaxValue System.Console.WriteLine(x) End Sub End Module ]]></file> </compilation>) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() Dim expectedError = <expected> BC30439: Constant expression not representable in type 'Short'. Dim x As Short = Integer.MaxValue ~~~~~~~~~~~~~~~~ </expected> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_04() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Short? = Integer.MaxValue System.Console.WriteLine(x) End Sub End Module ]]></file> </compilation>) Dim expectedIL = <![CDATA[ { // Code size 22 (0x16) .maxstack 2 .locals init (Short? V_0) //x IL_0000: nop IL_0001: ldloca.s V_0 IL_0003: ldc.i4.m1 IL_0004: call "Sub Short?..ctor(Short)" IL_0009: ldloc.0 IL_000a: box "Short?" IL_000f: call "Sub System.Console.WriteLine(Object)" IL_0014: nop IL_0015: ret } ]]> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) Dim verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() verifier.VerifyIL("Program.Main", expectedIL) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() verifier.VerifyIL("Program.Main", expectedIL) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) verifier = CompileAndVerify(compilation, expectedOutput:="-1").VerifyDiagnostics() verifier.VerifyIL("Program.Main", expectedIL) Dim expectedError = <expected> BC30439: Constant expression not representable in type 'Short?'. Dim x As Short? = Integer.MaxValue ~~~~~~~~~~~~~~~~ </expected> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) AssertTheseDiagnostics(compilation, expectedError) End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_05() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Short = CInt(Short.MaxValue) System.Console.WriteLine(x) End Sub End Module ]]></file> </compilation>) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_06() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x As Short? = CInt(Short.MaxValue) System.Console.WriteLine(x) End Sub End Module ]]></file> </compilation>) compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(False)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Custom).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.On).WithOverflowChecks(True)) CompileAndVerify(compilation, expectedOutput:="32767").VerifyDiagnostics() End Sub <WorkItem(1099862, "DevDiv")> <Fact()> Public Sub Bug1099862_07() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Module Program Sub Main(args As String()) Dim x = CType(Double.MaxValue, System.Nullable(Of Integer)) End Sub End Module ]]></file> </compilation>) Dim expectedError = <expected> BC30439: Constant expression not representable in type 'Integer?'. Dim x = CType(Double.MaxValue, System.Nullable(Of Integer)) ~~~~~~~~~~~~~~~ </expected> compilation = compilation.WithOptions(TestOptions.DebugExe.WithOptionStrict(OptionStrict.Off).WithOverflowChecks(False)) AssertTheseDiagnostics(compilation, expectedError) End Sub <WorkItem(2094, "https://github.com/dotnet/roslyn/issues/2094")> <Fact()> Public Sub DirectCastNothingToAStructure() Dim compilation = CreateCompilationWithMscorlibAndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Class Program Shared Sub Main() Try Dim val = DirectCast(Nothing, S) System.Console.WriteLine("Unexpected - 1 !!!") Catch e as System.NullReferenceException System.Console.WriteLine("Expected - 1") End Try Try M(DirectCast(Nothing, S)) System.Console.WriteLine("Unexpected - 2 !!!") Catch e as System.NullReferenceException System.Console.WriteLine("Expected - 2") End Try End Sub Shared Sub M(val as S) End Sub End Class Structure S End Structure ]]></file> </compilation>, options:=TestOptions.ReleaseExe) Dim expectedOutput = <![CDATA[ Expected - 1 Expected - 2 ]]> CompileAndVerify(compilation, expectedOutput:=expectedOutput).VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.DebugExe) CompileAndVerify(compilation, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub End Class End Namespace
droyad/roslyn
src/Compilers/VisualBasic/Test/Semantic/Semantics/Conversions.vb
Visual Basic
apache-2.0
287,249
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class frmCreate Inherits System.Windows.Forms.Form 'Form 重写 Dispose,以清理组件列表。 <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Windows 窗体设计器所必需的 Private components As System.ComponentModel.IContainer '注意: 以下过程是 Windows 窗体设计器所必需的 '可以使用 Windows 窗体设计器修改它。 '不要使用代码编辑器修改它。 <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.components = New System.ComponentModel.Container() Me.btnOpenImage = New System.Windows.Forms.Button() Me.PictureBox1 = New System.Windows.Forms.PictureBox() Me.ContextMenuStrip1 = New System.Windows.Forms.ContextMenuStrip(Me.components) Me.SaveImageToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.生成图线GToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem() Me.DisplayOffsetX = New System.Windows.Forms.TrackBar() Me.Label1 = New System.Windows.Forms.Label() Me.TextBox1 = New System.Windows.Forms.TextBox() Me.LOffset = New System.Windows.Forms.NumericUpDown() Me.Label2 = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.TOffset = New System.Windows.Forms.NumericUpDown() Me.Label4 = New System.Windows.Forms.Label() Me.ROffset = New System.Windows.Forms.NumericUpDown() Me.Label5 = New System.Windows.Forms.Label() Me.BOffset = New System.Windows.Forms.NumericUpDown() Me.btnAddChar = New System.Windows.Forms.Button() Me.BOffsetLock = New System.Windows.Forms.CheckBox() Me.TOffsetLock = New System.Windows.Forms.CheckBox() Me.ListView1 = New System.Windows.Forms.ListView() Me.ColumnHeader1 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader2 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader3 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader4 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.ColumnHeader5 = CType(New System.Windows.Forms.ColumnHeader(), System.Windows.Forms.ColumnHeader) Me.btnSaveTemplate = New System.Windows.Forms.Button() Me.btnNewTemplate = New System.Windows.Forms.Button() Me.btnOpenTemplate = New System.Windows.Forms.Button() Me.DisplayOffsetY = New System.Windows.Forms.TrackBar() Me.Label6 = New System.Windows.Forms.Label() Me.Label7 = New System.Windows.Forms.Label() Me.Button1 = New System.Windows.Forms.Button() CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).BeginInit() Me.ContextMenuStrip1.SuspendLayout() CType(Me.DisplayOffsetX, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.LOffset, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.TOffset, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.ROffset, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.BOffset, System.ComponentModel.ISupportInitialize).BeginInit() CType(Me.DisplayOffsetY, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'btnOpenImage ' Me.btnOpenImage.Location = New System.Drawing.Point(16, 89) Me.btnOpenImage.Margin = New System.Windows.Forms.Padding(4) Me.btnOpenImage.Name = "btnOpenImage" Me.btnOpenImage.Size = New System.Drawing.Size(101, 25) Me.btnOpenImage.TabIndex = 0 Me.btnOpenImage.Text = "打开图片" Me.btnOpenImage.UseVisualStyleBackColor = True ' 'PictureBox1 ' Me.PictureBox1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _ Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.PictureBox1.ContextMenuStrip = Me.ContextMenuStrip1 Me.PictureBox1.Location = New System.Drawing.Point(16, 640) Me.PictureBox1.Margin = New System.Windows.Forms.Padding(4) Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New System.Drawing.Size(850, 156) Me.PictureBox1.TabIndex = 1 Me.PictureBox1.TabStop = False ' 'ContextMenuStrip1 ' Me.ContextMenuStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.SaveImageToolStripMenuItem, Me.生成图线GToolStripMenuItem}) Me.ContextMenuStrip1.Name = "ContextMenuStrip1" Me.ContextMenuStrip1.Size = New System.Drawing.Size(160, 52) ' 'SaveImageToolStripMenuItem ' Me.SaveImageToolStripMenuItem.Name = "SaveImageToolStripMenuItem" Me.SaveImageToolStripMenuItem.Size = New System.Drawing.Size(159, 24) Me.SaveImageToolStripMenuItem.Text = "保存图片(&S)" ' '生成图线GToolStripMenuItem ' Me.生成图线GToolStripMenuItem.Name = "生成图线GToolStripMenuItem" Me.生成图线GToolStripMenuItem.Size = New System.Drawing.Size(159, 24) Me.生成图线GToolStripMenuItem.Text = "生成图线(&G)" ' 'DisplayOffsetX ' Me.DisplayOffsetX.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.DisplayOffsetX.Location = New System.Drawing.Point(198, 15) Me.DisplayOffsetX.Margin = New System.Windows.Forms.Padding(4) Me.DisplayOffsetX.Name = "DisplayOffsetX" Me.DisplayOffsetX.Size = New System.Drawing.Size(668, 56) Me.DisplayOffsetX.TabIndex = 2 ' 'Label1 ' Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(171, 140) Me.Label1.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(37, 15) Me.Label1.TabIndex = 3 Me.Label1.Text = "字符" ' 'TextBox1 ' Me.TextBox1.Location = New System.Drawing.Point(218, 137) Me.TextBox1.Margin = New System.Windows.Forms.Padding(4) Me.TextBox1.MaxLength = 1 Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New System.Drawing.Size(39, 25) Me.TextBox1.TabIndex = 4 ' 'LOffset ' Me.LOffset.Location = New System.Drawing.Point(360, 137) Me.LOffset.Margin = New System.Windows.Forms.Padding(4) Me.LOffset.Name = "LOffset" Me.LOffset.Size = New System.Drawing.Size(75, 25) Me.LOffset.TabIndex = 5 ' 'Label2 ' Me.Label2.AutoSize = True Me.Label2.ForeColor = System.Drawing.Color.Blue Me.Label2.Location = New System.Drawing.Point(266, 140) Me.Label2.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label2.Name = "Label2" Me.Label2.Size = New System.Drawing.Size(82, 15) Me.Label2.TabIndex = 6 Me.Label2.Text = "左边偏移量" ' 'Label3 ' Me.Label3.AutoSize = True Me.Label3.ForeColor = System.Drawing.Color.Red Me.Label3.Location = New System.Drawing.Point(620, 140) Me.Label3.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(82, 15) Me.Label3.TabIndex = 8 Me.Label3.Text = "上边偏移量" ' 'TOffset ' Me.TOffset.Location = New System.Drawing.Point(715, 138) Me.TOffset.Margin = New System.Windows.Forms.Padding(4) Me.TOffset.Name = "TOffset" Me.TOffset.Size = New System.Drawing.Size(75, 25) Me.TOffset.TabIndex = 7 ' 'Label4 ' Me.Label4.AutoSize = True Me.Label4.ForeColor = System.Drawing.Color.Chocolate Me.Label4.Location = New System.Drawing.Point(266, 173) Me.Label4.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label4.Name = "Label4" Me.Label4.Size = New System.Drawing.Size(82, 15) Me.Label4.TabIndex = 10 Me.Label4.Text = "右边偏移量" ' 'ROffset ' Me.ROffset.Location = New System.Drawing.Point(360, 170) Me.ROffset.Margin = New System.Windows.Forms.Padding(4) Me.ROffset.Name = "ROffset" Me.ROffset.Size = New System.Drawing.Size(75, 25) Me.ROffset.TabIndex = 9 ' 'Label5 ' Me.Label5.AutoSize = True Me.Label5.ForeColor = System.Drawing.Color.Green Me.Label5.Location = New System.Drawing.Point(443, 140) Me.Label5.Margin = New System.Windows.Forms.Padding(4, 0, 4, 0) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(82, 15) Me.Label5.TabIndex = 12 Me.Label5.Text = "下边偏移量" ' 'BOffset ' Me.BOffset.Location = New System.Drawing.Point(538, 137) Me.BOffset.Margin = New System.Windows.Forms.Padding(4) Me.BOffset.Name = "BOffset" Me.BOffset.Size = New System.Drawing.Size(75, 25) Me.BOffset.TabIndex = 11 ' 'btnAddChar ' Me.btnAddChar.Location = New System.Drawing.Point(171, 169) Me.btnAddChar.Margin = New System.Windows.Forms.Padding(4) Me.btnAddChar.Name = "btnAddChar" Me.btnAddChar.Size = New System.Drawing.Size(86, 28) Me.btnAddChar.TabIndex = 13 Me.btnAddChar.Text = "添加" Me.btnAddChar.UseVisualStyleBackColor = True ' 'BOffsetLock ' Me.BOffsetLock.AutoSize = True Me.BOffsetLock.Location = New System.Drawing.Point(446, 173) Me.BOffsetLock.Margin = New System.Windows.Forms.Padding(4) Me.BOffsetLock.Name = "BOffsetLock" Me.BOffsetLock.Size = New System.Drawing.Size(134, 19) Me.BOffsetLock.TabIndex = 14 Me.BOffsetLock.Text = "锁定下边偏移量" Me.BOffsetLock.UseVisualStyleBackColor = True ' 'TOffsetLock ' Me.TOffsetLock.AutoSize = True Me.TOffsetLock.Location = New System.Drawing.Point(623, 172) Me.TOffsetLock.Margin = New System.Windows.Forms.Padding(4) Me.TOffsetLock.Name = "TOffsetLock" Me.TOffsetLock.Size = New System.Drawing.Size(134, 19) Me.TOffsetLock.TabIndex = 15 Me.TOffsetLock.Text = "锁定上边偏移量" Me.TOffsetLock.UseVisualStyleBackColor = True ' 'ListView1 ' Me.ListView1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2, Me.ColumnHeader3, Me.ColumnHeader4, Me.ColumnHeader5}) Me.ListView1.FullRowSelect = True Me.ListView1.Location = New System.Drawing.Point(16, 205) Me.ListView1.Margin = New System.Windows.Forms.Padding(4) Me.ListView1.Name = "ListView1" Me.ListView1.Size = New System.Drawing.Size(850, 426) Me.ListView1.TabIndex = 16 Me.ListView1.UseCompatibleStateImageBehavior = False Me.ListView1.View = System.Windows.Forms.View.Details ' 'ColumnHeader1 ' Me.ColumnHeader1.Text = "字符" ' 'ColumnHeader2 ' Me.ColumnHeader2.Text = "x1" ' 'ColumnHeader3 ' Me.ColumnHeader3.Text = "y1" ' 'ColumnHeader4 ' Me.ColumnHeader4.Text = "x2" ' 'ColumnHeader5 ' Me.ColumnHeader5.Text = "y2" ' 'btnSaveTemplate ' Me.btnSaveTemplate.Location = New System.Drawing.Point(16, 122) Me.btnSaveTemplate.Margin = New System.Windows.Forms.Padding(4) Me.btnSaveTemplate.Name = "btnSaveTemplate" Me.btnSaveTemplate.Size = New System.Drawing.Size(102, 28) Me.btnSaveTemplate.TabIndex = 17 Me.btnSaveTemplate.Text = "保存模板" Me.btnSaveTemplate.UseVisualStyleBackColor = True ' 'btnNewTemplate ' Me.btnNewTemplate.Location = New System.Drawing.Point(16, 12) Me.btnNewTemplate.Name = "btnNewTemplate" Me.btnNewTemplate.Size = New System.Drawing.Size(102, 33) Me.btnNewTemplate.TabIndex = 18 Me.btnNewTemplate.Text = "新建模板" Me.btnNewTemplate.UseVisualStyleBackColor = True ' 'btnOpenTemplate ' Me.btnOpenTemplate.Location = New System.Drawing.Point(16, 51) Me.btnOpenTemplate.Name = "btnOpenTemplate" Me.btnOpenTemplate.Size = New System.Drawing.Size(102, 29) Me.btnOpenTemplate.TabIndex = 19 Me.btnOpenTemplate.Text = "打开模板" Me.btnOpenTemplate.UseVisualStyleBackColor = True ' 'DisplayOffsetY ' Me.DisplayOffsetY.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _ Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.DisplayOffsetY.Location = New System.Drawing.Point(198, 68) Me.DisplayOffsetY.Margin = New System.Windows.Forms.Padding(4) Me.DisplayOffsetY.Name = "DisplayOffsetY" Me.DisplayOffsetY.Size = New System.Drawing.Size(668, 56) Me.DisplayOffsetY.TabIndex = 20 ' 'Label6 ' Me.Label6.AutoSize = True Me.Label6.Location = New System.Drawing.Point(124, 30) Me.Label6.Name = "Label6" Me.Label6.Size = New System.Drawing.Size(67, 15) Me.Label6.TabIndex = 21 Me.Label6.Text = "水平移动" ' 'Label7 ' Me.Label7.AutoSize = True Me.Label7.Location = New System.Drawing.Point(124, 89) Me.Label7.Name = "Label7" Me.Label7.Size = New System.Drawing.Size(67, 15) Me.Label7.TabIndex = 22 Me.Label7.Text = "垂直移动" ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(16, 157) Me.Button1.Name = "Button1" Me.Button1.Size = New System.Drawing.Size(148, 41) Me.Button1.TabIndex = 23 Me.Button1.Text = "下一个字符" Me.Button1.UseVisualStyleBackColor = True ' 'frmCreate ' Me.AutoScaleDimensions = New System.Drawing.SizeF(8.0!, 15.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(879, 809) Me.Controls.Add(Me.Button1) Me.Controls.Add(Me.Label7) Me.Controls.Add(Me.Label6) Me.Controls.Add(Me.DisplayOffsetY) Me.Controls.Add(Me.btnOpenTemplate) Me.Controls.Add(Me.btnNewTemplate) Me.Controls.Add(Me.btnSaveTemplate) Me.Controls.Add(Me.ListView1) Me.Controls.Add(Me.TOffsetLock) Me.Controls.Add(Me.BOffsetLock) Me.Controls.Add(Me.btnAddChar) Me.Controls.Add(Me.Label5) Me.Controls.Add(Me.BOffset) Me.Controls.Add(Me.Label4) Me.Controls.Add(Me.ROffset) Me.Controls.Add(Me.Label3) Me.Controls.Add(Me.TOffset) Me.Controls.Add(Me.Label2) Me.Controls.Add(Me.LOffset) Me.Controls.Add(Me.TextBox1) Me.Controls.Add(Me.Label1) Me.Controls.Add(Me.DisplayOffsetX) Me.Controls.Add(Me.PictureBox1) Me.Controls.Add(Me.btnOpenImage) Me.Margin = New System.Windows.Forms.Padding(4) Me.Name = "frmCreate" Me.Text = "模版编辑器" CType(Me.PictureBox1, System.ComponentModel.ISupportInitialize).EndInit() Me.ContextMenuStrip1.ResumeLayout(False) CType(Me.DisplayOffsetX, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.LOffset, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.TOffset, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.ROffset, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.BOffset, System.ComponentModel.ISupportInitialize).EndInit() CType(Me.DisplayOffsetY, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents btnOpenImage As System.Windows.Forms.Button Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox Friend WithEvents DisplayOffsetX As System.Windows.Forms.TrackBar Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents TextBox1 As System.Windows.Forms.TextBox Friend WithEvents LOffset As System.Windows.Forms.NumericUpDown Friend WithEvents Label2 As System.Windows.Forms.Label Friend WithEvents Label3 As System.Windows.Forms.Label Friend WithEvents TOffset As System.Windows.Forms.NumericUpDown Friend WithEvents Label4 As System.Windows.Forms.Label Friend WithEvents ROffset As System.Windows.Forms.NumericUpDown Friend WithEvents Label5 As System.Windows.Forms.Label Friend WithEvents BOffset As System.Windows.Forms.NumericUpDown Friend WithEvents btnAddChar As System.Windows.Forms.Button Friend WithEvents BOffsetLock As System.Windows.Forms.CheckBox Friend WithEvents TOffsetLock As System.Windows.Forms.CheckBox Friend WithEvents ListView1 As System.Windows.Forms.ListView Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader3 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader4 As System.Windows.Forms.ColumnHeader Friend WithEvents ColumnHeader5 As System.Windows.Forms.ColumnHeader Friend WithEvents btnSaveTemplate As System.Windows.Forms.Button Friend WithEvents btnNewTemplate As System.Windows.Forms.Button Friend WithEvents btnOpenTemplate As System.Windows.Forms.Button Friend WithEvents DisplayOffsetY As System.Windows.Forms.TrackBar Friend WithEvents Label6 As System.Windows.Forms.Label Friend WithEvents Label7 As System.Windows.Forms.Label Friend WithEvents ContextMenuStrip1 As System.Windows.Forms.ContextMenuStrip Friend WithEvents SaveImageToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents 生成图线GToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem Friend WithEvents Button1 As System.Windows.Forms.Button End Class
twd2/HandWritingGenerator
HandWritingGenerator/frmCreate.Designer.vb
Visual Basic
mit
19,393
Imports SistFoncreagro.BussinessEntities Imports SistFoncreagro.BussinesLogic Public Class VentanaRegistroFacturaDetalle Inherits System.Web.UI.Page Dim detOcFac As IDetOcxFacturaBL Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then lblDocumento.Text = Request.QueryString("Doc") lblTipo.Text = Request.QueryString("tip") lblMonto.Text = Request.QueryString("Mont") If Request.QueryString("tipoRend") = 1 Then rdbPrecio.Checked = True rdbCantidad.Enabled = False GridView1.Columns(2).Visible = True GridView1.Columns(3).Visible = False GridView2.Columns(3).HeaderText = "Monto" GridView2.Columns(4).Visible = False GridView2.Columns(5).Visible = False Else 'rdbPrecio.Enabled = False End If 'If Session("fact") = "True" Then ' GridView2.Columns(0).Visible = False 'End If If GridView2.Rows.Count > 0 Then rdbPrecio.Enabled = False rdbCantidad.Enabled = False End If End If End Sub Protected Sub btnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGuardar.Click detOcFac = New DetOcxFacturaBL Dim lista As New List(Of DetOcxFactura) If rdbCantidad.Checked = True Then For i = 0 To GridView1.Rows.Count - 1 Dim cbSelec As CheckBox = CType(Me.GridView1.Rows(i).FindControl("cbDetalle"), CheckBox) If cbSelec.Checked = True Then Dim detOc As New DetOcxFactura Dim txtIdDetalleOc As TextBox = CType(Me.GridView1.Rows(i).FindControl("txtIdDetOc"), TextBox) Dim txtCantidad As TextBox = CType(Me.GridView1.Rows(i).FindControl("txtCantidadDet"), TextBox) detOc.IdOcxFactura = CInt(Request.QueryString("idOcfac")) detOc.IdDetalleOrdenCompra = CInt(txtIdDetalleOc.Text) detOc.Cantidad = CDec(txtCantidad.Text) lista.Add(detOc) End If Next detOcFac.SaveDetOcxFactura1(lista) Else If rdbPrecio.Checked = True Then For i = 0 To GridView1.Rows.Count - 1 Dim cbSelec As CheckBox = CType(Me.GridView1.Rows(i).FindControl("cbDetalle"), CheckBox) If cbSelec.Checked = True Then Dim detOc As New DetOcxFactura Dim txtIdDetalleOc As TextBox = CType(Me.GridView1.Rows(i).FindControl("txtIdDetOc"), TextBox) Dim txtMonto As TextBox = CType(Me.GridView1.Rows(i).FindControl("txtPrecioDet"), TextBox) detOc.IdOcxFactura = CInt(Request.QueryString("idOcfac")) detOc.IdDetalleOrdenCompra = CInt(txtIdDetalleOc.Text) detOc.PCompraDetalle = CDec(txtMonto.Text) lista.Add(detOc) End If Next detOcFac.SaveDetOcxFacturaPrec1(lista) GridView2.Columns(3).HeaderText = "Monto" GridView2.Columns(4).Visible = False GridView2.Columns(5).Visible = False End If End If GridView1.DataBind() GridView2.DataBind() End Sub Protected Sub GridView2_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView2.RowCommand detOcFac = New DetOcxFacturaBL Dim index = e.CommandArgument If e.CommandName = "Eliminar" Then Dim txtIdDetalleRequerimiento As TextBox = CType(GridView2.Rows(index).FindControl("txtIdDet"), TextBox) detOcFac.DeleteDetOcxFactura(CInt(txtIdDetalleRequerimiento.Text)) GridView2.DataBind() GridView1.DataBind() End If End Sub Function Validar(ByVal cant As Decimal) As Boolean If cant = 0 Then Return False Else Return True End If End Function Protected Sub LinkButton1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles LinkButton1.Click Response.Redirect("VentanaRegistroFactura.aspx?idoc=" + Session("id") + "&nro=" + Session("NroOrden") + "&are=" + Session("ar") + "&fac=" + Session("fact") + "&Mont=" + Session("Monto") + "&Moned=" + Session("Moneda")) End Sub Protected Sub btnFinalizar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnFinalizar.Click detOcFac = New DetOcxFacturaBL detOcFac.FinalizarRegistroDetOcxFactura(CInt(Request.QueryString("idOcfac"))) Response.Redirect("VentanaRegistroFactura.aspx?idoc=" + Session("id") + "&nro=" + Session("NroOrden") + "&are=" + Session("ar") + "&fac=" + Session("fact") + "&Mont=" + Session("Monto") + "&Moned=" + Session("Moneda")) End Sub Protected Sub rdbPrecio_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rdbPrecio.CheckedChanged If rdbPrecio.Checked = True Then GridView1.Columns(2).Visible = True GridView1.Columns(3).Visible = False End If End Sub Protected Sub rdbCantidad_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rdbCantidad.CheckedChanged If rdbCantidad.Checked = True Then GridView1.Columns(2).Visible = False GridView1.Columns(3).Visible = True End If End Sub End Class
crackper/SistFoncreagro
SistFoncreagro.WebSite/Logistica/VentanaRegistroFacturaDetalle.aspx.vb
Visual Basic
mit
5,694
Partial Class RepPoaMeses 'NOTE: The following procedure is required by the telerik Reporting Designer 'It can be modified using the telerik Reporting Designer. 'Do not modify it using the code editor. Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(RepPoaMeses)) Dim FormattingRule1 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule2 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule3 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule4 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule5 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule6 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule7 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim FormattingRule8 As Telerik.Reporting.Drawing.FormattingRule = New Telerik.Reporting.Drawing.FormattingRule() Dim ReportParameter1 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim ReportParameter2 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim ReportParameter3 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter() Dim StyleRule1 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule2 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule3 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Dim StyleRule4 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule() Me.SDSRepPoaMeses = New Telerik.Reporting.SqlDataSource() Me.labelsGroupHeader = New Telerik.Reporting.GroupHeaderSection() Me.TextBox3 = New Telerik.Reporting.TextBox() Me.TextBox55 = New Telerik.Reporting.TextBox() Me.TextBox56 = New Telerik.Reporting.TextBox() Me.TextBox60 = New Telerik.Reporting.TextBox() Me.TextBox59 = New Telerik.Reporting.TextBox() Me.TextBox57 = New Telerik.Reporting.TextBox() Me.TextBox58 = New Telerik.Reporting.TextBox() Me.TextBox76 = New Telerik.Reporting.TextBox() Me.TextBox75 = New Telerik.Reporting.TextBox() Me.labelsGroupFooter = New Telerik.Reporting.GroupFooterSection() Me.labelsGroup = New Telerik.Reporting.Group() Me.componenteGroupHeader = New Telerik.Reporting.GroupHeaderSection() Me.TextBox79 = New Telerik.Reporting.TextBox() Me.componenteGroupFooter = New Telerik.Reporting.GroupFooterSection() Me.componenteGroup = New Telerik.Reporting.Group() Me.actividadGroupHeader = New Telerik.Reporting.GroupHeaderSection() Me.TextBox80 = New Telerik.Reporting.TextBox() Me.actividadGroupFooter = New Telerik.Reporting.GroupFooterSection() Me.actividadGroup = New Telerik.Reporting.Group() Me.pageHeader = New Telerik.Reporting.PageHeaderSection() Me.TextBox2 = New Telerik.Reporting.TextBox() Me.PictureBox1 = New Telerik.Reporting.PictureBox() Me.TextBox39 = New Telerik.Reporting.TextBox() Me.TextBox38 = New Telerik.Reporting.TextBox() Me.TextBox9 = New Telerik.Reporting.TextBox() Me.TextBox8 = New Telerik.Reporting.TextBox() Me.TextBox7 = New Telerik.Reporting.TextBox() Me.TextBox6 = New Telerik.Reporting.TextBox() Me.TextBox1 = New Telerik.Reporting.TextBox() Me.pageFooter = New Telerik.Reporting.PageFooterSection() Me.reportHeader = New Telerik.Reporting.ReportHeaderSection() Me.reportFooter = New Telerik.Reporting.ReportFooterSection() Me.detail = New Telerik.Reporting.DetailSection() Me.TextBox62 = New Telerik.Reporting.TextBox() Me.TextBox61 = New Telerik.Reporting.TextBox() Me.eneEjeDataTextBox = New Telerik.Reporting.TextBox() Me.eneProgDataTextBox = New Telerik.Reporting.TextBox() Me.unidadDataTextBox = New Telerik.Reporting.TextBox() Me.nomTareaDataTextBox = New Telerik.Reporting.TextBox() Me.TextBox4 = New Telerik.Reporting.TextBox() Me.TextBox5 = New Telerik.Reporting.TextBox() Me.TextBox10 = New Telerik.Reporting.TextBox() CType(Me, System.ComponentModel.ISupportInitialize).BeginInit() ' 'SDSRepPoaMeses ' Me.SDSRepPoaMeses.ConnectionString = "cnx" Me.SDSRepPoaMeses.Name = "SDSRepPoaMeses" Me.SDSRepPoaMeses.Parameters.AddRange(New Telerik.Reporting.SqlDataSourceParameter() {New Telerik.Reporting.SqlDataSourceParameter("@Anio", System.Data.DbType.Int32, "=Parameters.Anio.Value"), New Telerik.Reporting.SqlDataSourceParameter("@IdProyecto", System.Data.DbType.Int32, "=Parameters.IdProyecto.Value"), New Telerik.Reporting.SqlDataSourceParameter("@Meses", System.Data.DbType.AnsiString, "=Parameters.Meses.Value")}) Me.SDSRepPoaMeses.SelectCommand = "dbo.RepPoaTecnicoXMeses" Me.SDSRepPoaMeses.SelectCommandType = Telerik.Reporting.SqlDataSourceCommandType.StoredProcedure ' 'labelsGroupHeader ' Me.labelsGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.labelsGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox3, Me.TextBox55, Me.TextBox56, Me.TextBox60, Me.TextBox59, Me.TextBox57, Me.TextBox58, Me.TextBox76, Me.TextBox75}) Me.labelsGroupHeader.Name = "labelsGroupHeader" Me.labelsGroupHeader.PrintOnEveryPage = True ' 'TextBox3 ' Me.TextBox3.CanGrow = True Me.TextBox3.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(22.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox3.Name = "TextBox3" Me.TextBox3.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989998340606689R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox3.Style.BackgroundColor = System.Drawing.Color.Navy Me.TextBox3.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox3.Style.Color = System.Drawing.Color.White Me.TextBox3.Style.Font.Bold = True Me.TextBox3.Style.Font.Name = "Arial" Me.TextBox3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox3.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox3.StyleName = "Caption" Me.TextBox3.Value = "% EJEC." ' 'TextBox55 ' Me.TextBox55.CanGrow = True Me.TextBox55.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox55.Name = "TextBox55" Me.TextBox55.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989998340606689R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox55.Style.BackgroundColor = System.Drawing.Color.Navy Me.TextBox55.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox55.Style.Color = System.Drawing.Color.White Me.TextBox55.Style.Font.Bold = True Me.TextBox55.Style.Font.Name = "Arial" Me.TextBox55.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox55.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox55.StyleName = "Caption" Me.TextBox55.Value = "EJEC." ' 'TextBox56 ' Me.TextBox56.CanGrow = True Me.TextBox56.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox56.Name = "TextBox56" Me.TextBox56.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989998340606689R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox56.Style.BackgroundColor = System.Drawing.Color.Navy Me.TextBox56.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox56.Style.Color = System.Drawing.Color.White Me.TextBox56.Style.Font.Bold = True Me.TextBox56.Style.Font.Name = "Arial" Me.TextBox56.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox56.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox56.StyleName = "Caption" Me.TextBox56.Value = "PROG." ' 'TextBox60 ' Me.TextBox60.CanGrow = True Me.TextBox60.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(19.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox60.Name = "TextBox60" Me.TextBox60.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0001999139785767R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox60.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox60.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox60.Style.Font.Bold = True Me.TextBox60.Style.Font.Name = "Arial" Me.TextBox60.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox60.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox60.StyleName = "Caption" Me.TextBox60.Value = "='META '+ Parameters.Anio.Value" ' 'TextBox59 ' Me.TextBox59.CanGrow = True Me.TextBox59.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(18.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox59.Name = "TextBox59" Me.TextBox59.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0001999139785767R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox59.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox59.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox59.Style.Font.Bold = True Me.TextBox59.Style.Font.Name = "Arial" Me.TextBox59.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox59.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox59.StyleName = "Caption" Me.TextBox59.Value = "META TOTAL" ' 'TextBox57 ' Me.TextBox57.CanGrow = True Me.TextBox57.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(16.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox57.Name = "TextBox57" Me.TextBox57.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox57.Style.BackgroundColor = System.Drawing.Color.Navy Me.TextBox57.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox57.Style.Color = System.Drawing.Color.White Me.TextBox57.Style.Font.Bold = True Me.TextBox57.Style.Font.Name = "Arial" Me.TextBox57.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox57.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox57.StyleName = "Caption" Me.TextBox57.Value = "UNIDAD" ' 'TextBox58 ' Me.TextBox58.CanGrow = True Me.TextBox58.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox58.Name = "TextBox58" Me.TextBox58.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(15.999799728393555R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox58.Style.BackgroundColor = System.Drawing.Color.Navy Me.TextBox58.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox58.Style.Color = System.Drawing.Color.White Me.TextBox58.Style.Font.Bold = True Me.TextBox58.Style.Font.Name = "Arial" Me.TextBox58.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox58.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox58.StyleName = "Caption" Me.TextBox58.Value = "SUBACTIVIDAD/TAREA" ' 'TextBox76 ' Me.TextBox76.CanGrow = True Me.TextBox76.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox76.Name = "TextBox76" Me.TextBox76.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0001999139785767R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox76.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox76.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox76.Style.Font.Bold = True Me.TextBox76.Style.Font.Name = "Arial" Me.TextBox76.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox76.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox76.StyleName = "Caption" Me.TextBox76.Value = "% EJEC. ACUM." ' 'TextBox75 ' Me.TextBox75.CanGrow = True Me.TextBox75.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(23.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox75.Name = "TextBox75" Me.TextBox75.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0001999139785767R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.99989956617355347R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox75.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox75.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox75.Style.Font.Bold = True Me.TextBox75.Style.Font.Name = "Arial" Me.TextBox75.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox75.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox75.StyleName = "Caption" Me.TextBox75.Value = "EJEC. ACUM." ' 'labelsGroupFooter ' Me.labelsGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.71437495946884155R, Telerik.Reporting.Drawing.UnitType.Cm) Me.labelsGroupFooter.Name = "labelsGroupFooter" Me.labelsGroupFooter.Style.Visible = False ' 'labelsGroup ' Me.labelsGroup.GroupFooter = Me.labelsGroupFooter Me.labelsGroup.GroupHeader = Me.labelsGroupHeader Me.labelsGroup.Name = "labelsGroup" ' 'componenteGroupHeader ' Me.componenteGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.componenteGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox79}) Me.componenteGroupHeader.Name = "componenteGroupHeader" ' 'TextBox79 ' Me.TextBox79.CanGrow = True Me.TextBox79.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox79.Name = "TextBox79" Me.TextBox79.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(25.000202178955078R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox79.Style.BackgroundColor = System.Drawing.Color.CornflowerBlue Me.TextBox79.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox79.Style.Font.Bold = True Me.TextBox79.Style.Font.Name = "Arial" Me.TextBox79.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox79.StyleName = "Data" Me.TextBox79.Value = "= Fields.Componente" ' 'componenteGroupFooter ' Me.componenteGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.71437495946884155R, Telerik.Reporting.Drawing.UnitType.Cm) Me.componenteGroupFooter.Name = "componenteGroupFooter" Me.componenteGroupFooter.Style.Visible = False ' 'componenteGroup ' Me.componenteGroup.GroupFooter = Me.componenteGroupFooter Me.componenteGroup.GroupHeader = Me.componenteGroupHeader Me.componenteGroup.Groupings.AddRange(New Telerik.Reporting.Grouping() {New Telerik.Reporting.Grouping("=Fields.Componente")}) Me.componenteGroup.Name = "componenteGroup" ' 'actividadGroupHeader ' Me.actividadGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.actividadGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox80}) Me.actividadGroupHeader.Name = "actividadGroupHeader" ' 'TextBox80 ' Me.TextBox80.CanGrow = True Me.TextBox80.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox80.Name = "TextBox80" Me.TextBox80.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(25.000202178955078R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox80.Style.BackgroundColor = System.Drawing.Color.PaleTurquoise Me.TextBox80.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox80.Style.Font.Bold = True Me.TextBox80.Style.Font.Name = "Arial" Me.TextBox80.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox80.StyleName = "Data" Me.TextBox80.Value = "= Fields.Actividad" ' 'actividadGroupFooter ' Me.actividadGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.71437495946884155R, Telerik.Reporting.Drawing.UnitType.Cm) Me.actividadGroupFooter.Name = "actividadGroupFooter" Me.actividadGroupFooter.Style.Visible = False ' 'actividadGroup ' Me.actividadGroup.GroupFooter = Me.actividadGroupFooter Me.actividadGroup.GroupHeader = Me.actividadGroupHeader Me.actividadGroup.Groupings.AddRange(New Telerik.Reporting.Grouping() {New Telerik.Reporting.Grouping("=Fields.Actividad")}) Me.actividadGroup.Name = "actividadGroup" ' 'pageHeader ' Me.pageHeader.Height = New Telerik.Reporting.Drawing.Unit(3.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.pageHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox2, Me.PictureBox1, Me.TextBox39, Me.TextBox38, Me.TextBox9, Me.TextBox8, Me.TextBox7, Me.TextBox6, Me.TextBox1}) Me.pageHeader.Name = "pageHeader" ' 'TextBox2 ' Me.TextBox2.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox2.Name = "TextBox2" Me.TextBox2.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(24.973596572875977R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox2.Style.Font.Bold = True Me.TextBox2.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox2.Value = "='EJECUCIÓN DE ACTIVIDADES '+ Parameters.Anio.Value" ' 'PictureBox1 ' Me.PictureBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.PictureBox1.MimeType = "image/jpeg" Me.PictureBox1.Name = "PictureBox1" Me.PictureBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(4.5R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.PictureBox1.Sizing = Telerik.Reporting.Drawing.ImageSizeMode.Stretch Me.PictureBox1.Style.BackgroundImage.ImageData = Global.SistFoncreagro.Report.My.Resources.Resources.logotipo_foncreagro Me.PictureBox1.Style.BackgroundImage.MimeType = "image/jpeg" Me.PictureBox1.Style.BackgroundImage.Repeat = Telerik.Reporting.Drawing.BackgroundRepeat.NoRepeat Me.PictureBox1.Value = CType(resources.GetObject("PictureBox1.Value"), Object) ' 'TextBox39 ' Me.TextBox39.Format = "{0:d}" Me.TextBox39.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox39.Name = "TextBox39" Me.TextBox39.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9997971057891846R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox39.Style.Font.Name = "Arial" Me.TextBox39.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox39.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox39.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox39.StyleName = "PageInfo" Me.TextBox39.Value = "Hora:" ' 'TextBox38 ' Me.TextBox38.Format = "{0:t}" Me.TextBox38.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(23.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox38.Name = "TextBox38" Me.TextBox38.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9999727010726929R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox38.Style.Font.Name = "Arial" Me.TextBox38.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox38.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox38.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox38.StyleName = "PageInfo" Me.TextBox38.Value = "= Now()" ' 'TextBox9 ' Me.TextBox9.Format = "{0:d}" Me.TextBox9.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(23.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.49999985098838806R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox9.Name = "TextBox9" Me.TextBox9.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9999727010726929R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox9.Style.Font.Name = "Arial" Me.TextBox9.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox9.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox9.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox9.StyleName = "PageInfo" Me.TextBox9.Value = "= Now()" ' 'TextBox8 ' Me.TextBox8.Format = "{0:d}" Me.TextBox8.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.49999985098838806R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox8.Name = "TextBox8" Me.TextBox8.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9997971057891846R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox8.Style.Font.Name = "Arial" Me.TextBox8.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox8.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox8.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox8.StyleName = "PageInfo" Me.TextBox8.Value = "Fecha:" ' 'TextBox7 ' Me.TextBox7.Format = "{0:d}" Me.TextBox7.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0001000221527647227R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox7.Name = "TextBox7" Me.TextBox7.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9997971057891846R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox7.Style.Font.Name = "Arial" Me.TextBox7.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox7.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox7.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox7.StyleName = "PageInfo" Me.TextBox7.Value = "Página:" ' 'TextBox6 ' Me.TextBox6.Format = "{0:g}" Me.TextBox6.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(23.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0001000221527647227R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox6.Name = "TextBox6" Me.TextBox6.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.9999727010726929R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox6.Style.Font.Name = "Arial" Me.TextBox6.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox6.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.TextBox6.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Left Me.TextBox6.StyleName = "PageInfo" Me.TextBox6.Value = "=PageNumber+' de '+ PageCount" ' 'TextBox1 ' Me.TextBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox1.Name = "TextBox1" Me.TextBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(25.000202178955078R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox1.Style.Font.Bold = True Me.TextBox1.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox1.Value = "PROGRAMA DE GENERACIÓN DE OPORTUNIDADES DE DESARROLLO EN LOS DISTRITOS DE HUASMÍ" & _ "N, SOROCHUCO, LA ENCAÑADA Y BAMBAMARCA" ' 'pageFooter ' Me.pageFooter.Height = New Telerik.Reporting.Drawing.Unit(0.71437495946884155R, Telerik.Reporting.Drawing.UnitType.Cm) Me.pageFooter.Name = "pageFooter" ' 'reportHeader ' Me.reportHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.reportHeader.Name = "reportHeader" Me.reportHeader.Style.Visible = True ' 'reportFooter ' Me.reportFooter.Height = New Telerik.Reporting.Drawing.Unit(0.71437495946884155R, Telerik.Reporting.Drawing.UnitType.Cm) Me.reportFooter.Name = "reportFooter" Me.reportFooter.Style.Visible = False ' 'detail ' Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.detail.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox62, Me.TextBox61, Me.eneEjeDataTextBox, Me.eneProgDataTextBox, Me.unidadDataTextBox, Me.nomTareaDataTextBox, Me.TextBox4, Me.TextBox5, Me.TextBox10}) Me.detail.Name = "detail" ' 'TextBox62 ' Me.TextBox62.CanGrow = True Me.TextBox62.Format = "{0:N0}" Me.TextBox62.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(19.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox62.Name = "TextBox62" Me.TextBox62.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox62.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox62.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox62.Style.Font.Name = "Arial" Me.TextBox62.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox62.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox62.StyleName = "Data" Me.TextBox62.Value = "= Fields.MetaAnio" ' 'TextBox61 ' Me.TextBox61.CanGrow = True Me.TextBox61.Format = "{0:N0}" Me.TextBox61.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(18.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox61.Name = "TextBox61" Me.TextBox61.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox61.Style.BackgroundColor = System.Drawing.Color.FromArgb(CType(CType(192, Byte), Integer), CType(CType(192, Byte), Integer), CType(CType(255, Byte), Integer)) Me.TextBox61.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox61.Style.Font.Name = "Arial" Me.TextBox61.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox61.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox61.StyleName = "Data" Me.TextBox61.Value = "= Fields.MetaTotal" ' 'eneEjeDataTextBox ' Me.eneEjeDataTextBox.CanGrow = True Me.eneEjeDataTextBox.Format = "{0:N0}" Me.eneEjeDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.eneEjeDataTextBox.Name = "eneEjeDataTextBox" Me.eneEjeDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.eneEjeDataTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.eneEjeDataTextBox.Style.Font.Name = "Arial" Me.eneEjeDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.eneEjeDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.eneEjeDataTextBox.StyleName = "Data" Me.eneEjeDataTextBox.Value = "= Fields.Ejecutado" ' 'eneProgDataTextBox ' Me.eneProgDataTextBox.CanGrow = True Me.eneProgDataTextBox.Format = "{0:N0}" Me.eneProgDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.eneProgDataTextBox.Name = "eneProgDataTextBox" Me.eneProgDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.eneProgDataTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.eneProgDataTextBox.Style.Font.Name = "Arial" Me.eneProgDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.eneProgDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.eneProgDataTextBox.StyleName = "Data" Me.eneProgDataTextBox.Value = "= Fields.Programado" ' 'unidadDataTextBox ' Me.unidadDataTextBox.CanGrow = True Me.unidadDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(16.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.unidadDataTextBox.Name = "unidadDataTextBox" Me.unidadDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.unidadDataTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.unidadDataTextBox.Style.Font.Name = "Arial" Me.unidadDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.unidadDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.unidadDataTextBox.StyleName = "Data" Me.unidadDataTextBox.Value = "=Fields.Unidad" ' 'nomTareaDataTextBox ' Me.nomTareaDataTextBox.CanGrow = True Me.nomTareaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nomTareaDataTextBox.Name = "nomTareaDataTextBox" Me.nomTareaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(16.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.nomTareaDataTextBox.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.nomTareaDataTextBox.Style.Font.Name = "Arial" Me.nomTareaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.nomTareaDataTextBox.StyleName = "Data" Me.nomTareaDataTextBox.Value = "= Fields.tarea" ' 'TextBox4 ' Me.TextBox4.CanGrow = True FormattingRule1.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.Porc", Telerik.Reporting.FilterOperator.LessThan, "0.5")}) FormattingRule1.Style.BackgroundColor = System.Drawing.Color.Red FormattingRule2.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.Porc", Telerik.Reporting.FilterOperator.Equal, "0.5")}) FormattingRule2.Style.BackgroundColor = System.Drawing.Color.Yellow FormattingRule3.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.Porc", Telerik.Reporting.FilterOperator.GreaterThan, "0.5")}) FormattingRule3.Style.BackgroundColor = System.Drawing.Color.Lime FormattingRule4.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.Porc", Telerik.Reporting.FilterOperator.Equal, "-1")}) Me.TextBox4.ConditionalFormatting.AddRange(New Telerik.Reporting.Drawing.FormattingRule() {FormattingRule1, FormattingRule2, FormattingRule3, FormattingRule4}) Me.TextBox4.Format = "{0:P0}" Me.TextBox4.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(21.999795913696289R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox4.Name = "TextBox4" Me.TextBox4.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox4.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox4.Style.Font.Name = "Arial" Me.TextBox4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox4.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox4.StyleName = "Data" Me.TextBox4.Value = "= IIf(Fields.Porc=-1,'', Fields.Porc)" ' 'TextBox5 ' Me.TextBox5.CanGrow = True Me.TextBox5.Format = "{0:N0}" Me.TextBox5.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(23.000200271606445R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox5.Name = "TextBox5" Me.TextBox5.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox5.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox5.Style.Font.Name = "Arial" Me.TextBox5.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox5.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox5.StyleName = "Data" Me.TextBox5.Value = "= Fields.Acumulado" ' 'TextBox10 ' Me.TextBox10.CanGrow = True FormattingRule5.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.PorcAcum", Telerik.Reporting.FilterOperator.LessThan, "0.5")}) FormattingRule5.Style.BackgroundColor = System.Drawing.Color.Red FormattingRule6.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.PorcAcum", Telerik.Reporting.FilterOperator.Equal, "0.5")}) FormattingRule6.Style.BackgroundColor = System.Drawing.Color.Yellow FormattingRule7.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.PorcAcum", Telerik.Reporting.FilterOperator.GreaterThan, "0.5")}) FormattingRule7.Style.BackgroundColor = System.Drawing.Color.Lime FormattingRule8.Filters.AddRange(New Telerik.Reporting.Filter() {New Telerik.Reporting.Filter("=Fields.PorcAcum", Telerik.Reporting.FilterOperator.Equal, "-1")}) Me.TextBox10.ConditionalFormatting.AddRange(New Telerik.Reporting.Drawing.FormattingRule() {FormattingRule5, FormattingRule6, FormattingRule7, FormattingRule8}) Me.TextBox10.Format = "{0:P0}" Me.TextBox10.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(24.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox10.Name = "TextBox10" Me.TextBox10.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)) Me.TextBox10.Style.BorderStyle.Default = Telerik.Reporting.Drawing.BorderType.Solid Me.TextBox10.Style.Font.Name = "Arial" Me.TextBox10.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point) Me.TextBox10.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center Me.TextBox10.StyleName = "Data" Me.TextBox10.Value = "= IIf(Fields.PorcAcum=-1,'', Fields.PorcAcum)" ' 'RepPoaMeses ' Me.DataSource = Me.SDSRepPoaMeses Me.Groups.AddRange(New Telerik.Reporting.Group() {Me.labelsGroup, Me.componenteGroup, Me.actividadGroup}) Me.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.labelsGroupHeader, Me.labelsGroupFooter, Me.componenteGroupHeader, Me.componenteGroupFooter, Me.actividadGroupHeader, Me.actividadGroupFooter, Me.pageHeader, Me.pageFooter, Me.reportHeader, Me.reportFooter, Me.detail}) Me.PageSettings.Landscape = True Me.PageSettings.Margins.Bottom = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Left = New Telerik.Reporting.Drawing.Unit(2.5R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Right = New Telerik.Reporting.Drawing.Unit(2.2000000476837158R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.Margins.Top = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm) Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.A4 ReportParameter1.Name = "Anio" ReportParameter1.Text = "Anio" ReportParameter1.Type = Telerik.Reporting.ReportParameterType.[Integer] ReportParameter1.Visible = True ReportParameter2.Name = "IdProyecto" ReportParameter2.Text = "IdProyecto" ReportParameter2.Type = Telerik.Reporting.ReportParameterType.[Integer] ReportParameter2.Visible = True ReportParameter3.Name = "Meses" ReportParameter3.Text = "Meses" ReportParameter3.Visible = True Me.ReportParameters.Add(ReportParameter1) Me.ReportParameters.Add(ReportParameter2) Me.ReportParameters.Add(ReportParameter3) Me.Style.BackgroundColor = System.Drawing.Color.White StyleRule1.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Title")}) StyleRule1.Style.Color = System.Drawing.Color.Black StyleRule1.Style.Font.Bold = True StyleRule1.Style.Font.Italic = False StyleRule1.Style.Font.Name = "Tahoma" StyleRule1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule1.Style.Font.Strikeout = False StyleRule1.Style.Font.Underline = False StyleRule2.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Caption")}) StyleRule2.Style.Color = System.Drawing.Color.Black StyleRule2.Style.Font.Name = "Tahoma" StyleRule2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule2.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle StyleRule3.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Data")}) StyleRule3.Style.Font.Name = "Tahoma" StyleRule3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule3.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle StyleRule4.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("PageInfo")}) StyleRule4.Style.Font.Name = "Tahoma" StyleRule4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point) StyleRule4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle Me.StyleSheet.AddRange(New Telerik.Reporting.Drawing.StyleRule() {StyleRule1, StyleRule2, StyleRule3, StyleRule4}) Me.Width = New Telerik.Reporting.Drawing.Unit(25.000202178955078R, Telerik.Reporting.Drawing.UnitType.Cm) CType(Me, System.ComponentModel.ISupportInitialize).EndInit() End Sub Friend WithEvents SDSRepPoaMeses As Telerik.Reporting.SqlDataSource Friend WithEvents labelsGroupHeader As Telerik.Reporting.GroupHeaderSection Friend WithEvents labelsGroupFooter As Telerik.Reporting.GroupFooterSection Friend WithEvents labelsGroup As Telerik.Reporting.Group Friend WithEvents componenteGroupHeader As Telerik.Reporting.GroupHeaderSection Friend WithEvents componenteGroupFooter As Telerik.Reporting.GroupFooterSection Friend WithEvents componenteGroup As Telerik.Reporting.Group Friend WithEvents actividadGroupHeader As Telerik.Reporting.GroupHeaderSection Friend WithEvents actividadGroupFooter As Telerik.Reporting.GroupFooterSection Friend WithEvents actividadGroup As Telerik.Reporting.Group Friend WithEvents pageHeader As Telerik.Reporting.PageHeaderSection Friend WithEvents pageFooter As Telerik.Reporting.PageFooterSection Friend WithEvents reportHeader As Telerik.Reporting.ReportHeaderSection Friend WithEvents reportFooter As Telerik.Reporting.ReportFooterSection Friend WithEvents detail As Telerik.Reporting.DetailSection Friend WithEvents TextBox2 As Telerik.Reporting.TextBox Public WithEvents PictureBox1 As Telerik.Reporting.PictureBox Friend WithEvents TextBox39 As Telerik.Reporting.TextBox Friend WithEvents TextBox38 As Telerik.Reporting.TextBox Friend WithEvents TextBox9 As Telerik.Reporting.TextBox Friend WithEvents TextBox8 As Telerik.Reporting.TextBox Friend WithEvents TextBox7 As Telerik.Reporting.TextBox Friend WithEvents TextBox6 As Telerik.Reporting.TextBox Friend WithEvents TextBox1 As Telerik.Reporting.TextBox Friend WithEvents TextBox3 As Telerik.Reporting.TextBox Friend WithEvents TextBox55 As Telerik.Reporting.TextBox Friend WithEvents TextBox56 As Telerik.Reporting.TextBox Friend WithEvents TextBox60 As Telerik.Reporting.TextBox Friend WithEvents TextBox59 As Telerik.Reporting.TextBox Friend WithEvents TextBox57 As Telerik.Reporting.TextBox Friend WithEvents TextBox58 As Telerik.Reporting.TextBox Friend WithEvents TextBox76 As Telerik.Reporting.TextBox Friend WithEvents TextBox75 As Telerik.Reporting.TextBox Friend WithEvents TextBox79 As Telerik.Reporting.TextBox Friend WithEvents TextBox80 As Telerik.Reporting.TextBox Friend WithEvents TextBox62 As Telerik.Reporting.TextBox Friend WithEvents TextBox61 As Telerik.Reporting.TextBox Friend WithEvents eneEjeDataTextBox As Telerik.Reporting.TextBox Friend WithEvents eneProgDataTextBox As Telerik.Reporting.TextBox Friend WithEvents unidadDataTextBox As Telerik.Reporting.TextBox Friend WithEvents nomTareaDataTextBox As Telerik.Reporting.TextBox Friend WithEvents TextBox4 As Telerik.Reporting.TextBox Friend WithEvents TextBox5 As Telerik.Reporting.TextBox Friend WithEvents TextBox10 As Telerik.Reporting.TextBox End Class
crackper/SistFoncreagro
SistFoncreagro.Report/RepPoaMeses.Designer.vb
Visual Basic
mit
51,398
Imports DotNetNuke Imports System.Web.UI Imports System.Collections.Generic Imports System.Reflection Imports System.Math Imports System.Net Imports System.IO Imports System.Text Imports System.Net.Mail Imports System.Collections.Specialized Imports System.Linq Imports Stories Imports System.ServiceModel.Syndication Namespace DotNetNuke.Modules.AgapeConnect.Stories Partial Class RSS Inherits Entities.Modules.PortalModuleBase Const maxItemsInfeed = 15 Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim d As New StoriesDataContext Dim Stories = From c In d.AP_Stories Where c.PortalID = PortalId And c.TabId = TabId And c.IsVisible = True Order By c.StoryDate Descending Response.ContentType = "application/rss+xml" Dim myFeed As New SyndicationFeed() myFeed.Title = TextSyndicationContent.CreatePlaintextContent(TabController.CurrentPage.TabName) myFeed.Description = TextSyndicationContent.CreatePlaintextContent("Latest news from " & PortalSettings.PortalName & "/" & TabController.CurrentPage.TabName) myFeed.Links.Add(SyndicationLink.CreateAlternateLink(New Uri(NavigateURL()))) myFeed.Links.Add(SyndicationLink.CreateSelfLink(New Uri(EditUrl("RSS")))) myFeed.Copyright = SyndicationContent.CreatePlaintextContent("Copyright " & PortalSettings.PortalName) myFeed.Language = PortalSettings.DefaultLanguage Dim myList As New List(Of SyndicationItem) For Each row In Stories.Take(maxItemsInfeed) Dim insert As New SyndicationItem insert.Title = TextSyndicationContent.CreatePlaintextContent(row.Headline) insert.Links.Add(New SyndicationLink(New Uri(EditUrl("ViewStory") & "?StoryId" & row.StoryId))) insert.Summary = TextSyndicationContent.CreatePlaintextContent(Left(StoryFunctions.StripTags(row.StoryText), 500)) insert.PublishDate = row.StoryDate Dim author As New SyndicationPerson author.Name = row.Author author.Email = "" insert.Authors.Add(author) myList.Add(insert) Next myFeed.Items = myList Dim feedWriter = System.Xml.XmlWriter.Create(Response.OutputStream) Dim rssFormatter As New Rss20FeedFormatter(myFeed) rssFormatter.WriteTo(feedWriter) feedWriter.Close() End Sub End Class End Namespace
GlobalTechnology/OpsInABox
DesktopModules/AgapeConnect/Stories/RSS.ascx.vb
Visual Basic
mit
2,651
Public Class InvalidAgentTaskNameException : Inherits System.Exception Public Sub New() End Sub Public Sub New(message As String) MyBase.New(message) End Sub Public Sub New(message As String, inner As Exception) MyBase.New(message, inner) End Sub End Class
dbl4k/Agent
Agent.Common/Exceptions/InvalidAgentTaskNameException.vb
Visual Basic
mit
304
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.34014 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Imports System Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("JLNetStat.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set resourceCulture = value End Set End Property End Module End Namespace
joeylane/JLNetStat
JLNetStat/My Project/Resources.Designer.vb
Visual Basic
mit
2,715
 Option Strict On Imports System.Drawing Imports System.Windows.Forms Imports SignWriterStudio.General.All Imports SignWriterStudio.SWS Imports System Imports SignWriterStudio.General.SerializeObjects Public Module SWClassesMod 'Friend WithEvents monitor As EQATEC.Analytics.Monitor.IAnalyticsMonitor = EQATEC.Analytics.Monitor.AnalyticsMonitorFactory.Create("7A55FE8188FD4072B11C3EA5D30EB7F9") 'Private Sub NewVersion(ByVal sender As Object, ByVal e As EQATEC.Analytics.Monitor.VersionAvailableEventArgs) Handles monitor.VersionAvailable ' Dim MBO As MessageBoxOptions = CType(MessageBoxOptions.RtlReading And MessageBoxOptions.RightAlign, MessageBoxOptions) ' MessageBox.Show("Version " & e.OfficialVersion.ToString() & " is available", "", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MBO, False) 'End Sub 'Friend isSettingup As Boolean '= False Function ViewSymbolDetails(ByVal symb As SWSymbol) As String If symb Is Nothing Then Throw New ArgumentNullException("symb") End If Dim string1 As String = "isValid: " & symb.IsValid string1 &= vbCrLf() & "Code: " & symb.Code string1 &= vbCrLf() & "sssID: " & symb.Id string1 &= vbCrLf() & "SSS.ToString: " & symb.ToString string1 &= vbCrLf() & "SSS.baseGroup: " & symb.BaseGroup string1 &= vbCrLf() & "SSS.group: " & symb.Group string1 &= vbCrLf() & "SSS.category: " & symb.Category string1 &= vbCrLf() & "SSS.symbol: " & symb.Symbol string1 &= vbCrLf() & "SSS.variation: " & symb.Variation string1 &= vbCrLf() & "SSS.fill: " & symb.Fill string1 &= vbCrLf() & "SSS.rotation: " & symb.Rotation Return string1 End Function 'Public Sub PrintValues(ByVal myCollection As IEnumerable, ByVal mySeparator As Char) ' Dim obj As [Object] ' Dim OBJ2 As Dictionary(Of Integer, SWSign) = CType(myCollection, Dictionary(Of Integer, SWSign)) ' For Each obj In myCollection ' Dim obj1 As SWSign = CType(obj.value, SWSign) ' Console.Write("{0}{1}", mySeparator, obj1.GetHashCode) ' Next obj ' 'Console.WriteLine() ' 'Console.Write("{0}{1}", mySeparator, OBJ2.Count) ' 'Console.WriteLine() 'End Sub 'PrintValues End Module Public Class AcercaDe Private _autorizado As String Public Property Autorizado() As String Get Return _autorizado End Get Set(ByVal value As String) _autorizado = value End Set End Property Private _version As String Public Property Version() As String Get Return _version End Get Set(ByVal value As String) _version = value End Set End Property Private _prueba As String Public Property Prueba() As String Get Return _prueba End Get Set(ByVal value As String) _prueba = value End Set End Property Private _activado As String Public Property Activado() As String Get Return _activado End Get Set(ByVal value As String) _activado = value End Set End Property Private _level As String Public Property Level() As String Get Return _level End Get Set(ByVal value As String) _level = value End Set End Property Public Property IsBeta As Boolean Public Sub New() Version = My.Application.Info.Version.ToString Activado = "No" End Sub End Class Public Class ImageInfo Private _key As String Public Property Key() As String Get Return _key End Get Set(ByVal value As String) _key = value End Set End Property Private _image As Byte() Public Property Image() As Byte() Get Return _image End Get Set(ByVal value As Byte()) _image = value End Set End Property End Class ''' <summary> ''' Add symbols to the treeview ''' </summary> Public NotInheritable Class SymbolsToTreeView Private Sub New() End Sub ' In this section you can add your own using directives ' section 127-0-0-1-7a280c1:11b57c58272:-8000:0000000000000B1F begin ' section 127-0-0-1-7a280c1:11b57c58272:-8000:0000000000000B1F end ' * ' * A class that represents ... ' * All rights Reserved Copyright(c) 2008 ' * @see SWFrame ' * @author Jonathan Duncan ' */ ' Operations Private Shared Sub SaveImageList(ByVal imgList As ImageList, ByVal filename As String) 'Dim ImgStream As ImageListStreamer = ImgList.ImageStream Dim listtoSave As New List(Of ImageInfo) For I As Integer = 0 To imgList.Images.Count - 1 Dim img As Image = imgList.Images(I) Dim imgInfo As New ImageInfo imgInfo.Image = ImageToByteArray(img, Imaging.ImageFormat.Png) imgInfo.Key = imgList.Images.Keys(I) listtoSave.Add(imgInfo) Next Dim imgListXml As Xml.XmlDocument imgListXml = SerializeObject(listtoSave, listtoSave.GetType) 'IO.File.Delete(filename) imgListXml.Save(filename) End Sub Private Shared Function LoadImageList(ByVal imgList As ImageList, ByVal filename As String) As Integer Dim listtoLoad As New List(Of ImageInfo) Dim imgListXml As New Xml.XmlDocument imgListXml.Load(filename) listtoLoad = CType(DESerializeObject(imgListXml, listtoLoad.GetType), List(Of ImageInfo)) For Each imgInfo As ImageInfo In listtoLoad imgList.Images.Add(imgInfo.Key, ByteArraytoImage(imgInfo.Image)) Next Return listtoLoad.Count End Function Public Shared Sub Load(ByVal tv As Windows.Forms.Control, ByVal imgList As ImageList, ByVal myDataRow() As SymbolCache.ISWA2010DataSet.cacheRow, ByVal useBaseName As Boolean) ' section 127-0-0-1-7a280c1:11b57c58272:-8000:0000000000000B2A begin If tv Is Nothing Then Throw New ArgumentNullException("tv") End If If imgList Is Nothing Then Throw New ArgumentNullException("imgList") End If If myDataRow Is Nothing Then Throw New ArgumentNullException("myDataRow") End If Dim filename As String = IO.Path.Combine(General.Paths.AllUsersData, tv.Name & ".xml") If My.Computer.FileSystem.FileExists(filename) Then Dim imageCount As Integer = LoadImageListFromFile(filename, imgList) If Not imageCount = 652 Then 'Damaged file, load from database imgList.Images.Clear() LoadImageListFromDatabase(filename, imgList, myDataRow) End If Else LoadImageListFromDatabase(filename, imgList, myDataRow) End If LoadNodes(imgList, CType(tv, Windows.Forms.TreeView), myDataRow, useBaseName) ' section 127-0-0-1-7a280c1:11b57c58272:-8000:0000000000000B2A end End Sub Private Shared Sub LoadNodes(ByRef imgList As ImageList, ByRef tv As TreeView, ByRef myDataRow() As SymbolCache.ISWA2010DataSet.cacheRow, ByVal useBaseName As Boolean) tv.ImageList = imgList tv.BeginUpdate() 'Create Categories If tv.Nodes.Count = 0 Then tv.Tag = Nothing End If TVCategories_Load(tv) 'Load GroupBase and Base Symbols TreeViewCategory_Load(tv, myDataRow, UseBaseName) tv.CollapseAll() tv.EndUpdate() End Sub Private Shared Function LoadImageListFromFile(ByVal filename As String, ByVal imgList As ImageList) As Integer If imgList.Images.Count = 0 Then imgList.ColorDepth = ColorDepth.Depth8Bit imgList.TransparentColor = Nothing imgList.ImageSize = New Size(50, 55) End If Return LoadImageList(imgList, filename) End Function Private Shared Sub LoadImageListFromDatabase(ByVal filename As String, ByVal imgList As ImageList, ByRef myDataRow() As SymbolCache.ISWA2010DataSet.cacheRow) 'Try imgList = ImageList_Load(imgList, myDataRow, False) 'If tv.Name = "TVFavoriteSymbols" Then ' imgList = SWDrawing.AddImagestoImageList(imgList, "01-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "02-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "03-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "04-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "05-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "06-01-001-01-01-01", 55, 50, Color.OrangeRed) 'imgList = SWDrawing.AddImagestoImageList(imgList, "07-01-001-01-01-01", 55, 50, Color.OrangeRed) ''End If SaveImageList(imgList, filename) 'Catch ex As Exception ' MessageBox.Show(ex.Message, ) ' End Try End Sub Private Shared Sub TVCategories_Load(ByRef tv As TreeView) If tv.Tag Is Nothing Then Dim newCatNode As New TreeNode newCatNode.Name = "Category1" newCatNode.ToolTipText = "Hands [1]" newCatNode.ImageKey = "01-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey ' "S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category2" newCatNode.ToolTipText = "Movement [2]" newCatNode.ImageKey = "02-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey ' "S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category3" newCatNode.ToolTipText = "Dynamics [3]" newCatNode.ImageKey = "03-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey ' "S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category4" newCatNode.ToolTipText = "Face Head [4]" newCatNode.ImageKey = "04-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey '"S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category5" newCatNode.ToolTipText = "Body [5]" newCatNode.ImageKey = "05-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey ' "S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category6" newCatNode.ToolTipText = "Location [6]" newCatNode.ImageKey = "06-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey ' "S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) newCatNode.Name = "Category7" newCatNode.ToolTipText = "Punctuation [7]" newCatNode.ImageKey = "07-01-001-01-01-01" newCatNode.SelectedImageKey = newCatNode.ImageKey '"S" & newCatNode.ImageKey tv.Nodes.Add(CType(newCatNode.Clone, TreeNode)) tv.Tag = "Categories Set" End If End Sub ' Private Sub TreeViewCategory_Load(ByRef TV As TreeView, ByRef MyDataRows() As DataRow) ' TreeViewCategory_Load(TV, MyDataRows, True) ' End Sub Private Shared Sub TreeViewCategory_Load(ByRef tv As TreeView, ByRef myDataRows() As SymbolCache.ISWA2010DataSet.cacheRow, ByVal useBaseName As Boolean) Dim previousCatNodeName As String 'Dim PreviousGroupNodeName As String = String.Empty 'Dim PreviousBaseNodeName As String = String.Empty Dim currentCategory As Integer = 0 'Dim PreviousBaseGroup As Integer = Nothing 'Dim PreviousGroup As Integer = Nothing 'Dim I As Integer Dim catRows As SymbolCache.ISWA2010DataSet.cacheRow() = myDataRows Dim catNode As TreeNode Dim groupBaseNode As New TreeNode Dim baseNode As New TreeNode Dim catRow As SymbolCache.ISWA2010DataSet.cacheRow Dim memGroupBase As Integer = 0 Dim memBase As Integer = 0 Dim newGroupBase As Boolean = True Dim newBase As Boolean = True tv.BeginUpdate() groupBaseNode = New TreeNode baseNode = New TreeNode Dim newNode As New TreeNode For Each catRow In catRows 'Set up category If Not IsDBNull(catRow.sg_cat_num) AndAlso (currentCategory = 0 OrElse Not catRow.sg_cat_num = currentCategory) Then previousCatNodeName = "Category" & catRow.sg_cat_num currentCategory = catRow.sg_cat_num catNode = tv.Nodes(previousCatNodeName) 'Start new Category reset these two. memGroupBase = 0 memBase = 0 End If 'Create new node, set info newNode = New TreeNode If useBaseName Then If Not IsDBNull(catRow.bs_name) Then newNode.Text = catRow.bs_name End If End If newNode.ImageKey = catRow.sym_id newNode.SelectedImageKey = catRow.sym_id '"S" & CatRow.sym_id newNode.Name = catRow.sym_id 'Set Tooltiptext If IsDBNull(catRow.bs_name) Then newNode.ToolTipText = String.Empty Else newNode.ToolTipText = catRow.bs_name End If 'If is new GroupBase If Not memGroupBase = catRow.sg_grp_num Then newGroupBase = True End If 'If is new Base If Not memBase = catRow.bs_bas_num Then newBase = True End If 'Add Base Group Name Node If newGroupBase Then 'GroupBaseNode = CType(newNode.Clone, TreeNode) groupBaseNode = newNode catNode.Nodes.Add(groupBaseNode) 'Add details of BaseItem ElseIf newBase = True Then If groupBaseNode.Name = String.Empty Then 'Add to CatNode (lowest level) 'BaseNode = CatNode 'Add BaseNode to GroupBaseNode 'BaseNode = CType(newNode.Clone, TreeNode) baseNode = newNode catNode.Nodes.Add(baseNode) 'SetGroupBase for next pass groupBaseNode = baseNode Else 'Add BaseNode to GroupBaseNode 'BaseNode = CType(newNode.Clone, TreeNode) baseNode = newNode groupBaseNode.Nodes.Add(baseNode) End If ElseIf Not groupBaseNode.Name = String.Empty Then 'If TV.Nodes.Find(newNode.Name, True).Length = 0 Then groupBaseNode.Nodes.Add(newNode) Else catNode.Nodes.Add(newNode) End If 'Resert if New newGroupBase = False newBase = False 'Remember Previous Group and Base memGroupBase = catRow.sg_grp_num memBase = catRow.bs_bas_num Next tv.EndUpdate() End Sub Private Shared Function ImageList_Load(ByVal myImageList As ImageList, ByVal myDataRows() As SymbolCache.ISWA2010DataSet.cacheRow, Optional createdSelected As Boolean = True) As ImageList Return SWDrawing.LoadImageList(myImageList, myDataRows, 55, 50, Color.OrangeRed, CreatedSelected) End Function End Class Class StopWatch Private _swLap As New TimeSpan Private _swTotal As New TimeSpan Private _startTime As New DateTime Private _laps As Integer = 0 Public ReadOnly Property LastLap() As TimeSpan Get Return _swLap End Get End Property Public ReadOnly Property TotalTime() As TimeSpan Get Return _swTotal End Get End Property Public ReadOnly Property TotalLaps() As Integer Get Return _laps End Get End Property Public Sub SWStop() _swLap = Date.Now - _startTime _swTotal = _swTotal.Add(_swLap) End Sub Public Sub SWStart() _startTime = Date.Now _laps += 1 End Sub Public Sub Clear() _startTime = Nothing _swLap = New TimeSpan(0) _swTotal = New TimeSpan(0) _laps = 0 End Sub Public Sub Stats() MessageBox.Show("Last Lap was: " & _swLap.TotalMilliseconds & vbCrLf() & "Total Time is: " & _swTotal.TotalMilliseconds & vbCrLf() & "Average lap is: " & _swTotal.TotalMilliseconds / _laps) End Sub End Class #Region "Unused" Public NotInheritable Class SWQuiz 'Inherits SignListSubTitle ' In this section you can add your own using directives ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B37 begin ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B37 end ' * ' * A class that represents ... ' * All rights Reserved Copyright(c) 2008 ' * @see OtherClasses ' * @author Jonathan Duncan ' */ ' Attributes ' Associations ' Operations 'Public Sub getSignsforQuiz() ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B39 begin ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B39 end 'End Sub 'Public Sub saveQuirzResults() ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3B begin ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3B end 'End Sub 'Public Sub showQuirzResults() ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3D begin ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3D end 'End Sub 'Public Sub resetQuizResults() ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3F begin ' ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B3F end 'End Sub End Class Public NotInheritable Class SWSecurity ' In this section you can add your own using directives ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B36 begin ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B36 end ' * ' * A class that represents ... ' * All rights Reserved Copyright(c) 2008 ' * @see OtherClasses ' * @author Jonathan Duncan ' */ ' Attributes Private _cpuId As Integer Public Property CpuId() As Integer Get Return _cpuId End Get Set(ByVal value As Integer) _cpuId = value End Set End Property Private _harddriveId As Integer Public Property HarddriveId() As Integer Get Return _harddriveId End Get Set(ByVal value As Integer) _harddriveId = value End Set End Property Private _operatingsystemId As Integer Public Property OperatingsystemId() As Integer Get Return _operatingsystemId End Get Set(ByVal value As Integer) _operatingsystemId = value End Set End Property Private _seed As Integer Public Property Seed() As Integer Get Return _seed End Get Set(ByVal value As Integer) _seed = value End Set End Property Private _licencenumber As Integer Public Property Licencenumber() As Integer Get Return _licencenumber End Get Set(ByVal value As Integer) _licencenumber = value End Set End Property Private _instalationId As Integer Public Property InstalationId() As Integer Get Return _instalationId End Get Set(ByVal value As Integer) _instalationId = value End Set End Property ' Operations 'Public Sub GetComputerInfo() ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B38 begin ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B38 end 'End Sub 'Public Sub GetLicenceInfo() ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B3A begin ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B3A end 'End Sub 'Public Sub UserLevel() ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B3C begin ' ' section 127-0-0-1-10d587d1:11b793ea0a9:-8000:0000000000000B3C end 'End Sub End Class Public NotInheritable Class SWUserLevel ' In this section you can add your own using directives ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B19 begin ' section 127-0-0-1-5dfe14c5:1088497b690:-8000:0000000000000B19 end ' * ' * A class that represents ... ' * All rights Reserved Copyright(c) 2008 ' * @see OtherClasses ' * @author Jonathan Duncan ' */ ' Attributes Private _swUserHash As String Public Property SWUserHash() As String Get Return _SWUserHash End Get Set(ByVal value As String) _SWUserHash = value End Set End Property Private _swLevel As String Public Property SWLevel() As String Get Return _SWLevel End Get Set(ByVal value As String) _SWLevel = value End Set End Property ' Associations ' Operations End Class #End Region Friend NotInheritable Class FunctorComparer(Of T) Implements IComparer(Of T) ' Methods Public Sub New(ByVal comparison As Comparison(Of T)) comparison = comparison End Sub Public Function [Compare](ByVal x As T, ByVal y As T) As Integer Implements IComparer(Of T).Compare Return _comparison.Invoke(x, y) End Function ' Fields Private ReadOnly _comparison As Comparison(Of T) End Class Module SWSymbolCache Private ReadOnly _swSymbolCache As New Dictionary(Of Integer, SWSymbol) Public Property SWSymbolCache(code As Integer) As SWSymbol Get Dim swSymbol As SWSymbol = Nothing If _swSymbolCache.TryGetValue(Code, swSymbol) Then Return swSymbol End If Return Nothing End Get Set(ByVal value As SWSymbol) If Not _swSymbolCache.ContainsKey(Code) Then _swSymbolCache.Add(Code, value) End If End Set End Property End Module
JonathanDDuncan/SignWriterStudio
SWClasses/SWClasses.vb
Visual Basic
mit
23,164
'Copyright 2019 Esri 'Licensed under the Apache License, Version 2.0 (the "License"); 'you may not use this file except in compliance with the License. 'You may obtain a copy of the License at ' http://www.apache.org/licenses/LICENSE-2.0 'Unless required by applicable law or agreed to in writing, software 'distributed under the License is distributed on an "AS IS" BASIS, 'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 'See the License for the specific language governing permissions and 'limitations under the License. Imports Microsoft.VisualBasic Imports System Imports System.Drawing Imports System.Collections.Generic Imports System.Runtime.InteropServices Imports System.Windows.Forms Imports ESRI.ArcGIS.ADF.BaseClasses Imports ESRI.ArcGIS.ADF.CATIDs Imports ESRI.ArcGIS.Framework Imports ESRI.ArcGIS.esriSystem Imports ESRI.ArcGIS.Geodatabase Imports ESRI.ArcGIS.Catalog Imports ESRI.ArcGIS.CatalogUI Imports ESRI.ArcGIS.NetworkAnalystUI Imports SubsetNetworkEvaluators Namespace SubsetNetworkEvaluatorsUI ''' <summary> ''' The RemoveSubsetAttributesCommand is a context menu item automatically added to the ArcCatalog ''' Network Dataset context menu. If the network analyst extension license is checked out ''' you can use this command to quickly reverse the affects of the AddSubsetAttributesCommand. It only ''' removes those subset attributes that were or could have been added by the add command. You can always ''' just remove the subset attributes manually using the attributes page of the network dataset property sheet. ''' Removing the attribute will also remove the parameters and evaluator assignments. ''' </summary> <Guid("EDD273A2-2AC2-4f2f-B096-7088B58F0667"), ClassInterface(ClassInterfaceType.None), ProgId("SubsetNetworkEvaluatorsUI.RemoveSubsetAttributesCommand")> _ Public NotInheritable Class RemoveSubsetAttributesCommand : Inherits BaseCommand #Region "COM Registration Function(s)" <ComRegisterFunction(), ComVisible(False)> _ Private Shared Sub RegisterFunction(ByVal registerType As Type) ' Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType) ' ' TODO: Add any COM registration code here '' End Sub <ComUnregisterFunction(), ComVisible(False)> _ Private Shared Sub UnregisterFunction(ByVal registerType As Type) ' Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType) ' ' TODO: Add any COM unregistration code here '' End Sub #Region "ArcGIS Component Category Registrar generated code" ''' <summary> ''' Required method for ArcGIS Component Category registration - ''' Do not modify the contents of this method with the code editor. ''' </summary> Private Shared Sub ArcGISCategoryRegistration(ByVal registerType As Type) Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID) GxCommands.Register(regKey) GxNetworkDatasetContextMenuCommands.Register(regKey) End Sub ''' <summary> ''' Required method for ArcGIS Component Category unregistration - ''' Do not modify the contents of this method with the code editor. ''' </summary> Private Shared Sub ArcGISCategoryUnregistration(ByVal registerType As Type) Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID) GxCommands.Unregister(regKey) GxNetworkDatasetContextMenuCommands.Unregister(regKey) End Sub #End Region #End Region Private m_application As IApplication = Nothing Private m_nax As INetworkAnalystExtension = Nothing Public Sub New() MyBase.m_category = "Network Analyst Samples" 'localizable text MyBase.m_caption = "Remove Subset Attributes" 'localizable text MyBase.m_message = "Remove Subset Attributes" 'localizable text MyBase.m_toolTip = "Remove Subset Attributes" 'localizable text MyBase.m_name = "NASamples_RemoveSubsetAttributes" 'unique id, non-localizable (e.g. "MyCategory_ArcMapCommand") End Sub #Region "Overridden Class Methods" ''' <summary> ''' Occurs when this command is created ''' </summary> ''' <param name="hook">Instance of the application</param> Public Overloads Overrides Sub OnCreate(ByVal hook As Object) If hook Is Nothing Then Return End If m_application = TryCast(hook, IApplication) m_nax = TryCast(SubsetHelperUI.GetNAXConfiguration(m_application), INetworkAnalystExtension) End Sub ''' <summary> ''' Occurs when this command is clicked ''' </summary> Public Overloads Overrides Sub OnClick() Dim gxApp As IGxApplication = TryCast(m_application, IGxApplication) Dim gxDataset As IGxDataset = Nothing Dim dsType As esriDatasetType = esriDatasetType.esriDTAny If Not gxApp Is Nothing Then gxDataset = TryCast(gxApp.SelectedObject, IGxDataset) dsType = gxDataset.Type End If If dsType <> esriDatasetType.esriDTNetworkDataset Then Return End If Dim ds As IDataset = gxDataset.Dataset If ds Is Nothing Then Return End If Dim nds As INetworkDataset = TryCast(ds, INetworkDataset) If nds Is Nothing Then Return End If If (Not nds.Buildable) Then Return End If Dim netBuild As INetworkBuild = TryCast(nds, INetworkBuild) If netBuild Is Nothing Then Return End If Dim dsComponent As IDatasetComponent = TryCast(nds, IDatasetComponent) Dim deNet As IDENetworkDataset = Nothing If Not dsComponent Is Nothing Then deNet = TryCast(dsComponent.DataElement, IDENetworkDataset) End If If deNet Is Nothing Then Return End If FilterSubsetEvaluator.RemoveFilterSubsetAttribute(deNet) ScaleSubsetEvaluator.RemoveScaleSubsetAttributes(deNet) netBuild.UpdateSchema(deNet) End Sub Public Overloads Overrides ReadOnly Property Enabled() As Boolean Get Dim gxApp As IGxApplication = TryCast(m_application, IGxApplication) Dim gxDataset As IGxDataset = Nothing Dim dsType As esriDatasetType = esriDatasetType.esriDTAny Dim naxEnabled As Boolean = False Dim naxConfig As IExtensionConfig = TryCast(m_nax, IExtensionConfig) If Not naxConfig Is Nothing Then naxEnabled = naxConfig.State = esriExtensionState.esriESEnabled End If If naxEnabled Then If Not gxApp Is Nothing Then gxDataset = TryCast(gxApp.SelectedObject, IGxDataset) dsType = gxDataset.Type End If End If Return (dsType = esriDatasetType.esriDTNetworkDataset) End Get End Property #End Region End Class End Namespace
Esri/arcobjects-sdk-community-samples
Net/Networks/SubsetNetworkEvaluators/VBNet/SubsetNetworkEvaluatorsUI/RemoveSubsetAttributesCommand.vb
Visual Basic
apache-2.0
6,566
Imports System Imports System.Collections.ObjectModel Imports DbExtensions Namespace Northwind <Table(Name:="Shippers")> Public Class Shipper <Column> Property CompanyName As String <Column> Property Phone As String <Column(IsPrimaryKey:=True, IsDbGenerated:=True)> Property ShipperID As Integer <Association(OtherKey:=NameOf(Order.ShipVia))> ReadOnly Property Orders As New Collection(Of Order) End Class End Namespace
maxtoroq/DbExtensions
samples/VisualBasic/Northwind/Shipper.vb
Visual Basic
apache-2.0
488
Module Module1 'Control table address Public Const P_GOAL_POSITION_L = 30 Public Const P_GOAL_POSITION_H = 31 Public Const P_PRESENT_POSITION_L = 36 Public Const P_PRESENT_POSITION_H = 37 Public Const P_MOVING = 46 'Defulat setting Public Const DEFAULT_PORTNUM = 3 'COM3 Public Const DEFAULT_BAUDNUM = 1 '1Mbps Public Const DEFAULT_ID = 1 Dim GoalPos(0 To 1) As Integer Dim index, Moving, PresentPos, CommStatus As Integer Sub Main() GoalPos(0) = 0 GoalPos(1) = 1023 'GoalPos(1) = 4095 'for EX serise index = 0 'Open device If (dxl_initialize(DEFAULT_PORTNUM, DEFAULT_BAUDNUM) = 0) Then Console.WriteLine("Failed to open USB2Dynamixel!") Console.WriteLine("Press any key to terminate...") Console.ReadKey(True) Exit Sub Else Console.WriteLine("Succeed to open USB2Dynamixel!") End If While (True) Console.WriteLine("Press any key to continue!(press ESC to quit)") If (Console.ReadKey(True).Key = ConsoleKey.Escape) Then Exit While End If 'Write goal position dxl_write_word(DEFAULT_ID, P_GOAL_POSITION_L, GoalPos(index)) Moving = 1 While (Moving = 1) 'Read present position PresentPos = dxl_read_word(DEFAULT_ID, P_PRESENT_POSITION_L) CommStatus = dxl_get_result() If (CommStatus = COMM_RXSUCCESS) Then Console.WriteLine("" & GoalPos(index) & " " & PresentPos & "") PrintErrorCode() Else PrintCommStatus(CommStatus) Exit While End If 'Check moving done Moving = dxl_read_byte(DEFAULT_ID, P_MOVING) CommStatus = dxl_get_result() If (CommStatus = COMM_RXSUCCESS) Then If (Moving = 0) Then 'Change goal position If (index = 0) Then index = 1 Else index = 0 End If PrintErrorCode() End If Else PrintCommStatus(CommStatus) Exit While End If End While End While 'Close device dxl_terminate() Console.WriteLine("Press any key to terminate...") Console.ReadKey(True) End Sub 'Print communication result Sub PrintCommStatus(ByVal CommStatus As Integer) Select Case (CommStatus) Case COMM_TXFAIL Console.WriteLine("COMM_TXFAIL: Failed transmit instruction packet!") Case COMM_TXERROR Console.WriteLine("COMM_TXERROR: Incorrect instruction packet!") Case COMM_RXFAIL Console.WriteLine("COMM_RXFAIL: Failed get status packet from device!") Case COMM_RXWAITING Console.WriteLine("COMM_RXWAITING: Now recieving status packet!") Case COMM_RXTIMEOUT Console.WriteLine("COMM_RXTIMEOUT: There is no status packet!") Case COMM_RXCORRUPT Console.WriteLine("COMM_RXCORRUPT: Incorrect status packet!") Case Else Console.WriteLine("This is unknown error code!") End Select End Sub 'Print error bit of status packet Sub PrintErrorCode() If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_VOLTAGE) = 1) Then Console.WriteLine("Input voltage error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_ANGLE) = 1) Then Console.WriteLine("Angle limit error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_OVERHEAT) = 1) Then Console.WriteLine("Overheat error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_RANGE) = 1) Then Console.WriteLine("Out of range error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_CHECKSUM) = 1) Then Console.WriteLine("Checksum error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_OVERLOAD) = 1) Then Console.WriteLine("Overload error!") End If If (dynamixel.dxl_get_rxpacket_error(dynamixel.ERRBIT_INSTRUCTION) = 1) Then Console.WriteLine("Instruction code error!") End If End Sub End Module
samuelwilliams413/Integrate_Early
Runfiles/example/visual basic/Read_Write/Module1.vb
Visual Basic
bsd-3-clause
4,715
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.SignatureHelp Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Utilities.IntrinsicOperators Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp <ExportSignatureHelpProvider(NameOf(NameOfExpressionSignatureHelpProvider), LanguageNames.VisualBasic), [Shared]> Friend Class NameOfExpressionSignatureHelpProvider Inherits AbstractIntrinsicOperatorSignatureHelpProvider(Of NameOfExpressionSyntax) <ImportingConstructor> Public Sub New() End Sub Public Overrides Function IsRetriggerCharacter(ch As Char) As Boolean Return ch = ")"c End Function Public Overrides Function IsTriggerCharacter(ch As Char) As Boolean Return ch = "("c End Function Protected Overrides Function GetIntrinsicOperatorDocumentationAsync(node As NameOfExpressionSyntax, document As Document, cancellationToken As CancellationToken) As ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation)) Return New ValueTask(Of IEnumerable(Of AbstractIntrinsicOperatorDocumentation))({New NameOfExpressionDocumentation()}) End Function Protected Overrides Function IsArgumentListToken(node As NameOfExpressionSyntax, token As SyntaxToken) As Boolean Return _ node.NameOfKeyword <> token AndAlso node.CloseParenToken <> token End Function Protected Overrides Function IsTriggerToken(token As SyntaxToken) As Boolean Return token.IsChildToken(Of NameOfExpressionSyntax)(Function(noe) noe.OpenParenToken) End Function End Class End Namespace
abock/roslyn
src/Features/VisualBasic/Portable/SignatureHelp/NameOfExpressionSignatureHelpProvider.vb
Visual Basic
mit
1,968
Imports System.Resources Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("DBCodeGenerator")> <Assembly: AssemblyDescription("Generate data base code automatically")> <Assembly: AssemblyCompany("SGAI")> <Assembly: AssemblyProduct("DBCodeGenerator")> <Assembly: AssemblyCopyright("Copyright © SGAI AI 2009")> <Assembly: AssemblyTrademark("LiuWeiZhao welljoe@hotmail.com")> <Assembly: ComVisible(True)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("2b7d69e9-c8cb-417d-9163-7b6e71447a74")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")> <Assembly: NeutralResourcesLanguageAttribute("en")>
welljoe/code-sidelights
DBCodeGenerator/DBCodeGenerator/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
1,305
'*******************************************************************************************' ' ' ' Download Free Evaluation Version From: https://bytescout.com/download/web-installer ' ' ' ' Also available as Web API! Get free API Key https://app.pdf.co/signup ' ' ' ' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. ' ' https://www.bytescout.com ' ' https://www.pdf.co ' '*******************************************************************************************' Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("Watermarks")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("Watermarks")> <Assembly: AssemblyCopyright("Copyright © 2016")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("6fcfb82f-8e8d-4e8e-a3e9-7944b1a9721f")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
bytescout/ByteScout-SDK-SourceCode
Premium Suite/VB.NET/Add watermarks to pdf with pdf sdk/My Project/AssemblyInfo.vb
Visual Basic
apache-2.0
2,113
'********************************************************* ' ' Copyright (c) Microsoft. All rights reserved. ' This code is licensed under the MIT License (MIT). ' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY ' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR ' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ' '********************************************************* Imports Windows.Devices.Sensors Imports Windows.UI.Core Namespace Global.SDKTemplate Public NotInheritable Partial Class Scenario2_ShakeEvents Inherits Page Private _accelerometer As Accelerometer Private _shakeCount As UShort = 0 Dim rootPage As MainPage = MainPage.Current Public Sub New() Me.InitializeComponent() End Sub Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) _accelerometer = Accelerometer.GetDefault(rootPage.AccelerometerReadingType) If _accelerometer IsNot Nothing Then rootPage.NotifyUser(rootPage.AccelerometerReadingType.ToString & " accelerometer ready", NotifyType.StatusMessage) ScenarioEnableButton.IsEnabled = True Else rootPage.NotifyUser(rootPage.AccelerometerReadingType.ToString & " accelerometer not found", NotifyType.ErrorMessage) End If End Sub Protected Overrides Sub OnNavigatingFrom(e As NavigatingCancelEventArgs) If ScenarioDisableButton.IsEnabled Then ScenarioDisable() End If End Sub ''' <summary> ''' This is the event handler for VisibilityChanged events. You would register for these notifications ''' if handling sensor data when the app is not visible could cause unintended actions in the app. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"> ''' Event data that can be examined for the current visibility state. ''' </param> Private Sub VisibilityChanged(sender As Object, e As VisibilityChangedEventArgs) If ScenarioDisableButton.IsEnabled Then If e.Visible Then AddHandler _accelerometer.Shaken, AddressOf Shaken Else RemoveHandler _accelerometer.Shaken, AddressOf Shaken End If End If End Sub ''' <summary> ''' This is the event handler for Shaken events. ''' </summary> ''' <param name="sender"></param> ''' <param name="e"></param> Async Private Sub Shaken(sender As Object, e As AccelerometerShakenEventArgs) Await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, Sub() _shakeCount = _shakeCount + 1 ScenarioOutputText.Text = _shakeCount.ToString() End Sub) End Sub ''' <summary> ''' This is the click handler for the 'Enable' button. ''' </summary> Private Sub ScenarioEnable() AddHandler Window.Current.VisibilityChanged, AddressOf VisibilityChanged AddHandler _accelerometer.Shaken, AddressOf Shaken ScenarioEnableButton.IsEnabled = False ScenarioDisableButton.IsEnabled = True End Sub ''' <summary> ''' This is the click handler for the 'Disable' button. ''' </summary> Private Sub ScenarioDisable() RemoveHandler Window.Current.VisibilityChanged, AddressOf VisibilityChanged RemoveHandler _accelerometer.Shaken, AddressOf Shaken ScenarioEnableButton.IsEnabled = True ScenarioDisableButton.IsEnabled = False End Sub End Class End Namespace
oldnewthing/Windows-universal-samples
Samples/Accelerometer/vb/Scenario2_ShakeEvents.xaml.vb
Visual Basic
mit
3,790
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Reflection Imports System.Threading Imports Microsoft.CodeAnalysis.Scripting.Hosting Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Namespace Microsoft.CodeAnalysis.Scripting.VisualBasic Friend NotInheritable Class VisualBasicScriptCompiler Inherits ScriptCompiler Public Shared ReadOnly Instance As ScriptCompiler = New VisualBasicScriptCompiler() Private Shared ReadOnly s_defaultInteractive As VisualBasicParseOptions = New VisualBasicParseOptions(languageVersion:=LanguageVersion.VisualBasic11, kind:=SourceCodeKind.Interactive) Private Shared ReadOnly s_defaultScript As VisualBasicParseOptions = New VisualBasicParseOptions(languageVersion:=LanguageVersion.VisualBasic11, kind:=SourceCodeKind.Script) Private Shared ReadOnly s_vbRuntimeReference As MetadataReference = MetadataReference.CreateFromAssemblyInternal(GetType(CompilerServices.NewLateBinding).GetTypeInfo().Assembly) Private Sub New() End Sub Public Overrides ReadOnly Property DiagnosticFormatter As DiagnosticFormatter Get Return VisualBasicDiagnosticFormatter.Instance End Get End Property Public Overrides Function IsCompleteSubmission(tree As SyntaxTree) As Boolean ' TODO: https://github.com/dotnet/roslyn/issues/5235 Return True End Function Public Overrides Function ParseSubmission(text As SourceText, cancellationToken As CancellationToken) As SyntaxTree Return SyntaxFactory.ParseSyntaxTree(text, s_defaultInteractive, cancellationToken:=cancellationToken) End Function Private Shared Function GetGlobalImportsForCompilation(script As Script) As IEnumerable(Of GlobalImport) ' TODO: remember these per options instance so we don't need to reparse each submission ' TODO: get imports out of compilation??? Return script.Options.Namespaces.Select(Function(n) GlobalImport.Parse(n)) End Function Public Overrides Function CreateSubmission(script As Script) As Compilation Dim previousSubmission As Compilation = Nothing If script.Previous IsNot Nothing Then previousSubmission = script.Previous.GetCompilation() End If Dim diagnostics = DiagnosticBag.GetInstance() Dim references = script.GetReferencesForCompilation(MessageProvider.Instance, diagnostics, s_vbRuntimeReference) ' TODO report Diagnostics diagnostics.Free() ' parse: Dim parseOptions = If(script.Options.IsInteractive, s_defaultInteractive, s_defaultScript) Dim tree = VisualBasicSyntaxTree.ParseText(script.Code, parseOptions, script.Options.Path) ' create compilation: Dim assemblyName As String = Nothing Dim submissionTypeName As String = Nothing script.Builder.GenerateSubmissionId(assemblyName, submissionTypeName) Dim globalImports = GetGlobalImportsForCompilation(script) Dim submission = VisualBasicCompilation.CreateSubmission( assemblyName, tree, references, New VisualBasicCompilationOptions( outputKind:=OutputKind.DynamicallyLinkedLibrary, mainTypeName:=Nothing, scriptClassName:=submissionTypeName, globalImports:=globalImports, rootNamespace:="", optionStrict:=OptionStrict.Off, optionInfer:=True, optionExplicit:=True, optionCompareText:=False, embedVbCoreRuntime:=False, checkOverflow:=False, xmlReferenceResolver:=Nothing, ' don't support XML file references in interactive (permissions & doc comment includes) sourceReferenceResolver:=SourceFileResolver.Default, metadataReferenceResolver:=script.Options.MetadataResolver, assemblyIdentityComparer:=DesktopAssemblyIdentityComparer.Default), previousSubmission, script.ReturnType, script.GlobalsType) Return submission End Function End Class End Namespace
zmaruo/roslyn
src/Scripting/VisualBasic/VisualBasicScriptCompiler.vb
Visual Basic
apache-2.0
4,581
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Partial Friend Class VisualBasicCodeModelService Protected Overrides Function CreateNodeLocator() As AbstractNodeLocator Return New NodeLocator(Me) End Function Private Class NodeLocator Inherits AbstractNodeLocator Public Sub New(codeModelService As VisualBasicCodeModelService) MyBase.New(codeModelService) End Sub Protected Overrides ReadOnly Property DefaultPart As EnvDTE.vsCMPart Get Return EnvDTE.vsCMPart.vsCMPartWhole End Get End Property Protected Overrides Function GetStartPoint(text As SourceText, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint? Select Case node.Kind Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock Return GetTypeBlockStartPoint(text, DirectCast(node, TypeBlockSyntax), part) Case SyntaxKind.EnumBlock Return GetEnumBlockStartPoint(text, DirectCast(node, EnumBlockSyntax), part) Case SyntaxKind.ClassStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.StructureStatement Return GetTypeBlockStartPoint(text, DirectCast(node.Parent, TypeBlockSyntax), part) Case SyntaxKind.EnumStatement Return GetEnumBlockStartPoint(text, DirectCast(node.Parent, EnumBlockSyntax), part) Case SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.SubBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetMethodBlockStartPoint(text, DirectCast(node, MethodBlockBaseSyntax), part) Case SyntaxKind.SubNewStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement, SyntaxKind.RaiseEventStatement Return GetMethodBlockStartPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement If TypeOf node.Parent Is MethodBlockBaseSyntax Then Return GetMethodBlockStartPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part) Else Return GetMethodStatementStartPoint(text, DirectCast(node, MethodStatementSyntax), part) End If Case SyntaxKind.DeclareFunctionStatement, SyntaxKind.DeclareSubStatement Return GetDeclareStatementStartPoint(text, DirectCast(node, DeclareStatementSyntax), part) Case SyntaxKind.PropertyBlock Return GetPropertyBlockStartPoint(text, DirectCast(node, PropertyBlockSyntax), part) Case SyntaxKind.PropertyStatement Return GetPropertyStatementStartPoint(text, DirectCast(node, PropertyStatementSyntax), part) Case SyntaxKind.EventBlock Return GetEventBlockStartPoint(text, DirectCast(node, EventBlockSyntax), part) Case SyntaxKind.EventStatement Return GetEventStatementStartPoint(text, DirectCast(node, EventStatementSyntax), part) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return GetDelegateStatementStartPoint(text, DirectCast(node, DelegateStatementSyntax), part) Case SyntaxKind.NamespaceBlock Return GetNamespaceBlockStartPoint(text, DirectCast(node, NamespaceBlockSyntax), part) Case SyntaxKind.NamespaceStatement Return GetNamespaceBlockStartPoint(text, DirectCast(node.Parent, NamespaceBlockSyntax), part) Case SyntaxKind.ModifiedIdentifier Return GetVariableStartPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part) Case SyntaxKind.EnumMemberDeclaration Return GetVariableStartPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part) Case SyntaxKind.Parameter Return GetParameterStartPoint(text, DirectCast(node, ParameterSyntax), part) Case SyntaxKind.Attribute Return GetAttributeStartPoint(text, DirectCast(node, AttributeSyntax), part) Case SyntaxKind.SimpleArgument, SyntaxKind.OmittedArgument Return GetAttributeArgumentStartPoint(text, DirectCast(node, ArgumentSyntax), part) Case SyntaxKind.SimpleImportsClause Return GetImportsStatementStartPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part) Case SyntaxKind.OptionStatement Return GetOptionStatementStartPoint(text, DirectCast(node, OptionStatementSyntax), part) Case SyntaxKind.InheritsStatement Return GetInheritsStatementStartPoint(text, DirectCast(node, InheritsStatementSyntax), part) Case SyntaxKind.ImplementsStatement Return GetImplementsStatementStartPoint(text, DirectCast(node, ImplementsStatementSyntax), part) Case Else Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind))) Throw New NotSupportedException() End Select End Function Protected Overrides Function GetEndPoint(text As SourceText, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint? Select Case node.Kind Case SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock Return GetTypeBlockEndPoint(text, DirectCast(node, TypeBlockSyntax), part) Case SyntaxKind.EnumBlock Return GetEnumBlockEndPoint(text, DirectCast(node, EnumBlockSyntax), part) Case SyntaxKind.ClassStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock Return GetTypeBlockEndPoint(text, DirectCast(node.Parent, TypeBlockSyntax), part) Case SyntaxKind.EnumStatement Return GetEnumBlockEndPoint(text, DirectCast(node.Parent, EnumBlockSyntax), part) Case SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.SubBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return GetMethodBlockEndPoint(text, DirectCast(node, MethodBlockBaseSyntax), part) Case SyntaxKind.SubNewStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement, SyntaxKind.RaiseEventStatement Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part) Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement If TypeOf node.Parent Is MethodBlockBaseSyntax Then Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part) Else Return GetMethodStatementEndPoint(text, DirectCast(node, MethodStatementSyntax), part) End If Case SyntaxKind.DeclareFunctionStatement, SyntaxKind.DeclareSubStatement Return GetDeclareStatementEndPoint(text, DirectCast(node, DeclareStatementSyntax), part) Case SyntaxKind.PropertyBlock Return GetPropertyBlockEndPoint(text, DirectCast(node, PropertyBlockSyntax), part) Case SyntaxKind.PropertyStatement Return GetPropertyStatementEndPoint(text, DirectCast(node, PropertyStatementSyntax), part) Case SyntaxKind.EventBlock Return GetEventBlockEndPoint(text, DirectCast(node, EventBlockSyntax), part) Case SyntaxKind.EventStatement Return GetEventStatementEndPoint(text, DirectCast(node, EventStatementSyntax), part) Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return GetDelegateStatementEndPoint(text, DirectCast(node, DelegateStatementSyntax), part) Case SyntaxKind.NamespaceBlock Return GetNamespaceBlockEndPoint(text, DirectCast(node, NamespaceBlockSyntax), part) Case SyntaxKind.NamespaceStatement Return GetNamespaceBlockEndPoint(text, DirectCast(node.Parent, NamespaceBlockSyntax), part) Case SyntaxKind.ModifiedIdentifier Return GetVariableEndPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part) Case SyntaxKind.EnumMemberDeclaration Return GetVariableEndPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part) Case SyntaxKind.Parameter Return GetParameterEndPoint(text, DirectCast(node, ParameterSyntax), part) Case SyntaxKind.Attribute Return GetAttributeEndPoint(text, DirectCast(node, AttributeSyntax), part) Case SyntaxKind.SimpleArgument, SyntaxKind.OmittedArgument Return GetAttributeArgumentEndPoint(text, DirectCast(node, ArgumentSyntax), part) Case SyntaxKind.SimpleImportsClause Return GetImportsStatementEndPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part) Case SyntaxKind.OptionStatement Return GetOptionStatementEndPoint(text, DirectCast(node, OptionStatementSyntax), part) Case SyntaxKind.InheritsStatement Return GetInheritsStatementEndPoint(text, DirectCast(node, InheritsStatementSyntax), part) Case SyntaxKind.ImplementsStatement Return GetImplementsStatementEndPoint(text, DirectCast(node, ImplementsStatementSyntax), part) Case Else Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind))) Throw New NotImplementedException() End Select End Function Private Function GetAttributesStartPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint? ' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value. ' You can see the issue clearly in vb\Language\VsPackage\CodeModelHelpers.cpp, CodeModelLocations::GetAttributeSpecifierListLocation. ' Essentially, the old code tries to do the right thing for vsCMPartAttributes, but then deliberately falls through to the ' vsCMPartAttributesWithDelimiter case, where it overwrites the calculation it just made. Sigh... If attributes.Count = 0 Then Return Nothing End If Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter startPosition = attributes.First().LessThanToken.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Return Nothing Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(attributes.First().SyntaxTree, text, startPosition) End Function Private Function GetAttributesEndPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint? ' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value. ' See GetAttributesStartPoint for the details If attributes.Count = 0 Then Return Nothing End If Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter startPosition = attributes.Last().GreaterThanToken.Span.End Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Return Nothing Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(attributes.Last().SyntaxTree, text, startPosition) End Function Private Function GetHeaderStartPosition(typeBlock As TypeBlockSyntax) As Integer If typeBlock.BlockStatement.Modifiers.Count > 0 Then Return typeBlock.BlockStatement.Modifiers.First().SpanStart Else Return typeBlock.BlockStatement.DeclarationKeyword.SpanStart End If End Function Private Function GetHeaderStartPosition(enumBlock As EnumBlockSyntax) As Integer If enumBlock.EnumStatement.Modifiers.Count > 0 Then Return enumBlock.EnumStatement.Modifiers.First().SpanStart Else Return enumBlock.EnumStatement.EnumKeyword.SpanStart End If End Function Private Function GetTypeBlockStartPoint(text As SourceText, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = typeBlock.BlockStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, typeBlock.BlockStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = typeBlock.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole startPosition = GetHeaderStartPosition(typeBlock) Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim statement As StatementSyntax = typeBlock.BlockStatement While statement IsNot Nothing Dim [next] = statement.GetNextNonEmptyStatement() If [next] IsNot Nothing AndAlso ([next].Kind = SyntaxKind.InheritsStatement OrElse [next].Kind = SyntaxKind.ImplementsStatement) Then statement = [next] Continue While Else Exit While End If End While Debug.Assert(statement IsNot Nothing) Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart) ' statement points to either the last Inherits/Implements or to the type declaration itself. Dim nextStatement = statement.GetNextNonEmptyStatement() Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing) ' If the next statement is on the same line as the current one, set body start ' position to the end of the current statement If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then startPosition = statement.Span.End Else ' Otherwise, use the beginning of the next line. startPosition = text.Lines(statementLine.LineNumber + 1).Start End If If part = EnvDTE.vsCMPart.vsCMPartNavigate Then Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(text), typeBlock.BlockStatement, typeBlock.EndBlockStatement, statementLine.LineNumber + 1) End If Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition) End Function Private Function GetTypeBlockEndPoint(text As SourceText, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = typeBlock.BlockStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, typeBlock.BlockStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes startPosition = typeBlock.BlockStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = typeBlock.Span.End Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = typeBlock.EndBlockStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition) End Function Private Function GetEnumBlockStartPoint(text As SourceText, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = enumBlock.EnumStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, enumBlock.EnumStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = enumBlock.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole startPosition = GetHeaderStartPosition(enumBlock) Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim statement As StatementSyntax = enumBlock.EnumStatement Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart) Dim nextStatement = statement.GetNextNonEmptyStatement() Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing) ' If the next statement is on the same line as the current one, set body start ' position to the end of the current statement If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then startPosition = statement.Span.End Else ' Otherwise, use the beginning of the next line. startPosition = text.Lines(statementLine.LineNumber + 1).Start End If If part = EnvDTE.vsCMPart.vsCMPartNavigate Then Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(text), enumBlock.EnumStatement, enumBlock.EndEnumStatement, statementLine.LineNumber + 1) End If Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition) End Function Private Function GetEnumBlockEndPoint(text As SourceText, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = enumBlock.EnumStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, enumBlock.EnumStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes startPosition = enumBlock.EnumStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = enumBlock.Span.End Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = enumBlock.EndEnumStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition) End Function Private Function GetMethodBlockStartPoint(text As SourceText, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName Select Case methodBlock.BlockStatement.Kind Case SyntaxKind.SubNewStatement startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.SpanStart Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.SpanStart Case SyntaxKind.OperatorStatement startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.SpanStart Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement ' For properties accessors, use the name of property block Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)() If propertyBlock Is Nothing Then Throw Exceptions.ThrowEFail() End If Return GetPropertyBlockStartPoint(text, propertyBlock, part) Case SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' For event accessors, use the name of event block Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)() If eventBlock Is Nothing Then Throw Exceptions.ThrowEFail() End If Return GetEventBlockStartPoint(text, eventBlock, part) Case Else Throw Exceptions.ThrowEFail() End Select Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, methodBlock.BlockStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = methodBlock.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole startPosition = NavigationPointHelpers.GetHeaderStartPosition(methodBlock) Case EnvDTE.vsCMPart.vsCMPartNavigate Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(text), methodBlock) Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(methodBlock)) startPosition = text.Lines(startLine.LineNumber + 1).Start Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition) End Function Private Function GetDeclareStatementStartPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = declareStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, declareStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If declareStatement.AttributeLists.Count > 0 Then startPosition = declareStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else startPosition = declareStatement.SpanStart End If Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = declareStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(declareStatement.SyntaxTree, text, startPosition) End Function Private Function GetDeclareStatementEndPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = declareStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, declareStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = declareStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(declareStatement.SyntaxTree, text, endPosition) End Function Private Function GetMethodStatementStartPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = methodStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, methodStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If methodStatement.AttributeLists.Count > 0 Then startPosition = methodStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else startPosition = methodStatement.SpanStart End If Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = methodStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(methodStatement.SyntaxTree, text, startPosition) End Function Private Function GetMethodBlockEndPoint(text As SourceText, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName Select Case methodBlock.BlockStatement.Kind Case SyntaxKind.SubNewStatement startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.Span.End Case SyntaxKind.FunctionStatement, SyntaxKind.SubStatement startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.Span.End Case SyntaxKind.OperatorStatement startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.Span.End Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement ' For properties accessors, use the name of property block Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)() If propertyBlock Is Nothing Then Throw Exceptions.ThrowEFail() End If Return GetPropertyBlockEndPoint(text, propertyBlock, part) Case SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement ' For event accessors, use the name of event block Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)() If eventBlock Is Nothing Then Throw Exceptions.ThrowEFail() End If Return GetEventBlockEndPoint(text, eventBlock, part) Case Else Throw Exceptions.ThrowEFail() End Select Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, methodBlock.BlockStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes startPosition = methodBlock.BlockStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = methodBlock.Span.End Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = methodBlock.EndBlockStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition) End Function Private Function GetMethodStatementEndPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = methodStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, methodStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = methodStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(methodStatement.SyntaxTree, text, endPosition) End Function Private Function GetPropertyBlockStartPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Return GetPropertyStatementStartPoint(text, propertyBlock.PropertyStatement, part) End Function Private Function GetPropertyStatementStartPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = propertyStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, propertyStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole If propertyStatement.AttributeLists.Count > 0 Then startPosition = propertyStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else startPosition = propertyStatement.SpanStart End If Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = propertyStatement.SpanStart Case EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim beginLine = text.Lines.IndexOf(propertyStatement.Span.End) Dim lineNumber = beginLine + 1 startPosition = text.Lines(lineNumber).Start Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition) End Function Private Function GetPropertyBlockEndPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Return GetPropertyStatementEndPoint(text, propertyBlock.PropertyStatement, part) End Function Private Function GetPropertyStatementEndPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = propertyStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, propertyStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes startPosition = propertyStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock), DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.Span.End, propertyStatement.Span.End) Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, EnvDTE.vsCMPart.vsCMPartNavigate ' Oddity of VB code model: this only happens if it isn't an auto-property. Otherwise, the start of the file is returned. startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock), DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.SpanStart, 0) Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition) End Function Private Function GetEventBlockStartPoint(text As SourceText, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = eventBlock.EventStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, eventBlock.EventStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = eventBlock.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole startPosition = NavigationPointHelpers.GetHeaderStartPosition(eventBlock) Case EnvDTE.vsCMPart.vsCMPartNavigate Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(text), eventBlock) Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(eventBlock)) startPosition = text.Lines(startLine.LineNumber + 1).Start Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(eventBlock.SyntaxTree, text, startPosition) End Function Private Function GetEventStatementStartPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = eventStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, eventStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If eventStatement.AttributeLists.Count > 0 Then startPosition = eventStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else startPosition = eventStatement.SpanStart End If Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = eventStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition) End Function Private Function GetEventBlockEndPoint(text As SourceText, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Return GetEventStatementEndPoint(text, eventBlock.EventStatement, part) End Function Private Function GetEventStatementEndPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = eventStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, eventStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes startPosition = eventStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock), DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.Span.End, eventStatement.Span.End) Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, EnvDTE.vsCMPart.vsCMPartNavigate startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock), DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.SpanStart, eventStatement.Span.End) Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition) End Function Private Function GetDelegateStatementStartPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = delegateStatement.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, delegateStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If delegateStatement.AttributeLists.Count > 0 Then startPosition = delegateStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart Else startPosition = delegateStatement.SpanStart End If Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = delegateStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, startPosition) End Function Private Function GetDelegateStatementEndPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = delegateStatement.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, delegateStatement.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = delegateStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, endPosition) End Function Private Function GetTrailingColonTrivia(statement As StatementSyntax) As SyntaxTrivia? If Not statement.HasTrailingTrivia Then Return Nothing End If Return statement _ .GetTrailingTrivia() _ .FirstOrNullable(Function(t) t.Kind = SyntaxKind.ColonTrivia) End Function Private Function GetNamespaceBlockStartPoint(text As SourceText, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = namespaceBlock.NamespaceStatement.Name.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole startPosition = namespaceBlock.NamespaceStatement.SpanStart Case EnvDTE.vsCMPart.vsCMPartNavigate Dim beginStatement = namespaceBlock.NamespaceStatement Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart) Dim lineNumber = beginLine + 1 ' If the begin statement has trailing colon trivia, we assume the body starts at the colon. Dim colonTrivia = GetTrailingColonTrivia(beginStatement) If colonTrivia IsNot Nothing Then lineNumber = text.Lines.IndexOf(colonTrivia.Value.SpanStart) End If Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(text), namespaceBlock.NamespaceStatement, namespaceBlock.EndNamespaceStatement, lineNumber) Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter Dim beginStatement = namespaceBlock.NamespaceStatement Dim endStatement = namespaceBlock.EndNamespaceStatement ' Handle case where begin statement has trailing colon trivia, e.g. Namespace N : End Namespace Dim colonTrivia = GetTrailingColonTrivia(beginStatement) If colonTrivia IsNot Nothing Then startPosition = colonTrivia.Value.SpanStart Exit Select End If Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart) Dim lineNumber = beginLine + 1 startPosition = text.Lines(lineNumber).Start Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, startPosition) End Function Private Function GetNamespaceBlockEndPoint(text As SourceText, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = namespaceBlock.NamespaceStatement.Name.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader endPosition = namespaceBlock.NamespaceStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole endPosition = namespaceBlock.EndNamespaceStatement.Span.End Case EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter, EnvDTE.vsCMPart.vsCMPartNavigate endPosition = namespaceBlock.EndNamespaceStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, endPosition) End Function Private Function GetVariableStartPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)() Debug.Assert(fieldDeclaration IsNot Nothing) Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = variable.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, fieldDeclaration.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = fieldDeclaration.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If fieldDeclaration.Modifiers.Count > 0 Then startPosition = fieldDeclaration.Modifiers.First().SpanStart Else startPosition = fieldDeclaration.Declarators.First().SpanStart End If Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(variable.SyntaxTree, text, startPosition) End Function Private Function GetVariableStartPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = enumMember.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, enumMember.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = enumMember.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = enumMember.Identifier.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(enumMember.SyntaxTree, text, startPosition) End Function Private Function GetVariableEndPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)() Debug.Assert(fieldDeclaration IsNot Nothing) Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = variable.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, fieldDeclaration.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = fieldDeclaration.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(variable.SyntaxTree, text, endPosition) End Function Private Function GetVariableEndPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = enumMember.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, enumMember.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = enumMember.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(enumMember.SyntaxTree, text, endPosition) End Function Private Function GetParameterStartPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName startPosition = parameter.Identifier.SpanStart Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesStartPoint(text, parameter.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes startPosition = parameter.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter If parameter.Modifiers.Any() Then startPosition = parameter.Modifiers.First().SpanStart Else startPosition = parameter.Identifier.SpanStart End If Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(parameter.SyntaxTree, text, startPosition) End Function Private Function GetParameterEndPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName endPosition = parameter.Identifier.Span.End Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return GetAttributesEndPoint(text, parameter.AttributeLists, part) Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = parameter.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(parameter.SyntaxTree, text, endPosition) End Function Private Function GetImportsStatementStartPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = importsStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(importsStatement.SyntaxTree, text, startPosition) End Function Private Function GetImportsStatementEndPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = importsStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(importsStatement.SyntaxTree, text, endPosition) End Function Private Function GetOptionStatementStartPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = optionStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(optionStatement.SyntaxTree, text, startPosition) End Function Private Function GetOptionStatementEndPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = optionStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(optionStatement.SyntaxTree, text, endPosition) End Function Private Function GetInheritsStatementStartPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = inheritsStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, startPosition) End Function Private Function GetInheritsStatementEndPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = inheritsStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, endPosition) End Function Private Function GetImplementsStatementStartPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = implementsStatement.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, startPosition) End Function Private Function GetImplementsStatementEndPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = implementsStatement.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, endPosition) End Function Private Function GetAttributeStartPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartName startPosition = attribute.Name.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = attribute.SpanStart Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(attribute.SyntaxTree, text, startPosition) End Function Private Function GetAttributeEndPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartName endPosition = attribute.Name.Span.End Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = attribute.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(attribute.SyntaxTree, text, endPosition) End Function Private Function GetAttributeArgumentStartPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim startPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartName If Not argument.IsNamed Then Return Nothing End If startPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.SpanStart Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter startPosition = If(argument.Kind = SyntaxKind.OmittedArgument, argument.SpanStart - 1, argument.SpanStart) Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(argument.SyntaxTree, text, startPosition) End Function Private Function GetAttributeArgumentEndPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint? Dim endPosition As Integer Select Case part Case EnvDTE.vsCMPart.vsCMPartAttributes, EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter Return Nothing Case EnvDTE.vsCMPart.vsCMPartName If Not argument.IsNamed Then Return Nothing End If endPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Span.End Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes, EnvDTE.vsCMPart.vsCMPartHeader, EnvDTE.vsCMPart.vsCMPartWholeWithAttributes, EnvDTE.vsCMPart.vsCMPartWhole, EnvDTE.vsCMPart.vsCMPartNavigate, EnvDTE.vsCMPart.vsCMPartName, EnvDTE.vsCMPart.vsCMPartBody, EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter endPosition = argument.Span.End Case Else Throw Exceptions.ThrowEFail() End Select Return New VirtualTreePoint(argument.SyntaxTree, text, endPosition) End Function End Class End Class End Namespace
bbarry/roslyn
src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.vb
Visual Basic
apache-2.0
81,805
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class ThreeButtons Inherits System.Windows.Forms.UserControl 'UserControl overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.HandButton = New System.Windows.Forms.Button Me.AutoButton = New System.Windows.Forms.Button Me.OffButton = New System.Windows.Forms.Button Me.SuspendLayout() ' 'HandButton ' Me.HandButton.Location = New System.Drawing.Point(3, 3) Me.HandButton.Name = "HandButton" Me.HandButton.Size = New System.Drawing.Size(112, 48) Me.HandButton.TabIndex = 0 Me.HandButton.Text = "Hand" Me.HandButton.UseVisualStyleBackColor = True ' 'AutoButton ' Me.AutoButton.Location = New System.Drawing.Point(3, 57) Me.AutoButton.Name = "AutoButton" Me.AutoButton.Size = New System.Drawing.Size(112, 48) Me.AutoButton.TabIndex = 1 Me.AutoButton.Text = "Auto" Me.AutoButton.UseVisualStyleBackColor = True ' 'OffButton ' Me.OffButton.Location = New System.Drawing.Point(3, 111) Me.OffButton.Name = "OffButton" Me.OffButton.Size = New System.Drawing.Size(112, 48) Me.OffButton.TabIndex = 2 Me.OffButton.Text = "Off" Me.OffButton.UseVisualStyleBackColor = True ' 'ThreeButtons ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.OffButton) Me.Controls.Add(Me.AutoButton) Me.Controls.Add(Me.HandButton) Me.Name = "ThreeButtons" Me.Size = New System.Drawing.Size(150, 165) Me.ResumeLayout(False) End Sub Friend WithEvents HandButton As System.Windows.Forms.Button Friend WithEvents AutoButton As System.Windows.Forms.Button Friend WithEvents OffButton As System.Windows.Forms.Button End Class
bgreer5050/AdvancedHMI
AdvancedHMIControls/Controls/ThreeButtons.Designer.vb
Visual Basic
mit
2,722
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On Namespace My.Resources 'This class was auto-generated by the StronglyTypedResourceBuilder 'class via a tool like ResGen or Visual Studio. 'To add or remove a member, edit your .ResX file then rerun ResGen 'with the /str option, or rebuild your VS project. '''<summary> ''' A strongly-typed resource class, for looking up localized strings, etc. '''</summary> <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ Friend Module Resources Private resourceMan As Global.System.Resources.ResourceManager Private resourceCulture As Global.System.Globalization.CultureInfo '''<summary> ''' Returns the cached ResourceManager instance used by this class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager Get If Object.ReferenceEquals(resourceMan, Nothing) Then Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VehicleLoan.Resources", GetType(Resources).Assembly) resourceMan = temp End If Return resourceMan End Get End Property '''<summary> ''' Overrides the current thread's CurrentUICulture property for all ''' resource lookups using this strongly typed resource class. '''</summary> <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Friend Property Culture() As Global.System.Globalization.CultureInfo Get Return resourceCulture End Get Set(ByVal value As Global.System.Globalization.CultureInfo) resourceCulture = value End Set End Property End Module End Namespace
Shadorunce/MiniProjects
Vehicle Loan/VehicleLoanFiles/My Project/Resources.Designer.vb
Visual Basic
mit
2,782
Imports System.IO Imports System.Runtime.Serialization.Formatters Imports HomeSeerAPI Module utils Public plugin As New HSPI Public IFACE_NAME As String = "Sample-Basic" Public callback As HomeSeerAPI.IAppCallbackAPI Public hs As HomeSeerAPI.IHSApplication Public Instance As String = "" Public InterfaceVersion As Integer Public bShutDown As Boolean = False Public gEXEPath As String = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) Public Const INIFILE As String = "Sample-Basic.ini" Public CurrentPage As Object Public Structure pair Dim name As String Dim value As String End Structure Enum LogLevel As Integer Normal = 1 Debug = 2 End Enum Enum MessageType Normal = 0 Warning = 1 Error_ = 2 End Enum Public Enum DEVICE_COMMAND All_Lights_Off = 0 All_Lights_On = 1 UOn = 2 UOff = 3 End Enum Sub PEDAdd(ByRef PED As clsPlugExtraData, ByVal PEDName As String, ByVal PEDValue As Object) Dim ByteObject() As Byte = Nothing If PED Is Nothing Then PED = New clsPlugExtraData SerializeObject(PEDValue, ByteObject) If Not PED.AddNamed(PEDName, ByteObject) Then PED.RemoveNamed(PEDName) PED.AddNamed(PEDName, ByteObject) End If End Sub Function PEDGet(ByRef PED As clsPlugExtraData, ByVal PEDName As String) As Object Dim ByteObject() As Byte Dim ReturnValue As New Object ByteObject = PED.GetNamed(PEDName) If ByteObject Is Nothing Then Return Nothing DeSerializeObject(ByteObject, ReturnValue) Return ReturnValue End Function Public Function SerializeObject(ByRef ObjIn As Object, ByRef bteOut() As Byte) As Boolean If ObjIn Is Nothing Then Return False Dim str As New MemoryStream Dim sf As New Binary.BinaryFormatter Try sf.Serialize(str, ObjIn) ReDim bteOut(CInt(str.Length - 1)) bteOut = str.ToArray Return True Catch ex As Exception Log(LogLevel.Debug, IFACE_NAME & " Error: Serializing object " & ObjIn.ToString & " :" & ex.Message) Return False End Try End Function Public Function DeSerializeObject(ByRef bteIn() As Byte, ByRef ObjOut As Object) As Boolean ' Almost immediately there is a test to see if ObjOut is NOTHING. The reason for this ' when the ObjOut is suppose to be where the deserialized object is stored, is that ' I could find no way to test to see if the deserialized object and the variable to ' hold it was of the same type. If you try to get the type of a null object, you get ' only a null reference exception! If I do not test the object type beforehand and ' there is a difference, then the InvalidCastException is thrown back in the CALLING ' procedure, not here, because the cast is made when the ByRef object is cast when this ' procedure returns, not earlier. In order to prevent a cast exception in the calling ' procedure that may or may not be handled, I made it so that you have to at least ' provide an initialized ObjOut when you call this - ObjOut is set to nothing after it ' is typed. If bteIn Is Nothing Then Return False If bteIn.Length < 1 Then Return False If ObjOut Is Nothing Then Return False Dim str As MemoryStream Dim sf As New Binary.BinaryFormatter Dim ObjTest As Object Dim TType As System.Type Dim OType As System.Type Try OType = ObjOut.GetType ObjOut = Nothing str = New MemoryStream(bteIn) ObjTest = sf.Deserialize(str) If ObjTest Is Nothing Then Return False TType = ObjTest.GetType 'If Not TType.Equals(OType) Then Return False ObjOut = ObjTest If ObjOut Is Nothing Then Return False Return True Catch exIC As InvalidCastException Return False Catch ex As Exception Log(LogLevel.Debug, IFACE_NAME & " Error: DeSerializing object: " & ex.Message) Return False End Try End Function Private Sub DeleteDevices() Dim en As Object Dim dv As Object Try en = hs.GetDeviceEnumerator Do While Not en.Finished dv = en.GetNext If dv IsNot Nothing Then If dv.interface = IFACE_NAME Then Try hs.DeleteDevice(dv.ref) Catch ex As Exception End Try End If End If Loop hs.SaveEventsDevices() Catch ex As Exception End Try End Sub Sub DeleteModule(ByVal n As Integer) Dim i As Integer Log("Module to Delete is " & n) For i = 1 To 16 hs.DeleteDevice(hs.GetINISetting("Module " & n, "ref-" & i.ToString, "", INIFILE)) Next hs.ClearINISection("Module " & n.ToString, INIFILE) Log("Finished deleting module.") End Sub Function InitDevice(ByVal PName As String, ByVal modNum As Integer, ByVal counter As Integer, Optional ByVal ref As Integer = 0) As Boolean Dim dv As Scheduler.Classes.DeviceClass = Nothing Log("Initiating Device " & PName, LogLevel.Debug) Try If Not hs.DeviceExistsRef(ref) Then ref = hs.NewDeviceRef(PName) hs.SaveINISetting("Module " & modNum, "ref-" & counter.ToString, ref, INIFILE) Try dv = hs.GetDeviceByRef(ref) InitHSDevice(dv, PName) Return True Catch ex As Exception Log("Error initializing device " & PName & ": " & ex.Message) Return False End Try End If Catch ex As Exception Log("Error getting RefID from DeviceCode within InitDevice. " & ex.Message) End Try Return False End Function Sub InitHSDevice(ByRef dv As Scheduler.Classes.DeviceClass, Optional ByVal Name As String = "Sample") Dim test As Object = Nothing dv.Address(hs) = "HOME" Dim DT As New DeviceTypeInfo DT.Device_Type = DeviceTypeInfo.eDeviceAPI.Plug_In dv.DeviceType_Set(hs) = DT dv.Interface(hs) = IFACE_NAME dv.InterfaceInstance(hs) = Instance dv.Last_Change(hs) = Now dv.Name(hs) = Name dv.Location(hs) = "Sample" dv.Device_Type_String(hs) = "Sample" dv.MISC_Set(hs, Enums.dvMISC.SHOW_VALUES) dv.MISC_Set(hs, Enums.dvMISC.NO_LOG) dv.Status_Support(hs) = False End Sub Public Sub SendCommand(ByVal Housecode As String, ByVal Devicecode As String, ByVal Action As Integer) 'Send a command somewhere End Sub Public Sub RegisterCallback(ByRef frm As Object) ' call back into HS and get a reference to the HomeSeer ActiveX interface ' this can be used make calls back into HS like hs.SetDeviceValue, etc. ' The callback object is a different interface reserved for plug-ins. callback = frm hs = frm.GetHSIface If hs Is Nothing Then MsgBox("Unable to access HS interface", MsgBoxStyle.Critical) Else Log("Register callback completed", LogLevel.Debug) InterfaceVersion = hs.InterfaceVersion End If End Sub Public Sub RegisterWebPage(ByVal link As String, Optional linktext As String = "", Optional page_title As String = "") Try hs.RegisterPage(link, IFACE_NAME, Instance) If linktext = "" Then linktext = link linktext = linktext.Replace("_", " ") If page_title = "" Then page_title = linktext Dim wpd As New HomeSeerAPI.webPageDesc wpd.plugInName = IFACE_NAME wpd.link = link wpd.linktext = linktext & Instance wpd.page_title = page_title & Instance callback.RegisterLink(wpd) Catch ex As Exception Log(LogLevel.Debug, "Error - Registering Web Links: " & ex.Message) End Try End Sub Public Sub Log(ByVal Message As String, Optional ByVal Log_Level As LogLevel = LogLevel.Normal) If Log_Level = LogLevel.Normal Then hs.WriteLog(IFACE_NAME, Message) End If If Log_Level = LogLevel.Debug Then If IO.Directory.Exists(gEXEPath & "\Debug Logs") Then IO.File.AppendAllText(gEXEPath & "\Debug Logs\CurrentCost.log", Now.ToString & " ~ " & Message & vbCrLf) ElseIf IO.Directory.Exists(gEXEPath & "\Logs") Then IO.File.AppendAllText(gEXEPath & "\Logs\CurrentCost.log", Now.ToString & " ~ " & Message & vbCrLf) Else IO.File.AppendAllText(gEXEPath & "\CurrentCost.log", Now.ToString & " ~ " & Message & vbCrLf) End If End If End Sub End Module
alexdresko/HSPI
Templates/HspiSampleBasic/utils.vb
Visual Basic
mit
9,297
Imports ChartDirector Public Class financedemo Implements DemoModule ' Name of demo module Public Function getName() As String Implements DemoModule.getName Return "Interactive Financial Chart" End Function ' Number of charts produced in this demo module Public Function getNoOfCharts() As Integer Implements DemoModule.getNoOfCharts Return 1 End Function ' Main code for creating chart. Public Sub createChart(ByVal viewer As WinChartViewer, ByVal chartIndex As Integer) _ Implements DemoModule.createChart 'This demo uses its own form. The viewer on the right pane is not used. viewer.Image = Nothing Dim f As System.Windows.Forms.Form = New FrmFinanceDemo() f.ShowDialog() f.Dispose() End Sub End Class
jojogreen/Orbital-Mechanix-Suite
NetWinCharts/VBNetWinCharts/financedemo.vb
Visual Basic
apache-2.0
815
Public Class dlgProgress Private a As Integer = 0 Public Shared title As String = "..." Public Shared isOff As Boolean = False Private Sub frmProgress_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint Cursor = Cursors.WaitCursor If isOff Then Me.Dispose() isOff = False End If DrawProgress(e.Graphics, New Rectangle(31, 31, 137, 137), a) End Sub Private Sub DrawProgress(g As Graphics, rect As Rectangle, percentage As Single) 'work out the angles for each arc Dim progressAngle = CSng(360 / 100 * percentage) Dim remainderAngle = 360 - progressAngle 'create pens to use for the arcs Using progressPen As New Pen(Color.DimGray, 13), remainderPen As New Pen(Color.DeepSkyBlue, 13) 'set the smoothing to high quality for better output g.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias 'draw the blue and white arcs g.DrawArc(progressPen, rect, -90, progressAngle) g.DrawArc(remainderPen, rect, progressAngle - 90, remainderAngle) End Using Dim font As New Font("", 12, FontStyle.Bold) Dim msr = g.MeasureString(title, font) Dim pt As New Point((Me.Width - msr.Width) / 2 - 2, (Me.Height - msr.Height) / 2) msr.Width += 2 g.FillRectangle(Brushes.LightYellow, pt.X, pt.Y, msr.Width, msr.Height) g.DrawString(title, font, Brushes.Blue, pt) End Sub Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick If a >= 200 Then a = 0 End If a += 1 Me.Refresh() End Sub End Class
AuCourseHelper/AuCourseHelper_PC
Teacher/Forms/dlgProgress.vb
Visual Basic
apache-2.0
1,702
Imports BVSoftware.Bvc5.Core Imports BVSoftware.Bvc5.Core.Content Partial Class BVModules_ProductModifiers_DropDownList_ProductModifierView Inherits ProductModifierTemplate Protected modifier As New Catalog.ProductModifier Public Overrides ReadOnly Property IsValid() As Boolean Get InputRequiredFieldValidator.Validate() Return InputRequiredFieldValidator.IsValid End Get End Property Private Sub LoadSettings() modifier = DirectCast(Me.Product.ChoicesAndInputs.FindBusinessObject(Me.BlockId), Catalog.ProductModifier) Me.displayName = modifier.DisplayName End Sub Protected Sub Display() If modifier.DisplayName <> String.Empty Then InputLabel.Visible = True InputLabel.Text = modifier.DisplayName Else InputLabel.Visible = False End If Me.ModifierRadioButtonList.DataSource = modifier.ModifierOptions Me.ModifierRadioButtonList.DataTextField = "DisplayText" Me.ModifierRadioButtonList.DataValueField = "bvin" Me.ModifierRadioButtonList.DataBind() Me.InputRequiredFieldValidator.Enabled = modifier.Required For Each item As ListItem In Me.ModifierRadioButtonList.Items Dim modifierOption As Catalog.ProductModifierOption = Catalog.ProductModifierOption.FindByBvin(item.Value) If modifierOption.IsNull Then Me.InputRequiredFieldValidator.InitialValue = item.Value End If If modifierOption.IsDefault Then item.Selected = True Else item.Selected = False End If Next End Sub Public Overrides Sub InitializeDisplay() LoadSettings() Display() End Sub Public Overrides Function GetValue() As String Return ModifierRadioButtonList.SelectedValue End Function Protected Sub ModifierList_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ModifierRadioButtonList.SelectedIndexChanged MyBase.RaiseSelectionChangedEvent() End Sub Public Overrides Sub SetValue(ByVal value As String) ModifierRadioButtonList.SelectedValue = value End Sub End Class
ajaydex/Scopelist_2015
BVModules/ProductModifiers/Radio Button List/View.ascx.vb
Visual Basic
apache-2.0
2,286
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Script Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Script)) Me.MainToolStrip = New System.Windows.Forms.ToolStrip() Me.DAcceptButton = New System.Windows.Forms.ToolStripButton() Me.ToolSep1 = New System.Windows.Forms.ToolStripSeparator() Me.UndoButton = New System.Windows.Forms.ToolStripButton() Me.RedoButton = New System.Windows.Forms.ToolStripButton() Me.ToolSep3 = New System.Windows.Forms.ToolStripSeparator() Me.LoadInButton = New System.Windows.Forms.ToolStripButton() Me.SaveOutButton = New System.Windows.Forms.ToolStripButton() Me.MainStatusStrip = New System.Windows.Forms.StatusStrip() Me.StatsLabel = New System.Windows.Forms.ToolStripStatusLabel() Me.SpacesLabel = New System.Windows.Forms.ToolStripStatusLabel() Me.FunctionLabel = New System.Windows.Forms.ToolStripStatusLabel() Me.MainTextBox = New ScintillaNet.Scintilla() Me.SidePanel = New System.Windows.Forms.Panel() Me.ParseDBASChecker = New System.Windows.Forms.CheckBox() Me.ArgumentsList = New System.Windows.Forms.ListBox() Me.EditArgumentButton = New System.Windows.Forms.Button() Me.AddArgumentButton = New System.Windows.Forms.Button() Me.DeleteArgumentButton = New System.Windows.Forms.Button() Me.InsertIntoCodeButton = New System.Windows.Forms.Button() Me.ArgumentsLabel = New System.Windows.Forms.Label() Me.NameLabel = New System.Windows.Forms.Label() Me.NameTextBox = New System.Windows.Forms.TextBox() Me.MainToolStrip.SuspendLayout() Me.MainStatusStrip.SuspendLayout() CType(Me.MainTextBox, System.ComponentModel.ISupportInitialize).BeginInit() Me.SidePanel.SuspendLayout() Me.SuspendLayout() ' 'MainToolStrip ' Me.MainToolStrip.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.MainToolStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.DAcceptButton, Me.ToolSep1, Me.UndoButton, Me.RedoButton, Me.ToolSep3, Me.LoadInButton, Me.SaveOutButton}) Me.MainToolStrip.Location = New System.Drawing.Point(0, 0) Me.MainToolStrip.Name = "MainToolStrip" Me.MainToolStrip.Size = New System.Drawing.Size(544, 25) Me.MainToolStrip.TabIndex = 0 Me.MainToolStrip.Text = "ToolStrip1" ' 'DAcceptButton ' Me.DAcceptButton.Image = Global.DS_Game_Maker.My.Resources.Resources.AcceptIcon Me.DAcceptButton.ImageTransparentColor = System.Drawing.Color.Magenta Me.DAcceptButton.Name = "DAcceptButton" Me.DAcceptButton.Size = New System.Drawing.Size(60, 22) Me.DAcceptButton.Text = "Accept" ' 'ToolSep1 ' Me.ToolSep1.Name = "ToolSep1" Me.ToolSep1.Size = New System.Drawing.Size(6, 25) ' 'UndoButton ' Me.UndoButton.Image = Global.DS_Game_Maker.My.Resources.Resources.UndoIcon Me.UndoButton.ImageTransparentColor = System.Drawing.Color.Magenta Me.UndoButton.Name = "UndoButton" Me.UndoButton.Size = New System.Drawing.Size(55, 22) Me.UndoButton.Text = " Undo" ' 'RedoButton ' Me.RedoButton.Image = Global.DS_Game_Maker.My.Resources.Resources.RedoIcon Me.RedoButton.ImageTransparentColor = System.Drawing.Color.Magenta Me.RedoButton.Name = "RedoButton" Me.RedoButton.Size = New System.Drawing.Size(55, 22) Me.RedoButton.Text = "Redo " ' 'ToolSep3 ' Me.ToolSep3.Name = "ToolSep3" Me.ToolSep3.Size = New System.Drawing.Size(6, 25) ' 'LoadInButton ' Me.LoadInButton.Image = Global.DS_Game_Maker.My.Resources.Resources.OpenIcon Me.LoadInButton.ImageTransparentColor = System.Drawing.Color.Magenta Me.LoadInButton.Name = "LoadInButton" Me.LoadInButton.Size = New System.Drawing.Size(75, 22) Me.LoadInButton.Text = "Load In..." ' 'SaveOutButton ' Me.SaveOutButton.Image = Global.DS_Game_Maker.My.Resources.Resources.SaveIcon Me.SaveOutButton.ImageTransparentColor = System.Drawing.Color.Magenta Me.SaveOutButton.Name = "SaveOutButton" Me.SaveOutButton.Size = New System.Drawing.Size(84, 22) Me.SaveOutButton.Text = "Save Out..." ' 'MainStatusStrip ' Me.MainStatusStrip.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.MainStatusStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.StatsLabel, Me.SpacesLabel, Me.FunctionLabel}) Me.MainStatusStrip.Location = New System.Drawing.Point(0, 477) Me.MainStatusStrip.Name = "MainStatusStrip" Me.MainStatusStrip.Size = New System.Drawing.Size(544, 26) Me.MainStatusStrip.TabIndex = 1 Me.MainStatusStrip.Text = "StatusStrip1" ' 'StatsLabel ' Me.StatsLabel.Name = "StatsLabel" Me.StatsLabel.Padding = New System.Windows.Forms.Padding(4) Me.StatsLabel.Size = New System.Drawing.Size(19, 21) Me.StatsLabel.Text = "-" ' 'SpacesLabel ' Me.SpacesLabel.Name = "SpacesLabel" Me.SpacesLabel.Padding = New System.Windows.Forms.Padding(4) Me.SpacesLabel.Size = New System.Drawing.Size(21, 21) Me.SpacesLabel.Text = " " ' 'FunctionLabel ' Me.FunctionLabel.AutoSize = False Me.FunctionLabel.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.FunctionLabel.Name = "FunctionLabel" Me.FunctionLabel.Padding = New System.Windows.Forms.Padding(4) Me.FunctionLabel.Size = New System.Drawing.Size(300, 21) Me.FunctionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft ' 'MainTextBox ' Me.MainTextBox.ConfigurationManager.Language = "vbscript" Me.MainTextBox.Dock = System.Windows.Forms.DockStyle.Fill Me.MainTextBox.IsBraceMatching = True Me.MainTextBox.Location = New System.Drawing.Point(196, 25) Me.MainTextBox.Margins.Margin0.Width = 20 Me.MainTextBox.Name = "MainTextBox" Me.MainTextBox.Scrolling.HorizontalWidth = 1000 Me.MainTextBox.Size = New System.Drawing.Size(348, 452) Me.MainTextBox.Styles.BraceBad.FontName = "Verdana" Me.MainTextBox.Styles.BraceLight.FontName = "Verdana" Me.MainTextBox.Styles.ControlChar.FontName = "Verdana" Me.MainTextBox.Styles.Default.FontName = "Verdana" Me.MainTextBox.Styles.IndentGuide.FontName = "Verdana" Me.MainTextBox.Styles.LastPredefined.FontName = "Verdana" Me.MainTextBox.Styles.LineNumber.FontName = "Verdana" Me.MainTextBox.Styles.Max.FontName = "Verdana" Me.MainTextBox.TabIndex = 4 ' 'SidePanel ' Me.SidePanel.BackColor = System.Drawing.Color.FromArgb(CType(CType(219, Byte), Integer), CType(CType(219, Byte), Integer), CType(CType(219, Byte), Integer)) Me.SidePanel.Controls.Add(Me.ParseDBASChecker) Me.SidePanel.Controls.Add(Me.ArgumentsList) Me.SidePanel.Controls.Add(Me.EditArgumentButton) Me.SidePanel.Controls.Add(Me.AddArgumentButton) Me.SidePanel.Controls.Add(Me.DeleteArgumentButton) Me.SidePanel.Controls.Add(Me.InsertIntoCodeButton) Me.SidePanel.Controls.Add(Me.ArgumentsLabel) Me.SidePanel.Controls.Add(Me.NameLabel) Me.SidePanel.Controls.Add(Me.NameTextBox) Me.SidePanel.Dock = System.Windows.Forms.DockStyle.Left Me.SidePanel.Location = New System.Drawing.Point(0, 25) Me.SidePanel.Name = "SidePanel" Me.SidePanel.Size = New System.Drawing.Size(196, 452) Me.SidePanel.TabIndex = 5 ' 'ParseDBASChecker ' Me.ParseDBASChecker.AutoSize = True Me.ParseDBASChecker.CheckAlign = System.Drawing.ContentAlignment.MiddleRight Me.ParseDBASChecker.Location = New System.Drawing.Point(96, 259) Me.ParseDBASChecker.Name = "ParseDBASChecker" Me.ParseDBASChecker.Size = New System.Drawing.Size(87, 17) Me.ParseDBASChecker.TabIndex = 6 Me.ParseDBASChecker.Text = "Parse DBAS?" Me.ParseDBASChecker.UseVisualStyleBackColor = True ' 'ArgumentsList ' Me.ArgumentsList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed Me.ArgumentsList.FormattingEnabled = True Me.ArgumentsList.ItemHeight = 16 Me.ArgumentsList.Location = New System.Drawing.Point(13, 78) Me.ArgumentsList.Name = "ArgumentsList" Me.ArgumentsList.Size = New System.Drawing.Size(170, 148) Me.ArgumentsList.TabIndex = 6 ' 'EditArgumentButton ' Me.EditArgumentButton.Image = Global.DS_Game_Maker.My.Resources.Resources.PencilIcon Me.EditArgumentButton.Location = New System.Drawing.Point(44, 227) Me.EditArgumentButton.Name = "EditArgumentButton" Me.EditArgumentButton.Size = New System.Drawing.Size(30, 26) Me.EditArgumentButton.TabIndex = 14 Me.EditArgumentButton.UseVisualStyleBackColor = True ' 'AddArgumentButton ' Me.AddArgumentButton.Image = Global.DS_Game_Maker.My.Resources.Resources.PlusIcon Me.AddArgumentButton.Location = New System.Drawing.Point(13, 227) Me.AddArgumentButton.Name = "AddArgumentButton" Me.AddArgumentButton.Size = New System.Drawing.Size(30, 26) Me.AddArgumentButton.TabIndex = 13 Me.AddArgumentButton.UseVisualStyleBackColor = True ' 'DeleteArgumentButton ' Me.DeleteArgumentButton.Image = Global.DS_Game_Maker.My.Resources.Resources.DeleteIcon Me.DeleteArgumentButton.Location = New System.Drawing.Point(75, 227) Me.DeleteArgumentButton.Name = "DeleteArgumentButton" Me.DeleteArgumentButton.Size = New System.Drawing.Size(30, 26) Me.DeleteArgumentButton.TabIndex = 6 Me.DeleteArgumentButton.UseVisualStyleBackColor = True ' 'InsertIntoCodeButton ' Me.InsertIntoCodeButton.Image = Global.DS_Game_Maker.My.Resources.Resources.ArrowFadeRightIcon Me.InsertIntoCodeButton.ImageAlign = System.Drawing.ContentAlignment.MiddleRight Me.InsertIntoCodeButton.Location = New System.Drawing.Point(108, 227) Me.InsertIntoCodeButton.Name = "InsertIntoCodeButton" Me.InsertIntoCodeButton.Size = New System.Drawing.Size(76, 26) Me.InsertIntoCodeButton.TabIndex = 8 Me.InsertIntoCodeButton.Text = " Insert" Me.InsertIntoCodeButton.TextAlign = System.Drawing.ContentAlignment.MiddleLeft Me.InsertIntoCodeButton.UseVisualStyleBackColor = True ' 'ArgumentsLabel ' Me.ArgumentsLabel.AutoSize = True Me.ArgumentsLabel.Location = New System.Drawing.Point(10, 62) Me.ArgumentsLabel.Name = "ArgumentsLabel" Me.ArgumentsLabel.Size = New System.Drawing.Size(63, 13) Me.ArgumentsLabel.TabIndex = 4 Me.ArgumentsLabel.Text = "Arguments:" ' 'NameLabel ' Me.NameLabel.AutoSize = True Me.NameLabel.Location = New System.Drawing.Point(10, 13) Me.NameLabel.Name = "NameLabel" Me.NameLabel.Size = New System.Drawing.Size(38, 13) Me.NameLabel.TabIndex = 2 Me.NameLabel.Text = "Name:" ' 'NameTextBox ' Me.NameTextBox.Location = New System.Drawing.Point(13, 29) Me.NameTextBox.Name = "NameTextBox" Me.NameTextBox.Size = New System.Drawing.Size(170, 21) Me.NameTextBox.TabIndex = 1 ' 'Script ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.ClientSize = New System.Drawing.Size(544, 503) Me.Controls.Add(Me.MainTextBox) Me.Controls.Add(Me.SidePanel) Me.Controls.Add(Me.MainStatusStrip) Me.Controls.Add(Me.MainToolStrip) Me.Font = New System.Drawing.Font("Tahoma", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon) Me.MinimumSize = New System.Drawing.Size(560, 350) Me.Name = "Script" Me.MainToolStrip.ResumeLayout(False) Me.MainToolStrip.PerformLayout() Me.MainStatusStrip.ResumeLayout(False) Me.MainStatusStrip.PerformLayout() CType(Me.MainTextBox, System.ComponentModel.ISupportInitialize).EndInit() Me.SidePanel.ResumeLayout(False) Me.SidePanel.PerformLayout() Me.ResumeLayout(False) Me.PerformLayout() End Sub Friend WithEvents MainToolStrip As System.Windows.Forms.ToolStrip Friend WithEvents DAcceptButton As System.Windows.Forms.ToolStripButton Friend WithEvents MainStatusStrip As System.Windows.Forms.StatusStrip Friend WithEvents StatsLabel As System.Windows.Forms.ToolStripStatusLabel Friend WithEvents ToolSep1 As System.Windows.Forms.ToolStripSeparator Friend WithEvents LoadInButton As System.Windows.Forms.ToolStripButton Friend WithEvents SaveOutButton As System.Windows.Forms.ToolStripButton Friend WithEvents MainTextBox As ScintillaNet.Scintilla Friend WithEvents SidePanel As System.Windows.Forms.Panel Friend WithEvents NameTextBox As System.Windows.Forms.TextBox Friend WithEvents NameLabel As System.Windows.Forms.Label Friend WithEvents ToolSep3 As System.Windows.Forms.ToolStripSeparator Friend WithEvents ArgumentsLabel As System.Windows.Forms.Label Friend WithEvents InsertIntoCodeButton As System.Windows.Forms.Button Friend WithEvents EditArgumentButton As System.Windows.Forms.Button Friend WithEvents AddArgumentButton As System.Windows.Forms.Button Friend WithEvents DeleteArgumentButton As System.Windows.Forms.Button Friend WithEvents FunctionLabel As System.Windows.Forms.ToolStripStatusLabel Friend WithEvents SpacesLabel As System.Windows.Forms.ToolStripStatusLabel Friend WithEvents ArgumentsList As System.Windows.Forms.ListBox Friend WithEvents ParseDBASChecker As System.Windows.Forms.CheckBox Friend WithEvents UndoButton As System.Windows.Forms.ToolStripButton Friend WithEvents RedoButton As System.Windows.Forms.ToolStripButton End Class
cfwprpht/dsgamemaker
Script.Designer.vb
Visual Basic
mit
16,076
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class EnumDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of EnumStatementSyntax) Protected Overrides Sub CollectBlockSpans(enumDeclaration As EnumStatementSyntax, spans As ArrayBuilder(Of BlockSpan), options As OptionSet, cancellationToken As CancellationToken) CollectCommentsRegions(enumDeclaration, spans) Dim block = TryCast(enumDeclaration.Parent, EnumBlockSyntax) If Not block?.EndEnumStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=enumDeclaration, autoCollapse:=True, type:=BlockTypes.Type, isCollapsible:=True)) CollectCommentsRegions(block.EndEnumStatement, spans) End If End Sub End Class End Namespace
abock/roslyn
src/Features/VisualBasic/Portable/Structure/Providers/EnumDeclarationStructureProvider.vb
Visual Basic
mit
1,454
'------------------------------------------------------------------------------ ' <auto-generated> ' This code was generated by a tool. ' Runtime Version:4.0.30319.42000 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </auto-generated> '------------------------------------------------------------------------------ Option Strict On Option Explicit On <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0"), _ Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Partial Friend NotInheritable Class MySettings Inherits Global.System.Configuration.ApplicationSettingsBase Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings) #Region "My.Settings Auto-Save Functionality" #If _MyType = "WindowsForms" Then Private Shared addedHandler As Boolean Private Shared addedHandlerLockObject As New Object <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) If My.Application.SaveMySettingsOnExit Then My.Settings.Save() End If End Sub #End If #End Region Public Shared ReadOnly Property [Default]() As MySettings Get #If _MyType = "WindowsForms" Then If Not addedHandler Then SyncLock addedHandlerLockObject If Not addedHandler Then AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings addedHandler = True End If End SyncLock End If #End If Return defaultInstance End Get End Property End Class Namespace My <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ Friend Module MySettingsProperty <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ Friend ReadOnly Property Settings() As Global.Demos.WPF.VisualBasic.ScheduleChartDataGrid.MouseEventHandling.MySettings Get Return Global.Demos.WPF.VisualBasic.ScheduleChartDataGrid.MouseEventHandling.MySettings.Default End Get End Property End Module End Namespace
DlhSoftTeam/GanttChartLightLibrary-Demos
GanttChartLightLibraryDemos/Demos/Samples/WPF-VisualBasic/ScheduleChartDataGrid/MouseEventHandling/My Project/Settings.Designer.vb
Visual Basic
mit
2,913
Public Enum StatisticPeriodType None = 0 Month = 10091001 Day = 10091002 Quarter = 10091003 Week = 10091004 Year = 10091005 End Enum
EIDSS/EIDSS-Legacy
EIDSS v6/vb/EIDSS/EIDSS_Common/Enums/StatisticPeriodType.vb
Visual Basic
bsd-2-clause
165
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class UsingBlockStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of UsingBlockSyntax) Protected Overrides Sub CollectBlockSpans(node As UsingBlockSyntax, spans As ArrayBuilder(Of BlockSpan), options As OptionSet, cancellationToken As CancellationToken) spans.AddIfNotNull(CreateBlockSpanFromBlock( node, node.UsingStatement, autoCollapse:=False, type:=BlockTypes.Statement, isCollapsible:=True)) End Sub End Class End Namespace
VSadov/roslyn
src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb
Visual Basic
apache-2.0
1,126
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. ' VB has a difference from C# in that CodeModelEvents are not fired for a ' CodeElement unless it's Children are accessed. This is intended to be a ' performance improvement by not firing as many CodeModelEvents. This ' suppression of events is not supported in Roslyn. Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel Partial Friend Class VisualBasicCodeModelService Protected Overrides Function CreateCodeModelEventCollector() As AbstractCodeModelEventCollector Return New CodeModelEventCollector(Me) End Function Private Class CodeModelEventCollector Inherits AbstractCodeModelEventCollector Public Sub New(codeModelService As AbstractCodeModelService) MyBase.New(codeModelService) End Sub Private Sub CompareCompilationUnits(oldRoot As CompilationUnitSyntax, newRoot As CompilationUnitSyntax, eventQueue As CodeModelEventQueue) Dim parent As SyntaxNode = Nothing ' Options CompareChildren( AddressOf CompareOptions, oldRoot.Options.AsReadOnlyList(), newRoot.Options.AsReadOnlyList(), parent, CodeModelEventType.Unknown, eventQueue) ' Imports CompareChildren( AddressOf CompareImportsClauses, GetImportsClauses(oldRoot.Imports), GetImportsClauses(newRoot.Imports), parent, CodeModelEventType.Unknown, eventQueue) ' File-level attributes CompareChildren( AddressOf CompareAttributes, GetAttributes(oldRoot.Attributes), GetAttributes(newRoot.Attributes), parent, CodeModelEventType.Unknown, eventQueue) ' Namespaces and types CompareChildren( AddressOf CompareNamespacesOrTypes, GetValidMembers(oldRoot), GetValidMembers(newRoot), parent, CodeModelEventType.Unknown, eventQueue) End Sub Private Shared Function GetImportsClauses(importsStatements As SyntaxList(Of ImportsStatementSyntax)) As IReadOnlyList(Of ImportsClauseSyntax) Return importsStatements _ .SelectMany(Function(i) i.ImportsClauses) _ .Where(Function(i) Not TypeOf i Is XmlNamespaceImportsClauseSyntax) _ .ToArray() End Function Private Shared Function GetAttributes(attributesStatements As SyntaxList(Of AttributesStatementSyntax)) As IReadOnlyList(Of AttributeSyntax) Return attributesStatements _ .SelectMany(Function(a) a.AttributeLists) _ .SelectMany(Function(a) a.Attributes) _ .ToArray() End Function Private Shared Function GetAttributes(attributeLists As SyntaxList(Of AttributeListSyntax)) As IReadOnlyList(Of AttributeSyntax) Return attributeLists _ .SelectMany(Function(a) a.Attributes) _ .ToArray() End Function Private Shared Function IsMissingEndBlockError(statement As DeclarationStatementSyntax, [error] As String) As Boolean Select Case [error] Case "BC30481" ' Missing End Class Return True Case "BC30625" ' Missing End Module Return True Case "BC30185" ' Missing End Enum Return True Case "BC30253" ' Missing End Interface Return True Case "BC30624" ' Missing End Structure Return True Case "BC30626" ' Missing End Namespace Return True Case "BC30026" ' Missing End Sub Return True Case "BC30027" ' Missing End Function Return True Case "BC30025" ' Missing End Property Return True Case "BC33005" ' Missing End Operator Return True End Select Return False End Function Private Shared Function HasOnlyMissingEndBlockErrors(statement As DeclarationStatementSyntax) As Boolean Dim errors = statement.GetDiagnostics() If Not errors.Any() Then Return True End If Return errors.All(Function(e) IsMissingEndBlockError(statement, e.Id)) End Function Private Shared Function IsValidTopLevelDeclaration(member As DeclarationStatementSyntax) As Boolean If member.IsTopLevelBlock() Then Dim memberBegin = member.GetTopLevelBlockBegin() If memberBegin.IsTopLevelDeclaration() AndAlso HasOnlyMissingEndBlockErrors(memberBegin) Then Return True End If ElseIf member.IsTopLevelDeclaration() Then If member.ContainsDiagnostics Then Return False End If If member.Parent.IsKind(SyntaxKind.CompilationUnit, SyntaxKind.NamespaceBlock) AndAlso member.IsKind(SyntaxKind.FieldDeclaration) Then Return False End If Return True End If Return False End Function Private Function GetValidMembers(node As SyntaxNode) As IReadOnlyList(Of DeclarationStatementSyntax) Return VisualBasicCodeModelService _ .GetChildMemberNodes(node) _ .Where(Function(m) IsValidTopLevelDeclaration(m)) _ .ToArray() End Function Private Shared Function GetNames(variableDeclarators As SeparatedSyntaxList(Of VariableDeclaratorSyntax)) As IReadOnlyList(Of ModifiedIdentifierSyntax) Return variableDeclarators _ .SelectMany(Function(v) v.Names) _ .ToArray() End Function Private Function GetParameters(parameterList As ParameterListSyntax) As SeparatedSyntaxList(Of ParameterSyntax) Return If(parameterList IsNot Nothing, parameterList.Parameters, Nothing) End Function Private Function CompareOptions(oldOption As OptionStatementSyntax, newOption As OptionStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean If oldOption.NameKeyword.Kind <> newOption.NameKeyword.Kind OrElse oldOption.ValueKeyword.Kind <> newOption.ValueKeyword.Kind Then EnqueueChangeEvent(newOption, newNodeParent, CodeModelEventType.Rename, eventQueue) Return False End If Return True End Function Private Function CompareImportsClauses(oldImportsClause As ImportsClauseSyntax, newImportsClause As ImportsClauseSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean ' Note: Only namespaces are compared and aliases are ignored. If Not CompareNames(oldImportsClause.GetName(), newImportsClause.GetName()) Then EnqueueChangeEvent(newImportsClause, newNodeParent, CodeModelEventType.Rename, eventQueue) Return False End If Return True End Function Private Function CompareAttributes(oldAttribute As AttributeSyntax, newAttribute As AttributeSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim targetsChange As CodeModelEventType = 0 Dim namesChange As CodeModelEventType = 0 Dim argumentsChange As CodeModelEventType = 0 If Not CompareAttributeTargets(oldAttribute.Target, newAttribute.Target) Then targetsChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareTypeNames(oldAttribute.Name, newAttribute.Name) Then namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareArgumentLists(oldAttribute.ArgumentList, newAttribute.ArgumentList, newAttribute, eventQueue) Then argumentsChange = CodeModelEventType.ArgChange hasChanges = True End If If hasChanges Then EnqueueChangeEvent(newAttribute, newNodeParent, targetsChange Or namesChange Or argumentsChange, eventQueue) End If Return Not hasChanges End Function Private Function CompareAttributeTargets(oldAttributeTarget As AttributeTargetSyntax, newAttributeTarget As AttributeTargetSyntax) As Boolean If oldAttributeTarget Is Nothing OrElse newAttributeTarget Is Nothing Then Return oldAttributeTarget Is newAttributeTarget End If Return oldAttributeTarget.AttributeModifier.Kind = newAttributeTarget.AttributeModifier.Kind End Function Private Function CompareArgumentLists(oldArgumentList As ArgumentListSyntax, newArgumentList As ArgumentListSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim oldArguments = If(oldArgumentList IsNot Nothing, oldArgumentList.Arguments, Nothing) Dim newArguments = If(newArgumentList IsNot Nothing, newArgumentList.Arguments, Nothing) Return CompareChildren( AddressOf CompareArguments, oldArguments.AsReadOnlyList(), newArguments.AsReadOnlyList(), newNodeParent, CodeModelEventType.Unknown, eventQueue) End Function Private Function CompareArguments(oldArgument As ArgumentSyntax, newArgument As ArgumentSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert((TypeOf oldArgument Is SimpleArgumentSyntax OrElse TypeOf oldArgument Is OmittedArgumentSyntax) AndAlso (TypeOf newArgument Is SimpleArgumentSyntax OrElse TypeOf newArgument Is OmittedArgumentSyntax)) Dim hasChanges = False Dim nameChanges As CodeModelEventType = 0 Dim valueChanges As CodeModelEventType = 0 If oldArgument.Kind <> newArgument.Kind OrElse oldArgument.IsNamed <> newArgument.IsNamed _ Then nameChanges = CodeModelEventType.Rename hasChanges = True ElseIf oldArgument.IsNamed Then Dim oldNamedArgument = DirectCast(oldArgument, SimpleArgumentSyntax) Dim newNamedArgument = DirectCast(newArgument, SimpleArgumentSyntax) If Not CompareNames(oldNamedArgument.NameColonEquals.Name, newNamedArgument.NameColonEquals.Name) Then nameChanges = CodeModelEventType.Rename hasChanges = True End If End If Dim oldExpression = oldArgument.GetExpression() Dim newExpression = newArgument.GetExpression() If Not CompareExpressions(oldExpression, newExpression) Then valueChanges = CodeModelEventType.Unknown hasChanges = True End If If hasChanges Then EnqueueChangeEvent(newArgument, newNodeParent, nameChanges Or valueChanges, eventQueue) End If Return Not hasChanges End Function Private Function CompareNamespacesOrTypes(oldNamespaceOrType As DeclarationStatementSyntax, newNamespaceOrType As DeclarationStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean ' If the kind doesn't match, it has to be a remove/add. If oldNamespaceOrType.Kind <> newNamespaceOrType.Kind Then EnqueueRemoveEvent(oldNamespaceOrType, newNodeParent, eventQueue) EnqueueAddEvent(newNamespaceOrType, newNodeParent, eventQueue) Return False End If If TypeOf oldNamespaceOrType Is IncompleteMemberSyntax Then Return False End If If TypeOf oldNamespaceOrType Is NamespaceBlockSyntax Then Return CompareNamespaces( DirectCast(oldNamespaceOrType, NamespaceBlockSyntax), DirectCast(newNamespaceOrType, NamespaceBlockSyntax), newNodeParent, eventQueue) ElseIf TypeOf oldNamespaceOrType Is TypeBlockSyntax OrElse TypeOf oldNamespaceOrType Is EnumBlockSyntax OrElse TypeOf oldNamespaceOrType Is DelegateStatementSyntax Then Return CompareTypeDeclarations( oldNamespaceOrType, newNamespaceOrType, newNodeParent, eventQueue) End If Return False End Function Private Function CompareNamespaces(oldNamespace As NamespaceBlockSyntax, newNamespace As NamespaceBlockSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean If Not CompareNames(oldNamespace.NamespaceStatement.Name, newNamespace.NamespaceStatement.Name) Then Dim change = CompareRenamedDeclarations( AddressOf CompareNamespacesOrTypes, GetValidMembers(oldNamespace), GetValidMembers(newNamespace), oldNamespace, newNamespace, newNodeParent, eventQueue) If change = DeclarationChange.NameOnly Then EnqueueChangeEvent(newNamespace, newNodeParent, CodeModelEventType.Rename, eventQueue) End If Return False End If Return CompareChildren( AddressOf CompareNamespacesOrTypes, GetValidMembers(oldNamespace), GetValidMembers(newNamespace), newNamespace, CodeModelEventType.Unknown, eventQueue) End Function Private Function TypeKindChanged(oldType As DeclarationStatementSyntax, newType As DeclarationStatementSyntax) As Boolean ' Several differences in member kind should not cause an add/remove event pair. For example, changing a Sub to a Function. If oldType.IsKind(SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateSubStatement) AndAlso newType.IsKind(SyntaxKind.DeclareFunctionStatement, SyntaxKind.DelegateSubStatement) Then Return False End If Return oldType.Kind <> newType.Kind End Function Private Function CompareTypeDeclarations(oldType As DeclarationStatementSyntax, newType As DeclarationStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldType IsNot Nothing AndAlso newType IsNot Nothing) Debug.Assert(TypeOf oldType Is TypeBlockSyntax OrElse TypeOf oldType Is EnumBlockSyntax OrElse TypeOf oldType Is DelegateStatementSyntax) Debug.Assert(TypeOf newType Is TypeBlockSyntax OrElse TypeOf oldType Is EnumBlockSyntax OrElse TypeOf newType Is DelegateStatementSyntax) ' If the kind doesn't match, it has to be a remove/add. If TypeKindChanged(oldType, newType) Then EnqueueRemoveEvent(oldType, newNodeParent, eventQueue) EnqueueAddEvent(newType, newNodeParent, eventQueue) Return False End If If TypeOf oldType Is TypeBlockSyntax Then Return CompareTypes( DirectCast(oldType, TypeBlockSyntax), DirectCast(newType, TypeBlockSyntax), newNodeParent, eventQueue) ElseIf TypeOf oldType Is EnumBlockSyntax Then Return CompareEnums( DirectCast(oldType, EnumBlockSyntax), DirectCast(newType, EnumBlockSyntax), newNodeParent, eventQueue) ElseIf TypeOf oldType Is DelegateStatementSyntax Then Return CompareMethods( DirectCast(oldType, DelegateStatementSyntax), DirectCast(newType, DelegateStatementSyntax), newNodeParent, eventQueue) End If Return False End Function Private Function CompareTypes(oldType As TypeBlockSyntax, newType As TypeBlockSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim baseListsChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldType.BlockStatement.Identifier.ToString(), newType.BlockStatement.Identifier.ToString()) Then ' If the type name is different, it might mean that the whole type has been removed a new one added. ' In that case, we shouldn't do any other checks and return immediately. Dim change = CompareRenamedDeclarations( AddressOf CompareMemberDeclarations, GetValidMembers(oldType), GetValidMembers(newType), oldType, newType, newNodeParent, eventQueue) If change = DeclarationChange.WholeDeclaration Then Return False End If namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldType, newType) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareBaseLists(oldType, newType, eventQueue) Then baseListsChange = CodeModelEventType.BaseChange hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldType.BlockStatement.AttributeLists), GetAttributes(newType.BlockStatement.AttributeLists), newType, CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareChildren( AddressOf CompareMemberDeclarations, GetValidMembers(oldType), GetValidMembers(newType), newType, CodeModelEventType.Unknown, eventQueue) If hasChanges Then EnqueueChangeEvent(newType, newNodeParent, namesChange Or modifiersChange Or baseListsChange, eventQueue) End If If Not comp1 OrElse Not comp2 Then hasChanges = True End If Return Not hasChanges End Function Private Function CompareEnums(oldEnum As EnumBlockSyntax, newEnum As EnumBlockSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim baseListsChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldEnum.EnumStatement.Identifier.ToString(), newEnum.EnumStatement.Identifier.ToString()) Then ' If the type name is different, it might mean that the whole type has been removed a new one added. ' In that case, we shouldn't do any other checks and return immediately. Dim change = CompareRenamedDeclarations( AddressOf CompareMemberDeclarations, GetValidMembers(oldEnum), GetValidMembers(newEnum), oldEnum, newEnum, newNodeParent, eventQueue) If change = DeclarationChange.WholeDeclaration Then Return False End If namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldEnum, newEnum) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldEnum.EnumStatement.AttributeLists), GetAttributes(newEnum.EnumStatement.AttributeLists), newEnum, CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareChildren( AddressOf CompareMemberDeclarations, GetValidMembers(oldEnum), GetValidMembers(newEnum), newEnum, CodeModelEventType.Unknown, eventQueue) If hasChanges Then EnqueueChangeEvent(newEnum, newNodeParent, namesChange Or modifiersChange Or baseListsChange, eventQueue) End If If Not comp1 OrElse Not comp2 Then hasChanges = True End If Return Not hasChanges End Function Private Function MemberKindChanged(oldMember As StatementSyntax, newMember As StatementSyntax) As Boolean ' Several differences in member kind should not cause an add/remove event pair. For example, changing a Sub to a Function. If oldMember.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock) AndAlso newMember.IsKind(SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubBlock, SyntaxKind.FunctionBlock) Then Return False End If If oldMember.IsKind(SyntaxKind.DeclareFunctionStatement, SyntaxKind.DeclareSubStatement) AndAlso newMember.IsKind(SyntaxKind.DeclareFunctionStatement, SyntaxKind.DeclareSubStatement) Then Return False End If If oldMember.IsKind(SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock) AndAlso newMember.IsKind(SyntaxKind.PropertyStatement, SyntaxKind.PropertyBlock) Then Return False End If If oldMember.IsKind(SyntaxKind.EventStatement, SyntaxKind.EventBlock) AndAlso newMember.IsKind(SyntaxKind.EventStatement, SyntaxKind.EventBlock) Then Return False End If Return oldMember.Kind <> newMember.Kind End Function Private Function CompareMemberDeclarations(oldMember As DeclarationStatementSyntax, newMember As DeclarationStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldMember IsNot Nothing AndAlso newMember IsNot Nothing) ' If the kind doesn't match, it has to be a remove/add. If MemberKindChanged(oldMember, newMember) Then EnqueueRemoveEvent(oldMember, newNodeParent, eventQueue) EnqueueAddEvent(newMember, newNodeParent, eventQueue) Return False End If If TypeOf oldMember Is TypeBlockSyntax OrElse TypeOf oldMember Is EnumBlockSyntax OrElse TypeOf oldMember Is DelegateStatementSyntax Then Return CompareTypeDeclarations(oldMember, newMember, newNodeParent, eventQueue) ' oldMember should be checked for PropertyStatementSyntax and EventStatementSyntax before being checked for MethodBaseSyntax since ' sometimes newMember could be a PropertyBlockSyntax or EventBlockSyntax which neither MethodBlockBaseSyntax nor MethodBaseSyntax ElseIf TypeOf oldMember Is PropertyBlockSyntax OrElse TypeOf oldMember Is PropertyStatementSyntax Then Return CompareProperties( If(TypeOf oldMember Is PropertyBlockSyntax, DirectCast(oldMember, PropertyBlockSyntax).PropertyStatement, DirectCast(oldMember, PropertyStatementSyntax)), If(TypeOf newMember Is PropertyBlockSyntax, DirectCast(newMember, PropertyBlockSyntax).PropertyStatement, DirectCast(newMember, PropertyStatementSyntax)), newNodeParent, eventQueue) ElseIf TypeOf oldMember Is EventBlockSyntax OrElse TypeOf oldMember Is EventStatementSyntax Then Return CompareEvents( If(TypeOf oldMember Is EventBlockSyntax, DirectCast(oldMember, EventBlockSyntax).EventStatement, DirectCast(oldMember, EventStatementSyntax)), If(TypeOf newMember Is EventBlockSyntax, DirectCast(newMember, EventBlockSyntax).EventStatement, DirectCast(newMember, EventStatementSyntax)), newNodeParent, eventQueue) ElseIf TypeOf oldMember Is MethodBlockBaseSyntax OrElse TypeOf oldMember Is MethodBaseSyntax Then Return CompareMethods( If(TypeOf oldMember Is MethodBlockBaseSyntax, DirectCast(oldMember, MethodBlockBaseSyntax).BlockStatement, DirectCast(oldMember, MethodBaseSyntax)), If(TypeOf newMember Is MethodBlockBaseSyntax, DirectCast(newMember, MethodBlockBaseSyntax).BlockStatement, DirectCast(newMember, MethodBaseSyntax)), newNodeParent, eventQueue) ElseIf TypeOf oldMember Is FieldDeclarationSyntax Then Return CompareFields( DirectCast(oldMember, FieldDeclarationSyntax), DirectCast(newMember, FieldDeclarationSyntax), newNodeParent, eventQueue) ElseIf TypeOf oldMember Is EnumMemberDeclarationSyntax Then Return CompareEnumMembers( DirectCast(oldMember, EnumMemberDeclarationSyntax), DirectCast(newMember, EnumMemberDeclarationSyntax), newNodeParent, eventQueue) End If Debug.Fail(String.Format("Unexpected member kind: {0}", oldMember.Kind)) Throw New NotImplementedException() End Function Private Function CompareMethods(oldMethod As MethodBaseSyntax, newMethod As MethodBaseSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim typesChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldMethod.GetNameText(), newMethod.GetNameText()) Then ' If the method name is different, it might mean that the whole method has been removed a new one added. ' In that case, we shouldn't do any other checks and return immediately. Dim change = CompareRenamedDeclarations( AddressOf CompareParameters, GetParameters(oldMethod.ParameterList).AsReadOnlyList(), GetParameters(newMethod.ParameterList).AsReadOnlyList(), GetValidParentNode(oldMethod), GetValidParentNode(newMethod), newNodeParent, eventQueue) If change = DeclarationChange.WholeDeclaration Then Return False End If namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldMethod, newMethod) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareTypeNames(oldMethod.Type(), newMethod.Type()) Then typesChange = CodeModelEventType.TypeRefChange hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldMethod.AttributeLists), GetAttributes(newMethod.AttributeLists), GetValidParentNode(newMethod), CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareParameterLists( oldMethod.ParameterList, newMethod.ParameterList, GetValidParentNode(newMethod), eventQueue) If hasChanges Then EnqueueChangeEvent(newMethod, newNodeParent, namesChange Or modifiersChange Or typesChange, eventQueue) End If If Not comp1 OrElse Not comp2 Then hasChanges = True End If Return Not hasChanges End Function Private Function CompareProperties(oldProperty As PropertyStatementSyntax, newProperty As PropertyStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim typesChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldProperty.Identifier.ToString(), newProperty.Identifier.ToString()) Then ' If the property name is different, it might mean that the property method has been removed a new one added. ' In that case, we shouldn't do any other checks and return immediately. Dim change = CompareRenamedDeclarations( AddressOf CompareParameters, GetParameters(oldProperty.ParameterList).AsReadOnlyList(), GetParameters(newProperty.ParameterList).AsReadOnlyList(), GetValidParentNode(oldProperty), GetValidParentNode(newProperty), newNodeParent, eventQueue) If change = DeclarationChange.WholeDeclaration Then Return False End If namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldProperty, newProperty) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareTypeNames(oldProperty.Type(), newProperty.Type()) Then typesChange = CodeModelEventType.TypeRefChange hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldProperty.AttributeLists), GetAttributes(newProperty.AttributeLists), GetValidParentNode(newProperty), CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareParameterLists( oldProperty.ParameterList, newProperty.ParameterList, GetValidParentNode(newProperty), eventQueue) If hasChanges Then EnqueueChangeEvent(newProperty, newNodeParent, namesChange Or modifiersChange Or typesChange, eventQueue) End If If Not comp1 OrElse Not comp2 Then hasChanges = True End If Return Not hasChanges End Function Private Function CompareEvents(oldEvent As EventStatementSyntax, newEvent As EventStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim typesChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldEvent.Identifier.ToString(), newEvent.Identifier.ToString()) Then ' If the property name is different, it might mean that the property method has been removed a new one added. ' In that case, we shouldn't do any other checks and return immediately. Dim change = CompareRenamedDeclarations( AddressOf CompareParameters, GetParameters(oldEvent.ParameterList).AsReadOnlyList(), GetParameters(newEvent.ParameterList).AsReadOnlyList(), GetValidParentNode(oldEvent), GetValidParentNode(newEvent), newNodeParent, eventQueue) If change = DeclarationChange.WholeDeclaration Then Return False End If namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldEvent, newEvent) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareTypeNames(oldEvent.Type(), newEvent.Type()) Then typesChange = CodeModelEventType.TypeRefChange hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldEvent.AttributeLists), GetAttributes(newEvent.AttributeLists), GetValidParentNode(newEvent), CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareParameterLists( oldEvent.ParameterList, newEvent.ParameterList, GetValidParentNode(newEvent), eventQueue) If hasChanges Then EnqueueChangeEvent(newEvent, newNodeParent, namesChange Or modifiersChange Or typesChange, eventQueue) End If If Not comp1 OrElse Not comp2 Then hasChanges = True End If Return Not hasChanges End Function Private Function CompareFields(oldField As FieldDeclarationSyntax, newField As FieldDeclarationSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldField IsNot Nothing AndAlso newField IsNot Nothing) Dim hasChanges = False If CompareChildren( AddressOf CompareModifiedIdentifiers, GetNames(oldField.Declarators), GetNames(newField.Declarators), newNodeParent, CodeModelEventType.Unknown, eventQueue) Then hasChanges = True End If If CompareChildren( AddressOf CompareAttributes, GetAttributes(oldField.AttributeLists), GetAttributes(newField.AttributeLists), newField, CodeModelEventType.Unknown, eventQueue) Then hasChanges = True End If Return hasChanges End Function Private Function CompareModifiedIdentifiers(oldModifiedIdentifier As ModifiedIdentifierSyntax, newModifiedIdentifier As ModifiedIdentifierSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldModifiedIdentifier IsNot Nothing AndAlso newModifiedIdentifier IsNot Nothing) Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim typesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(oldModifiedIdentifier.Identifier.ToString(), newModifiedIdentifier.Identifier.ToString()) Then namesChange = CodeModelEventType.Rename Return False End If Dim oldVariableDeclarator = DirectCast(oldModifiedIdentifier.Parent, VariableDeclaratorSyntax) Dim newVariableDeclarator = DirectCast(newModifiedIdentifier.Parent, VariableDeclaratorSyntax) If Not CompareTypeNames(oldVariableDeclarator.Type(), newVariableDeclarator.Type()) Then typesChange = CodeModelEventType.TypeRefChange hasChanges = True End If Dim oldField = DirectCast(oldVariableDeclarator.Parent, FieldDeclarationSyntax) Dim newField = DirectCast(newVariableDeclarator.Parent, FieldDeclarationSyntax) If Not CompareModifiers(oldField, newField) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If hasChanges Then EnqueueChangeEvent(newModifiedIdentifier, newNodeParent, namesChange Or typesChange Or modifiersChange, eventQueue) End If Return Not hasChanges End Function Private Function CompareEnumMembers(oldEnumMember As EnumMemberDeclarationSyntax, newEnumMember As EnumMemberDeclarationSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldEnumMember IsNot Nothing AndAlso newEnumMember IsNot Nothing) Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 If Not StringComparer.Ordinal.Equals(oldEnumMember.Identifier.ToString(), newEnumMember.Identifier.ToString()) Then namesChange = CodeModelEventType.Rename hasChanges = True End If Dim comp1 = CompareChildren( AddressOf CompareAttributes, GetAttributes(oldEnumMember.AttributeLists), GetAttributes(newEnumMember.AttributeLists), newEnumMember, CodeModelEventType.Unknown, eventQueue) If hasChanges Then EnqueueChangeEvent(newEnumMember, newNodeParent, namesChange, eventQueue) End If If Not comp1 Then hasChanges = True End If Return Not hasChanges End Function Private Function CompareParameterLists(oldParameterList As ParameterListSyntax, newParameterList As ParameterListSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Dim oldParameters = GetParameters(oldParameterList) Dim newParameters = GetParameters(newParameterList) Return CompareChildren( AddressOf CompareParameters, oldParameters.AsReadOnlyList(), newParameters.AsReadOnlyList(), newNodeParent, CodeModelEventType.Unknown, eventQueue) End Function Private Function CompareParameters(oldParameter As ParameterSyntax, newParameter As ParameterSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Debug.Assert(oldParameter IsNot Nothing AndAlso newParameter IsNot Nothing) Dim hasChanges = False Dim namesChange As CodeModelEventType = 0 Dim modifiersChange As CodeModelEventType = 0 Dim typesChange As CodeModelEventType = 0 Dim valuesChange As CodeModelEventType = 0 If Not StringComparer.OrdinalIgnoreCase.Equals(Me.CodeModelService.GetParameterName(oldParameter), Me.CodeModelService.GetParameterName(newParameter)) Then namesChange = CodeModelEventType.Rename hasChanges = True End If If Not CompareModifiers(oldParameter, newParameter) Then modifiersChange = CodeModelEventType.Unknown hasChanges = True End If If Not CompareTypeNames(oldParameter.Type(), newParameter.Type()) Then typesChange = CodeModelEventType.TypeRefChange hasChanges = True End If If hasChanges Then EnqueueChangeEvent(newParameter, newNodeParent, namesChange Or modifiersChange Or valuesChange Or typesChange, eventQueue) End If Return Not hasChanges End Function Private Function CompareBaseLists(oldType As TypeBlockSyntax, newType As TypeBlockSyntax, eventQueue As CodeModelEventQueue) As Boolean Dim comp1 = CompareChildren( AddressOf CompareInherits, oldType.Inherits.AsReadOnlyList(), newType.Inherits.AsReadOnlyList(), newType, CodeModelEventType.Unknown, eventQueue) Dim comp2 = CompareChildren( AddressOf CompareImplements, oldType.Implements.AsReadOnlyList(), newType.Implements.AsReadOnlyList(), newType, CodeModelEventType.Unknown, eventQueue) Return comp1 AndAlso comp2 End Function Private Function CompareInherits(oldInherits As InheritsStatementSyntax, newInherits As InheritsStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Return True End Function Private Function CompareImplements(oldImplements As ImplementsStatementSyntax, newImplements As ImplementsStatementSyntax, newNodeParent As SyntaxNode, eventQueue As CodeModelEventQueue) As Boolean Return True End Function Private Function CompareModifiers(oldMember As StatementSyntax, newMember As StatementSyntax) As Boolean Return oldMember.GetModifierFlags() = newMember.GetModifierFlags() End Function Private Function CompareModifiers(oldParameter As ParameterSyntax, newParameter As ParameterSyntax) As Boolean Return oldParameter.GetModifierFlags() = newParameter.GetModifierFlags() End Function Private Function CompareExpressions(oldExpression As ExpressionSyntax, newExpression As ExpressionSyntax) As Boolean If oldExpression Is Nothing OrElse newExpression Is Nothing Then Return oldExpression Is newExpression End If If oldExpression.Kind <> newExpression.Kind Then Return False End If If TypeOf oldExpression Is TypeSyntax Then Return CompareTypeNames(DirectCast(oldExpression, TypeSyntax), DirectCast(newExpression, TypeSyntax)) End If If TypeOf oldExpression Is LiteralExpressionSyntax Then Return StringComparer.OrdinalIgnoreCase.Equals(oldExpression.ToString(), newExpression.ToString()) End If If TypeOf oldExpression Is CastExpressionSyntax Then Dim oldCast = DirectCast(oldExpression, CastExpressionSyntax) Dim newCast = DirectCast(newExpression, CastExpressionSyntax) Return CompareTypeNames(oldCast.Type, newCast.Type) AndAlso CompareExpressions(oldCast.Expression, newCast.Expression) End If If TypeOf oldExpression Is PredefinedCastExpressionSyntax Then Dim oldPredefinedCast = DirectCast(oldExpression, PredefinedCastExpressionSyntax) Dim newPredefinedCast = DirectCast(newExpression, PredefinedCastExpressionSyntax) Return CompareExpressions(oldPredefinedCast.Expression, newPredefinedCast.Expression) End If If TypeOf oldExpression Is UnaryExpressionSyntax Then Dim oldUnaryExpression = DirectCast(oldExpression, UnaryExpressionSyntax) Dim newUnaryExpression = DirectCast(newExpression, UnaryExpressionSyntax) Return CompareExpressions(oldUnaryExpression.Operand, newUnaryExpression.Operand) End If If TypeOf oldExpression Is BinaryExpressionSyntax Then Dim oldBinaryExpression = DirectCast(oldExpression, BinaryExpressionSyntax) Dim newBinaryExpression = DirectCast(newExpression, BinaryExpressionSyntax) Return CompareExpressions(oldBinaryExpression.Left, newBinaryExpression.Left) AndAlso CompareExpressions(oldBinaryExpression.Right, newBinaryExpression.Right) End If If TypeOf oldExpression Is MemberAccessExpressionSyntax Then Dim oldMemberAccess = DirectCast(oldExpression, MemberAccessExpressionSyntax) Dim newMemberAccess = DirectCast(newExpression, MemberAccessExpressionSyntax) Return CompareExpressions(oldMemberAccess.Expression, newMemberAccess.Expression) AndAlso CompareExpressions(oldMemberAccess.Name, newMemberAccess.Name) End If Return True End Function Private Function CompareTypeNames(oldType As TypeSyntax, newType As TypeSyntax) As Boolean If oldType Is Nothing OrElse newType Is Nothing Then Return oldType Is newType End If If oldType.Kind <> newType.Kind Then Return False End If Select Case oldType.Kind Case SyntaxKind.PredefinedType Dim oldPredefinedType = DirectCast(oldType, PredefinedTypeSyntax) Dim newPredefinedType = DirectCast(newType, PredefinedTypeSyntax) Return oldPredefinedType.Keyword.Kind = newPredefinedType.Keyword.Kind Case SyntaxKind.ArrayType Dim oldArrayType = DirectCast(oldType, ArrayTypeSyntax) Dim newArrayType = DirectCast(newType, ArrayTypeSyntax) Return oldArrayType.RankSpecifiers.Count = newArrayType.RankSpecifiers.Count AndAlso CompareTypeNames(oldArrayType.ElementType, newArrayType.ElementType) Case SyntaxKind.NullableType Dim oldNullableType = DirectCast(oldType, NullableTypeSyntax) Dim newNullableType = DirectCast(newType, NullableTypeSyntax) Return CompareTypeNames(oldNullableType.ElementType, newNullableType.ElementType) Case SyntaxKind.IdentifierName, SyntaxKind.QualifiedName, SyntaxKind.GlobalName, SyntaxKind.GenericName Dim oldName = DirectCast(oldType, NameSyntax) Dim newName = DirectCast(newType, NameSyntax) Return CompareNames(oldName, newName) End Select Debug.Fail(String.Format("Unknown kind: {0}", oldType.Kind)) Return False End Function Private Function CompareNames(oldName As NameSyntax, newName As NameSyntax) As Boolean If oldName.Kind <> newName.Kind Then Return False End If Select Case oldName.Kind Case SyntaxKind.IdentifierName Dim oldIdentifierName = DirectCast(oldName, IdentifierNameSyntax) Dim newIdentifierName = DirectCast(newName, IdentifierNameSyntax) Return StringComparer.OrdinalIgnoreCase.Equals(oldIdentifierName.Identifier.ToString(), newIdentifierName.Identifier.ToString()) Case SyntaxKind.QualifiedName Dim oldQualifiedName = DirectCast(oldName, QualifiedNameSyntax) Dim newQualifiedName = DirectCast(newName, QualifiedNameSyntax) Return CompareNames(oldQualifiedName.Left, newQualifiedName.Left) AndAlso CompareNames(oldQualifiedName.Right, newQualifiedName.Right) Case SyntaxKind.GenericName Dim oldGenericName = DirectCast(oldName, GenericNameSyntax) Dim newGenericName = DirectCast(newName, GenericNameSyntax) If Not StringComparer.OrdinalIgnoreCase.Equals(oldGenericName.Identifier.ToString(), newGenericName.Identifier.ToString()) Then Return False End If If oldGenericName.Arity <> newGenericName.Arity Then Return False End If For i = 0 To oldGenericName.Arity - 1 If Not CompareTypeNames(oldGenericName.TypeArgumentList.Arguments(i), newGenericName.TypeArgumentList.Arguments(i)) Then Return False End If Next Return True Case SyntaxKind.GlobalName Return True End Select Debug.Fail(String.Format("Unknown kind: {0}", oldName.Kind)) Return False End Function Protected Overrides Sub CollectCore(oldRoot As SyntaxNode, newRoot As SyntaxNode, eventQueue As CodeModelEventQueue) CompareCompilationUnits(DirectCast(oldRoot, CompilationUnitSyntax), DirectCast(newRoot, CompilationUnitSyntax), eventQueue) End Sub Private Function GetValidParentNode(node As SyntaxNode) As SyntaxNode If TypeOf node Is TypeStatementSyntax AndAlso TypeOf node.Parent Is TypeBlockSyntax Then Return node.Parent End If If TypeOf node Is EnumStatementSyntax AndAlso TypeOf node.Parent Is EnumBlockSyntax Then Return node.Parent End If If TypeOf node Is MethodBaseSyntax AndAlso TypeOf node.Parent Is MethodBlockBaseSyntax Then Return node.Parent End If If TypeOf node Is PropertyStatementSyntax AndAlso TypeOf node.Parent Is PropertyBlockSyntax Then Return node.Parent End If If TypeOf node Is EventStatementSyntax AndAlso TypeOf node.Parent Is EventBlockSyntax Then Return node.Parent End If Return node End Function Protected Overrides Sub EnqueueAddEvent(node As SyntaxNode, parent As SyntaxNode, eventQueue As CodeModelEventQueue) If eventQueue Is Nothing Then Return End If If TypeOf node Is IncompleteMemberSyntax Then Return End If If TypeOf node Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(node, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueAddEvent(name, parent) Next Next Return End If If TypeOf parent Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(parent, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueAddEvent(node, name) Next Next Return End If eventQueue.EnqueueAddEvent(GetValidParentNode(node), parent) End Sub Protected Overrides Sub EnqueueChangeEvent(node As SyntaxNode, parent As SyntaxNode, eventType As CodeModelEventType, eventQueue As CodeModelEventQueue) If eventQueue Is Nothing Then Return End If If TypeOf node Is IncompleteMemberSyntax Then Return End If If TypeOf node Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(node, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueChangeEvent(name, parent, eventType) Next Next Return End If If TypeOf parent Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(parent, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueChangeEvent(node, name, eventType) Next Next Return End If eventQueue.EnqueueChangeEvent(GetValidParentNode(node), parent, eventType) End Sub Protected Overrides Sub EnqueueRemoveEvent(node As SyntaxNode, parent As SyntaxNode, eventQueue As CodeModelEventQueue) If eventQueue Is Nothing Then Return End If If TypeOf node Is IncompleteMemberSyntax Then Return End If If TypeOf node Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(node, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueRemoveEvent(name, parent) Next Next Return End If If TypeOf parent Is FieldDeclarationSyntax Then For Each variableDeclarator In DirectCast(parent, FieldDeclarationSyntax).Declarators For Each name In variableDeclarator.Names eventQueue.EnqueueRemoveEvent(node, name) Next Next Return End If eventQueue.EnqueueRemoveEvent(GetValidParentNode(node), GetValidParentNode(parent)) End Sub End Class End Class End Namespace
bbarry/roslyn
src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.CodeModelEventCollector.vb
Visual Basic
apache-2.0
58,754