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
|
|---|---|---|---|---|---|
' 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.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.VisualStudio.GraphModel
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Public Class GraphNodeIdTests
Private Async Function AssertMarkedNodeIdIsAsync(code As String, expectedId As String, Optional language As String = "C#", Optional symbolTransform As Func(Of ISymbol, ISymbol) = Nothing) As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language=<%= language %> CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
<%= code %>
</Document>
</Project>
</Workspace>)
Dim graph = await testState.GetGraphWithMarkedSymbolNodeAsync(symbolTransform)
Dim node = graph.Nodes.Single()
Assert.Equal(expectedId, node.Id.ToString())
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestSimpleType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class $$C { } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C)")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestNestedType() As Task
Await AssertMarkedNodeIdIsAsync("namespace N { class C { class $$E { } } }", "(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=E ParentType=C))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithSimpleArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=Int32))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithNestedArrayType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(int[][,] p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Int32 ArrayRank=1 ParentType=(Name=Int32 ArrayRank=2 ParentType=Int32)))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { struct S { } unsafe void $$M(S** p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=S Indirection=2 ParentType=C))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithVoidPointerType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { unsafe void $$M(void* p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Void Indirection=1))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T t, U u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0),(ParameterIdentifier=0)]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(547263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547263")>
Public Async Function TestMemberWithParameterTypeConstructedWithMemberTypeParameter() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M<T>(T t, System.Func<T, int> u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=(Name=Func GenericParameterCount=2 GenericArguments=[(ParameterIdentifier=0),(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithArraysOfGenericTypeParameters() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[] t, U[] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ParameterIdentifier=0)))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithArraysOfGenericTypeParameters2() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C<T> { void $$M<U>(T[][,] t, U[][,] u) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(Name=C GenericParameterCount=1) Member=(Name=M GenericParameterCount=1 OverloadingParameters=[(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(Type=(Name=C GenericParameterCount=1) ParameterIdentifier=0)))),(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=(ArrayRank=1 ParentType=(ArrayRank=2 ParentType=(ParameterIdentifier=0))))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestMemberWithGenericType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<int> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System Type=Int32)]))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=Object)]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithGenericTypeOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(System.Collections.Generic.List<dynamic> p) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Assembly=file:///Z:/FxReferenceAssembliesUri Namespace=System.Collections.Generic Type=(Name=List GenericParameterCount=1 GenericArguments=[(Namespace=System Type=Object)]))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(616549, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/616549")>
Public Async Function TestMemberWithArrayOfDynamicType() As Task
Await AssertMarkedNodeIdIsAsync(
"namespace N { class C { void $$M(dynamic[] d) { } } }",
"(Assembly=file:///Z:/CSharpAssembly1.dll Namespace=N Type=C Member=(Name=M OverloadingParameters=[(Namespace=System Type=(Name=Object ArrayRank=1 ParentType=Object))]))")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Progression), WorkItem(547234, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547234")>
Public Async Function TestErrorType() As Task
Await AssertMarkedNodeIdIsAsync(
"Class $$C : Inherits D : End Class",
"Type=D",
LanguageNames.VisualBasic,
Function(s) DirectCast(s, INamedTypeSymbol).BaseType)
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/VisualStudio/Core/Test/Progression/GraphNodeIdTests.vb
|
Visual Basic
|
apache-2.0
| 9,683
|
' Copyright (c) Microsoft. All rights reserved.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Net.Http
Imports Windows.ApplicationModel.Background
Imports Windows.Devices.Enumeration
Imports Windows.Devices.I2C
Imports Windows.System.Threading
' The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
Public NotInheritable Class StartupTask
Implements IBackgroundTask
Dim deferral As BackgroundTaskDeferral
Dim sensor As I2cDevice
Dim timer As ThreadPoolTimer
Public Async Sub Run(taskInstance As IBackgroundTaskInstance) Implements IBackgroundTask.Run
deferral = taskInstance.GetDeferral()
Dim controller As I2cController
controller = Await I2cController.GetDefaultAsync()
sensor = controller.GetDevice(New I2cConnectionSettings(&H40))
timer = ThreadPoolTimer.CreatePeriodicTimer(AddressOf Timer_Tick, TimeSpan.FromSeconds(2))
End Sub
Public Sub Timer_Tick(timer As ThreadPoolTimer)
Dim tempCommand(0 To 0) As Byte
tempCommand(0) = &HE3
Dim tempData(0 To 1) As Byte
sensor.WriteRead(tempCommand, tempData)
Dim byte0 As Int32 = tempData(0)
Dim byte1 As Int32 = tempData(1)
Dim rawReading As Short = byte0 << 8 Or byte1
Dim tempRatio As Double = rawReading / 65536.0
Dim temperature As Double = (-46.85 + (175.72 * tempRatio)) * 9.0 / 5.0 + 32
System.Diagnostics.Debug.WriteLine("Temp: " + temperature.ToString())
Dim humidityCommand(0 To 0) As Byte
humidityCommand(0) = &HE5
Dim humidityData(0 To 1) As Byte
sensor.WriteRead(humidityCommand, humidityData)
byte0 = humidityData(0)
byte1 = humidityData(1)
rawReading = byte0 << 8 Or byte1
Dim humidityRatio As Double = rawReading / 65536.0
Dim humidity As Double = -6 + (125 * humidityRatio)
System.Diagnostics.Debug.WriteLine("Humidity: " + humidity.ToString())
End Sub
End Class
|
parameshbabu/samples
|
WeatherStation/VB/WeatherStationVB/StartupTask.vb
|
Visual Basic
|
mit
| 2,079
|
' 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.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Declarations
''' <summary>
''' Recommends the "Function" and "Sub" keywords in external method declarations.
''' </summary>
Friend Class DelegateSubFunctionKeywordRecommender
Inherits AbstractKeywordRecommender
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As IEnumerable(Of RecommendedKeyword)
If context.FollowsEndOfStatement Then
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End If
If context.TargetToken.IsChildToken(Of DelegateStatementSyntax)(Function(delegateDeclaration) delegateDeclaration.DelegateKeyword) Then
Return {New RecommendedKeyword("Function", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Function_procedure_that_is_a_procedure_that_returns_a_value_to_the_calling_code),
New RecommendedKeyword("Sub", VBFeaturesResources.Declares_the_name_parameters_and_code_that_define_a_Sub_procedure_that_is_a_procedure_that_does_not_return_a_value_to_the_calling_code)}
Else
Return SpecializedCollections.EmptyEnumerable(Of RecommendedKeyword)()
End If
End Function
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Declarations/DelegateSubFunctionKeywordRecommender.vb
|
Visual Basic
|
apache-2.0
| 1,742
|
' 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.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Partial Public Class GetExtendedSemanticInfoTests
<Fact>
Public Sub [GetXmlNamespace]()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/">
Module M
Private F1 = GetXmlNamespace(p)
Private F2 = GetXmlNamespace()
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' GetXmlNamespace with argument.
Dim node = FindNodeFromText(tree, "GetXmlNamespace(p)")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XNamespace")
' GetXmlNamespace with no argument.
node = FindNodeFromText(tree, "GetXmlNamespace()")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XNamespace")
End Sub
<Fact>
Public Sub XmlDocument()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Private F = <?xml version="1.0"?><?pi data?><!-- comment --><x/>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XML document
Dim node = FindNodeFromText(tree, "<?xml").Parent
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XDocument")
' Declaration
node = FindNodeFromText(tree, "<?xml")
Assert.IsNotType(Of ExpressionSyntax)(node)
' Processing instruction.
node = FindNodeFromText(tree, "<?pi")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XProcessingInstruction")
' Comment.
node = FindNodeFromText(tree, "<!--")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XComment")
' Root element.
node = FindNodeFromText(tree, "<x/>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
End Sub
<Fact>
Public Sub XmlProcessingInstruction()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Private F As Object = <?p?>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = FindNodeFromText(tree, "<?p?>")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XProcessingInstruction")
End Sub
<Fact>
Public Sub XmlElement()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Module M
Public F = <x a="b"><y/>z<![CDATA[c]]>B</>
End Module
</file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XML element
Dim node = FindNodeFromText(tree, "<x ").Parent
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
' Start tag.
node = FindNodeFromText(tree, "<x ")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
' End tag.
node = FindNodeFromText(tree, "</>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
' Element name.
node = FindNodeFromText(tree, "x ")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Attribute.
node = FindNodeFromText(tree, "a=").Parent
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XAttribute")
' Attribute name.
node = FindNodeFromText(tree, "a=")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Attribute value.
node = FindNodeFromText(tree, """b""")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' Sub element
node = FindNodeFromText(tree, "<y/>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
' Text.
node = FindNodeFromText(tree, "z")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' CDATA.
node = FindNodeFromText(tree, "<![CDATA[c]]>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XCData")
' Entity.
node = FindNodeFromText(tree, "B")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
End Sub
<Fact>
Public Sub XmlName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb">
Module M
Sub Main()
Dim x = <xmlliteral>
</xmlliteral>
End Sub
End Module
</file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of XmlNameSyntax).Last
Assert.Equal("xmlliteral", syntax.ToString())
Dim symbolInfo = semanticModel.GetSymbolInfo(syntax)
Assert.Null(symbolInfo.Symbol)
Dim typeInfo = semanticModel.GetTypeInfo(syntax)
Assert.Null(typeInfo.Type)
End Sub
' Redundant xmlns attributes (matching Imports) will be dropped.
' Ensure we are still generating BoundNodes for semantic info.
<Fact>
Public Sub XmlnsAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Option Strict On
Imports <xmlns:p="http://roslyn/">
Module M
Private F As Object = <x xmlns:p="http://roslyn/"/>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = FindNodeOfTypeFromText(Of XmlAttributeSyntax)(tree, "xmlns:p=""http://roslyn/""/>")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XAttribute")
End Sub
<Fact>
Public Sub XmlPrefix()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports <xmlns:p="http://roslyn/p">
Module M
Private F As Object = p
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
Dim node = FindNodeOfTypeFromText(Of EqualsValueSyntax)(tree, "= p").Value
Dim info = semanticModel.GetSemanticInfoSummary(node)
Assert.True(DirectCast(info.Type, TypeSymbol).IsErrorType())
End Sub
<Fact>
Public Sub XmlEmbeddedExpression()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Private F1 As String = "y"
Private F2 = <x <%= F1 %>=""/>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' Embedded expression.
Dim node = FindNodeFromText(tree, "<%= F1 %>")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' Expression only.
node = FindNodeFromText(tree, "F1 %>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
End Sub
<Fact>
Public Sub XmlElementAccess()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports <xmlns:p="...">
Module M
Private F = <x/>.<y>.<p:z>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XElement member access.
Dim node = FindNodeFromText(tree, "<y>")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "IEnumerable(Of XElement)")
' IEnumerable(Of XElement) member access.
node = FindNodeFromText(tree, "<p:z>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "IEnumerable(Of XElement)")
' Member access name.
node = FindNodeFromText(tree, "y")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access qualified name.
node = FindNodeFromText(tree, "p:").Parent
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access local name.
node = FindNodeFromText(tree, "z")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
End Sub
<Fact>
Public Sub XmlDescendantAccess()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports <xmlns:p="...">
Module M
Private F = <x/>...<y>...<p:z>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XElement member access.
Dim node = FindNodeFromText(tree, "<y>")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "IEnumerable(Of XElement)")
' IEnumerable(Of XElement) member access.
node = FindNodeFromText(tree, "<p:z>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "IEnumerable(Of XElement)")
' Member access name.
node = FindNodeFromText(tree, "y")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access qualified name.
node = FindNodeFromText(tree, "p:").Parent
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access local name.
node = FindNodeFromText(tree, "z")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
End Sub
<Fact>
Public Sub XmlAttributeAccess()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports <xmlns:p="...">
Module M
Private F1 = <x/>.@y
Private F2 = <x/>.@p:z
Private F3 = <x/>.@<z>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XElement attribute access.
Dim node = FindNodeFromText(tree, "@y")
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' IEnumerable(Of XElement) attribute access.
node = FindNodeFromText(tree, "@p:z")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' XElement attribute access, bracketed name syntax.
node = FindNodeFromText(tree, "@<z>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
' Member access name.
node = FindNodeFromText(tree, "y")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access qualified name.
node = FindNodeFromText(tree, "p:").Parent
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access local name.
node = FindNodeFromText(tree, "z")
info = semanticModel.GetSemanticInfoSummary(node)
Assert.Null(info.Type)
' Member access bracketed name.
node = FindNodeFromText(tree, "<z>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "String")
End Sub
<Fact>
Public Sub ValueExtensionProperty()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M()
Dim x = <x/>
x.<y>.Value = x.<z>.Value
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertNoErrors()
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
ValueExtensionPropertyCore(model, FindNodeOfTypeFromText(Of MemberAccessExpressionSyntax)(tree, "x.<y>.Value"))
ValueExtensionPropertyCore(model, FindNodeOfTypeFromText(Of MemberAccessExpressionSyntax)(tree, "x.<z>.Value"))
End Sub
Private Sub ValueExtensionPropertyCore(model As SemanticModel, expr As MemberAccessExpressionSyntax)
Dim info = model.GetSymbolInfo(expr)
Dim symbol = TryCast(info.Symbol, PropertySymbol)
Assert.NotNull(symbol)
CheckSymbol(symbol, "Property InternalXmlHelper.Value As String")
Assert.Equal(0, symbol.GetMethod.Parameters().Length)
Assert.Equal(1, symbol.SetMethod.Parameters().Length)
End Sub
<WorkItem(545659, "DevDiv")>
<Fact>
Public Sub LookupValueExtensionProperty()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections
Imports System.Collections.Generic
Imports System.Xml.Linq
Structure S
Implements IEnumerable(Of XElement)
Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator
Return Nothing
End Function
Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Structure
Class C
Implements IEnumerable(Of XElement)
Private Function GetEnumerator() As IEnumerator(Of XElement) Implements IEnumerable(Of XElement).GetEnumerator
Return Nothing
End Function
Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator
Return Nothing
End Function
End Class
Module M
Sub M(Of T As IEnumerable(Of XElement))(_1 As IEnumerable(Of XElement), _2 As C, _3 As S, _4 As T, _5 As IEnumerable(Of Object))
Dim o As Object
o = _1.Value
o = _2.Value
o = _3.Value
o = _4.Value
o = _5.Value
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30456: 'Value' is not a member of 'IEnumerable(Of Object)'.
o = _5.Value
~~~~~~~~
]]></errors>)
Dim tree = compilation.SyntaxTrees(0)
Dim model = compilation.GetSemanticModel(tree)
Dim position = FindNodeFromText(tree, "_1.Value").SpanStart
Dim method = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("M").GetMember(Of MethodSymbol)("M")
Dim n = method.Parameters.Length - 1
For i = 0 To n
Dim parameter = method.Parameters(i)
Dim type = parameter.Type
Dim descriptions = If(i < n, {"Property InternalXmlHelper.Value As String"}, {})
Dim symbols = model.LookupSymbols(position, container:=type, name:="Value", includeReducedExtensionMethods:=True)
CheckSymbols(symbols, descriptions)
symbols = model.LookupSymbols(position, container:=Nothing, name:="Value", includeReducedExtensionMethods:=True)
CheckSymbols(symbols)
symbols = model.LookupSymbols(position, container:=type, name:=Nothing, includeReducedExtensionMethods:=True)
symbols = symbols.WhereAsArray(Function(s) s.Name = "Value")
CheckSymbols(symbols, descriptions)
Next
End Sub
<WorkItem(544421, "DevDiv")>
<Fact()>
Public Sub XmlEndElementNoMatchingStart()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Private F = <?xml version="1.0"?><?p?></x>
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
Dim tree = compilation.SyntaxTrees(0)
Dim semanticModel = compilation.GetSemanticModel(tree)
' XDocument.
Dim node = FindNodeFromText(tree, "<?xml").Parent
Dim info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XDocument")
' Invalid root XmlElement.
node = FindNodeFromText(tree, "</x>")
info = semanticModel.GetSemanticInfoSummary(node)
CheckSymbol(info.Type, "XElement")
End Sub
<WorkItem(545167, "DevDiv")>
<Fact()>
Public Sub XmlElementEndTag()
Dim compilation = CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb"><![CDATA[
Module M
Private F As String = </>.ToString()'BIND:"</>"
End Module
]]></file>
</compilation>)
Dim semanticSummary = CompilationUtils.GetSemanticInfoSummary(Of XmlElementSyntax)(compilation, "a.vb")
Assert.Equal("System.Xml.Linq.XElement[missing]", semanticSummary.Type.ToTestDisplayString())
Assert.Equal(TypeKind.Error, semanticSummary.Type.TypeKind)
Assert.Equal("System.Xml.Linq.XElement[missing]", semanticSummary.ConvertedType.ToTestDisplayString())
Assert.Equal(TypeKind.Error, semanticSummary.ConvertedType.TypeKind)
Assert.Equal(ConversionKind.Identity, semanticSummary.ImplicitConversion.Kind)
Assert.Null(semanticSummary.Symbol)
Assert.Equal(CandidateReason.None, semanticSummary.CandidateReason)
Assert.Equal(0, semanticSummary.CandidateSymbols.Length)
Assert.Null(semanticSummary.Alias)
Assert.Equal(0, semanticSummary.MemberGroup.Length)
Assert.False(semanticSummary.ConstantValue.HasValue)
End Sub
End Class
End Namespace
|
droyad/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/XmlLiteralSemanticModelTests.vb
|
Visual Basic
|
apache-2.0
| 20,900
|
' 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.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class TryBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
Protected Overloads Overrides Function GetHighlights(node As SyntaxNode, cancellationToken As CancellationToken) As IEnumerable(Of TextSpan)
If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of TextSpan)()
End If
Dim highlights As New List(Of TextSpan)
With tryBlock
highlights.Add(.TryStatement.TryKeyword.Span)
HighlightRelatedStatements(tryBlock, highlights)
For Each catchBlock In .CatchBlocks
With catchBlock.CatchStatement
highlights.Add(.CatchKeyword.Span)
If .WhenClause IsNot Nothing Then
highlights.Add(.WhenClause.WhenKeyword.Span)
End If
End With
HighlightRelatedStatements(catchBlock, highlights)
Next
If .FinallyBlock IsNot Nothing Then
highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span)
End If
highlights.Add(.EndTryStatement.Span)
Return highlights
End With
End Function
Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan))
If node.Kind = SyntaxKind.ExitTryStatement Then
highlights.Add(node.Span)
Else
For Each childNodeOrToken In node.ChildNodesAndTokens()
If childNodeOrToken.IsToken Then
Continue For
End If
Dim child = childNodeOrToken.AsNode()
If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(child, highlights)
End If
Next
End If
End Sub
End Class
End Namespace
|
REALTOBIZ/roslyn
|
src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/TryBlockHighlighter.vb
|
Visual Basic
|
apache-2.0
| 2,823
|
Imports System.IO
Imports Aspose.Cells
Namespace Articles
Public Class ChangeHtmlLinkTarget
Public Shared Sub Run()
' ExStart:1
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
Dim inputPath As String = dataDir & "Sample1.xlsx"
Dim outputPath As String = dataDir & "Output.out.html"
Dim workbook As Workbook = New Workbook(inputPath)
Dim opts As HtmlSaveOptions = New HtmlSaveOptions()
opts.LinkTargetType = HtmlLinkTargetType.Self
workbook.Save(outputPath, opts)
Console.WriteLine("File saved: {0}", outputPath)
' ExEnd:1
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/ChangeHtmlLinkTarget.vb
|
Visual Basic
|
mit
| 767
|
Imports System.Web.Services
#If DEBUG Then
Partial Public Class JQueryPageMethods
Inherits BaseClasses.BaseSecurityPage
#Else
<ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Never), ComponentModel.ToolboxItem(False)> _
Partial Public Class JQueryPageMethods
Inherits BaseClasses.BaseSecurityPage
#End If
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
<WebMethod()> _
Public Shared Function GetDate(ByVal [when] As String) As String
Dim str As String
Using strR As New IO.StreamReader(HttpContext.Current.Request.InputStream)
str = strR.ReadToEnd
End Using
Select Case [when]
Case "Yesterday"
Return DateTime.Now.AddDays(-1).ToString()
Case "Today"
Return DateTime.Now.ToString()
Case "Tomorrow"
Return DateTime.Now.AddDays(1).ToString()
End Select
Return DateTime.Now.ToString()
End Function
End Class
|
Micmaz/DTIControls
|
DTICalendar/DTICalendar/JsonPOC/JQueryPageMethods.aspx.vb
|
Visual Basic
|
mit
| 1,138
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' La información general sobre un ensamblado se controla mediante el siguiente
' conjunto de atributos. Cambie estos atributos para modificar la información
' asociada con un ensamblado.
' Revisar los valores de los atributos del ensamblado
<Assembly: AssemblyTitle("BEZarenKalkulua")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("UPV/EHU")>
<Assembly: AssemblyProduct("BEZarenKalkulua")>
<Assembly: AssemblyCopyright("Copyright © UPV/EHU 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM
<Assembly: Guid("3a29b9db-f00a-4408-bd97-f16f87b588a0")>
' La información de versión de un ensamblado consta de los cuatro valores siguientes:
'
' Versión principal
' Versión secundaria
' Número de compilación
' Revisión
'
' Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión
' mediante el asterisco ('*'), como se muestra a continuación:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
CarlosIribarren/Ejemplos-Examples
|
Net/00_DLL/BEZarenKalkulua/BEZarenKalkulua/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,274
|
' 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.VisualBasic.ImplementAbstractClass
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass
Partial Public Class ImplementAbstractClassTests
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInDocument() As Task
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class {|FixAllInDocument:B1|}
Inherits A1
Implements I1
Private Class C1
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Private Class C2
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Private Class C2
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, ignoreTrivia:=False, fixAllActionEquivalenceKey:=fixAllActionId)
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInProject() As Task
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class {|FixAllInProject:B1|}
Inherits A1
Implements I1
Private Class C1
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Private Class C2
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, ignoreTrivia:=False, fixAllActionEquivalenceKey:=fixAllActionId)
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution() As Task
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class {|FixAllInSolution:B1|}
Inherits A1
Implements I1
Private Class C1
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Private Class C2
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<ProjectReference>Assembly1</ProjectReference>
<Document><![CDATA[
Class B3
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C3
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, ignoreTrivia:=False, fixAllActionEquivalenceKey:=fixAllActionId)
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)>
<Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)>
Public Async Function TestFixAllInSolution_DifferentAssemblyWithSameTypeName() As Task
Dim fixAllActionId = VisualBasicImplementAbstractClassCodeFixProvider.GetCodeActionId("Assembly1", "Global.A1")
Dim input = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class {|FixAllInSolution:B1|}
Inherits A1
Implements I1
Private Class C1
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Private Class C2
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Dim expected = <Workspace>
<Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C1
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
<Document><![CDATA[
Class B2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
Private Class C2
Inherits A1
Implements I1
Public Overrides Sub F1()
Throw New NotImplementedException()
End Sub
End Class
End Class]]>
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true">
<Document><![CDATA[
Public MustInherit Class A1
Public MustOverride Sub F1()
End Class
Public Interface I1
Sub F2()
End Interface
Class B3
Inherits A1
Implements I1
Private Class C3
Inherits A1
Implements I1
End Class
End Class]]>
</Document>
</Project>
</Workspace>.ToString()
Await TestInRegularAndScriptAsync(input, expected, ignoreTrivia:=False, fixAllActionEquivalenceKey:=fixAllActionId)
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb
|
Visual Basic
|
apache-2.0
| 14,476
|
' ******************************************************************************
' **
' ** Yahoo! Managed
' ** Written by Marius Häusler 2011
' ** It would be pleasant, if you contact me when you are using this code.
' ** Contact: YahooFinanceManaged@gmail.com
' ** Project Home: http://code.google.com/p/yahoo-finance-managed/
' **
' ******************************************************************************
' **
' ** Copyright 2011 Marius Häusler
' **
' ** 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.
' **
' ******************************************************************************
Namespace YahooManaged.Finance
''' <summary>
''' Stores informations of an industry
''' </summary>
''' <remarks></remarks>
Public Class IndustryData
''' <summary>
''' The name of the industry
''' </summary>
''' <value></value>
''' <returns>The name of the industry</returns>
''' <remarks></remarks>
Public Property Name() As String
''' <summary>
''' The Yahoo ID of the industry
''' </summary>
''' <value></value>
''' <returns>An ID string</returns>
''' <remarks></remarks>
Public Property ID() As Industry
''' <summary>
''' The companies of the industry
''' </summary>
''' <value></value>
''' <returns>A list of companies</returns>
''' <remarks></remarks>
Public Property Companies() As List(Of CompanyInfoData)
Public Sub New()
Me.Companies = New List(Of CompanyInfoData)
End Sub
Public Shared Function GetIndustryName(ByVal ind As Industry) As String
Select Case ind
Case Industry.Agricultural_Chemicals : Return "Agricultural Chemicals"
Case Industry.Aluminum : Return "Aluminum"
Case Industry.Chemicals_Major_Diversified : Return "Chemicals - Major Diversified"
Case Industry.Copper : Return "Copper"
Case Industry.Gold : Return "Gold"
Case Industry.Independent_Oil_And_Gas : Return "Independent Oil & Gas"
Case Industry.Industrial_Metals_And_Minerals : Return "Industrial Metals & Minerals"
Case Industry.Major_Integrated_Oil_And_Gas : Return "Major Integrated Oil & Gas"
Case Industry.Nonmetallic_Mineral_Mining : Return "Nonmetallic Mineral Mining"
Case Industry.Oil_And_Gas_Drilling_And_Exploration : Return "Oil & Gas Drilling & Exploration"
Case Industry.Oil_And_Gas_Equipment_And_Services : Return "Oil & Gas Equipment & Services"
Case Industry.Oil_And_Gas_Pipelines : Return "Oil & Gas Pipelines"
Case Industry.Oil_And_Gas_Refining_And_Marketing : Return "Oil & Gas Refining & Marketing"
Case Industry.Silver : Return "Silver"
Case Industry.Specialty_Chemicals : Return "Specialty Chemicals"
Case Industry.Steel_And_Iron : Return "Steel & Iron"
Case Industry.Synthetics : Return "Synthetics"
Case Industry.Conglomerates : Return "Conglomerates"
Case Industry.Appliances : Return "Appliances"
Case Industry.Auto_Manufacturers_Major : Return "Auto Manufacturers - Major"
Case Industry.Auto_Parts : Return "Auto Parts"
Case Industry.Beverages_Brewers : Return "Beverages - Brewers"
Case Industry.Beverages_Soft_Drinks : Return "Beverages - Soft Drinks"
Case Industry.Beverages_Wineries_And_Distillers : Return "Beverages - Wineries & Distillers"
Case Industry.Business_Equipment : Return "Business Equipment"
Case Industry.Cigarettes : Return "Cigarettes"
Case Industry.Cleaning_Products : Return "Cleaning Products"
Case Industry.Confectioners : Return "Confectioners"
Case Industry.Dairy_Products : Return "Dairy Products"
Case Industry.Electronic_Equipment : Return "Electronic Equipment"
Case Industry.Farm_Products : Return "Farm Products"
Case Industry.Food_Major_Diversified : Return "Food - Major Diversified"
Case Industry.Home_Furnishings_And_Fixtures : Return "Home Furnishings & Fixtures"
Case Industry.Housewares_And_Accessories : Return "Housewares & Accessories"
Case Industry.Meat_Products : Return "Meat Products"
Case Industry.Office_Supplies : Return "Office Supplies"
Case Industry.Packaging_And_Containers : Return "Packaging & Containers"
Case Industry.Paper_And_Paper_Products : Return "Paper & Paper Products"
Case Industry.Personal_Products : Return "Personal Products"
Case Industry.Photographic_Equipment_And_Supplies : Return "Photographic Equipment & Supplies"
Case Industry.Processed_And_Packaged_Goods : Return "Processed & Packaged Goods"
Case Industry.Recreational_Goods_Other : Return "Recreational Goods, Other"
Case Industry.Recreational_Vehicles : Return "Recreational Vehicles"
Case Industry.Rubber_And_Plastics : Return "Rubber & Plastics"
Case Industry.Sporting_Goods : Return "Sporting Goods"
Case Industry.Textile_Apparel_Clothing : Return "Textile - Apparel Clothing"
Case Industry.Textile_Apparel_Footwear_And_Accessories : Return "Textile - Apparel Footwear & Accessories"
Case Industry.Tobacco_Products_Other : Return "Tobacco Products, Other"
Case Industry.Toys_And_Games : Return "Toys & Games"
Case Industry.Trucks_And_Other_Vehicles : Return "Trucks & Other Vehicles"
Case Industry.Accident_And_Health_Insurance : Return "Accident & Health Insurance"
Case Industry.Asset_Management : Return "Asset Management"
Case Industry.Closed_End_Fund_Debt : Return "Closed-End Fund - Debt"
Case Industry.Closed_End_Fund_Equity : Return "Closed-End Fund - Equity"
Case Industry.Closed_End_Fund_Foreign : Return "Closed-End Fund - Foreign"
Case Industry.Credit_Services : Return "Credit Services"
Case Industry.Diversified_Investments : Return "Diversified Investments"
Case Industry.Foreign_Money_Center_Banks : Return "Foreign Money Center Banks"
Case Industry.Foreign_Regional_Banks : Return "Foreign Regional Banks"
Case Industry.Insurance_Brokers : Return "Insurance Brokers"
Case Industry.Investment_Brokerage_National : Return "Investment Brokerage - National"
Case Industry.Investment_Brokerage_Regional : Return "Investment Brokerage - Regional"
Case Industry.Life_Insurance : Return "Life Insurance"
Case Industry.Money_Center_Banks : Return "Money Center Banks"
Case Industry.Mortgage_Investment : Return "Mortgage Investment"
Case Industry.Property_And_Casualty_Insurance : Return "Property & Casualty Insurance"
Case Industry.Property_Management : Return "Property Management"
Case Industry.REIT_Diversified : Return "REIT - Diversified"
Case Industry.REIT_Healthcare_Facilities : Return "REIT - Healthcare Facilities"
Case Industry.REIT_Hotel_Motel : Return "REIT - Hotel/Motel"
Case Industry.REIT_Industrial : Return "REIT - Industrial"
Case Industry.REIT_Office : Return "REIT - Office"
Case Industry.REIT_Residential : Return "REIT - Residential"
Case Industry.REIT_Retail : Return "REIT - Retail"
Case Industry.Real_Estate_Development : Return "Real Estate Development"
Case Industry.Regional_Mid_Atlantic_Banks : Return "Regional - Mid-Atlantic Banks"
Case Industry.Regional_Midwest_Banks : Return "Regional - Midwest Banks"
Case Industry.Regional_Northeast_Banks : Return "Regional - Northeast Banks"
Case Industry.Regional_Pacific_Banks : Return "Regional - Pacific Banks"
Case Industry.Regional_Southeast_Banks : Return "Regional - Southeast Banks"
Case Industry.Regional_Southwest_Banks : Return "Regional - Southwest Banks"
Case Industry.Savings_And_Loans : Return "Savings & Loans"
Case Industry.Surety_And_Title_Insurance : Return "Surety & Title Insurance"
Case Industry.Biotechnology : Return "Biotechnology"
Case Industry.Diagnostic_Substances : Return "Diagnostic Substances"
Case Industry.Drug_Delivery : Return "Drug Delivery"
Case Industry.Drug_Manufacturers_Major : Return "Drug Manufacturers - Major"
Case Industry.Drug_Manufacturers_Other : Return "Drug Manufacturers - Other"
Case Industry.Drug_Related_Products : Return "Drug Related Products"
Case Industry.Drugs_Generic : Return "Drugs - Generic"
Case Industry.Health_Care_Plans : Return "Health Care Plans"
Case Industry.Home_Health_Care : Return "Home Health Care"
Case Industry.Hospitals : Return "Hospitals"
Case Industry.Long_Term_Care_Facilities : Return "Long-Term Care Facilities"
Case Industry.Medical_Appliances_And_Equipment : Return "Medical Appliances & Equipment"
Case Industry.Medical_Instruments_And_Supplies : Return "Medical Instruments & Supplies"
Case Industry.Medical_Laboratories_And_Research : Return "Medical Laboratories & Research"
Case Industry.Medical_Practitioners : Return "Medical Practitioners"
Case Industry.Specialized_Health_Services : Return "Specialized Health Services"
Case Industry.Aerospace_Defense_Major_Diversified : Return "Aerospace/Defense - Major Diversified"
Case Industry.Aerospace_Defense_Products_And_Services : Return "Aerospace/Defense Products & Services"
Case Industry.Cement : Return "Cement"
Case Industry.Diversified_Machinery : Return "Diversified Machinery"
Case Industry.Farm_And_Construction_Machinery : Return "Farm & Construction Machinery"
Case Industry.General_Building_Materials : Return "General Building Materials"
Case Industry.General_Contractors : Return "General Contractors"
Case Industry.Heavy_Construction : Return "Heavy Construction"
Case Industry.Industrial_Electrical_Equipment : Return "Industrial Electrical Equipment"
Case Industry.Industrial_Equipment_And_Components : Return "Industrial Equipment & Components"
Case Industry.Lumber_Wood_Production : Return "Lumber, Wood Production"
Case Industry.Machine_Tools_And_Accessories : Return "Machine Tools & Accessories"
Case Industry.Manufactured_Housing : Return "Manufactured Housing"
Case Industry.Metal_Fabrication : Return "Metal Fabrication"
Case Industry.Pollution_And_Treatment_Controls : Return "Pollution & Treatment Controls"
Case Industry.Residential_Construction : Return "Residential Construction"
Case Industry.Small_Tools_And_Accessories : Return "Small Tools & Accessories"
Case Industry.Textile_Industrial : Return "Textile Industrial"
Case Industry.Waste_Management : Return "Waste Management"
Case Industry.Advertising_Agencies : Return "Advertising Agencies"
Case Industry.Air_Delivery_And_Freight_Services : Return "Air Delivery & Freight Services"
Case Industry.Air_Services_Other : Return "Air Services, Other"
Case Industry.Apparel_Stores : Return "Apparel Stores"
Case Industry.Auto_Dealerships : Return "Auto Dealerships"
Case Industry.Auto_Parts_Stores : Return "Auto Parts Stores"
Case Industry.Auto_Parts_Wholesale : Return "Auto Parts Wholesale"
Case Industry.Basic_Materials_Wholesale : Return "Basic Materials Wholesale"
Case Industry.Broadcasting_Radio : Return "Broadcasting - Radio"
Case Industry.Broadcasting_TV : Return "Broadcasting - TV"
Case Industry.Building_Materials_Wholesale : Return "Building Materials Wholesale"
Case Industry.Business_Services : Return "Business Services"
Case Industry.CATV_Systems : Return "CATV Systems"
Case Industry.Catalog_And_Mail_Order_Houses : Return "Catalog & Mail Order Houses"
Case Industry.Computers_Wholesale : Return "Computers Wholesale"
Case Industry.Consumer_Services : Return "Consumer Services"
Case Industry.Department_Stores : Return "Department Stores"
Case Industry.Discount_Variety_Stores : Return "Discount, Variety Stores"
Case Industry.Drug_Stores : Return "Drug Stores"
Case Industry.Drugs_Wholesale : Return "Drugs Wholesale"
Case Industry.Education_And_Training_Services : Return "Education & Training Services"
Case Industry.Electronics_Stores : Return "Electronics Stores"
Case Industry.Electronics_Wholesale : Return "Electronics Wholesale"
Case Industry.Entertainment_Diversified : Return "Entertainment - Diversified"
Case Industry.Food_Wholesale : Return "Food Wholesale"
Case Industry.Gaming_Activities : Return "Gaming Activities"
Case Industry.General_Entertainment : Return "General Entertainment"
Case Industry.Grocery_Stores : Return "Grocery Stores"
Case Industry.Home_Furnishing_Stores : Return "Home Furnishing Stores"
Case Industry.Home_Improvement_Stores : Return "Home Improvement Stores"
Case Industry.Industrial_Equipment_Wholesale : Return "Industrial Equipment Wholesale"
Case Industry.Jewelry_Stores : Return "Jewelry Stores"
Case Industry.Lodging : Return "Lodging"
Case Industry.Major_Airlines : Return "Major Airlines"
Case Industry.Management_Services : Return "Management Services"
Case Industry.Marketing_Services : Return "Marketing Services"
Case Industry.Medical_Equipment_Wholesale : Return "Medical Equipment Wholesale"
Case Industry.Movie_Production_Theaters : Return "Movie Production, Theaters"
Case Industry.Music_And_Video_Stores : Return "Music & Video Stores"
Case Industry.Personal_Services : Return "Personal Services"
Case Industry.Publishing_Books : Return "Publishing - Books"
Case Industry.Publishing_Newspapers : Return "Publishing - Newspapers"
Case Industry.Publishing_Periodicals : Return "Publishing - Periodicals"
Case Industry.Railroads : Return "Railroads"
Case Industry.Regional_Airlines : Return "Regional Airlines"
Case Industry.Rental_And_Leasing_Services : Return "Rental & Leasing Services"
Case Industry.Research_Services : Return "Research Services"
Case Industry.Resorts_And_Casinos : Return "Resorts & Casinos"
Case Industry.Restaurants : Return "Restaurants"
Case Industry.Security_And_Protection_Services : Return "Security & Protection Services"
Case Industry.Shipping : Return "Shipping"
Case Industry.Specialty_Eateries : Return "Specialty Eateries"
Case Industry.Specialty_Retail_Other : Return "Specialty Retail, Other"
Case Industry.Sporting_Activities : Return "Sporting Activities"
Case Industry.Sporting_Goods_Stores : Return "Sporting Goods Stores"
Case Industry.Staffing_And_Outsourcing_Services : Return "Staffing & Outsourcing Services"
Case Industry.Technical_Services : Return "Technical Services"
Case Industry.Toy_And_Hobby_Stores : Return "Toy & Hobby Stores"
Case Industry.Trucking : Return "Trucking"
Case Industry.Wholesale_Other : Return "Wholesale, Other"
Case Industry.Application_Software : Return "Application Software"
Case Industry.Business_Software_And_Services : Return "Business Software & Services"
Case Industry.Communication_Equipment : Return "Communication Equipment"
Case Industry.Computer_Based_Systems : Return "Computer Based Systems"
Case Industry.Computer_Peripherals : Return "Computer Peripherals"
Case Industry.Data_Storage_Devices : Return "Data Storage Devices"
Case Industry.Diversified_Communication_Services : Return "Diversified Communication Services"
Case Industry.Diversified_Computer_Systems : Return "Diversified Computer Systems"
Case Industry.Diversified_Electronics : Return "Diversified Electronics"
Case Industry.Healthcare_Information_Services : Return "Healthcare Information Services"
Case Industry.Information_And_Delivery_Services : Return "Information & Delivery Services"
Case Industry.Information_Technology_Services : Return "Information Technology Services"
Case Industry.Internet_Information_Providers : Return "Internet Information Providers"
Case Industry.Internet_Service_Providers : Return "Internet Service Providers"
Case Industry.Internet_Software_And_Services : Return "Internet Software & Services"
Case Industry.Long_Distance_Carriers : Return "Long Distance Carriers"
Case Industry.Multimedia_And_Graphics_Software : Return "Multimedia & Graphics Software"
Case Industry.Networking_And_Communication_Devices : Return "Networking & Communication Devices"
Case Industry.Personal_Computers : Return "Personal Computers"
Case Industry.Printed_Circuit_Boards : Return "Printed Circuit Boards"
Case Industry.Processing_Systems_And_Products : Return "Processing Systems & Products"
Case Industry.Scientific_And_Technical_Instruments : Return "Scientific & Technical Instruments"
Case Industry.Security_Software_And_Services : Return "Security Software & Services"
Case Industry.Semiconductor_Broad_Line : Return "Semiconductor - Broad Line"
Case Industry.Semiconductor_Integrated_Circuits : Return "Semiconductor - Integrated Circuits"
Case Industry.Semiconductor_Specialized : Return "Semiconductor - Specialized"
Case Industry.Semiconductor_Equipment_And_Materials : Return "Semiconductor Equipment & Materials"
Case Industry.Semiconductor_Memory_Chips : Return "Semiconductor- Memory Chips"
Case Industry.Technical_And_System_Software : Return "Technical & System Software"
Case Industry.Telecom_Services_Domestic : Return "Telecom Services - Domestic"
Case Industry.Telecom_Services_Foreign : Return "Telecom Services - Foreign"
Case Industry.Wireless_Communications : Return "Wireless Communications"
Case Industry.Diversified_Utilities : Return "Diversified Utilities"
Case Industry.Electric_Utilities : Return "Electric Utilities"
Case Industry.Foreign_Utilities : Return "Foreign Utilities"
Case Industry.Gas_Utilities : Return "Gas Utilities"
Case Industry.Water_Utilities : Return "Water Utilities"
Case Else : Return "N/A"
End Select
End Function
End Class
End Namespace
|
agassan/YahooManaged
|
MaasOne.YahooManaged/YahooManaged/Finance/IndustryData.vb
|
Visual Basic
|
apache-2.0
| 20,868
|
Imports System.Diagnostics
Imports System.Windows.Forms
Public Class Explorer1
Private Sub Explorer1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Set up the UI
SetUpListViewColumns()
LoadTree()
End Sub
Private Sub LoadTree()
' TODO: Add code to add items to the treeview
Dim tvRoot As TreeNode
Dim tvNode As TreeNode
tvRoot = Me.TreeView.Nodes.Add("Root")
tvNode = tvRoot.Nodes.Add("TreeItem1")
tvNode = tvRoot.Nodes.Add("TreeItem2")
tvNode = tvRoot.Nodes.Add("TreeItem3")
End Sub
Private Sub LoadListView()
' TODO: Add code to add items to the listview based on the selected item in the treeview
Dim lvItem As ListViewItem
ListView.Items.Clear()
lvItem = ListView.Items.Add("ListViewItem1")
lvItem.ImageKey = "Graph1"
lvItem.SubItems.AddRange(New String() {"Column2", "Column3"})
lvItem = ListView.Items.Add("ListViewItem2")
lvItem.ImageKey = "Graph2"
lvItem.SubItems.AddRange(New String() {"Column2", "Column3"})
lvItem = ListView.Items.Add("ListViewItem3")
lvItem.ImageKey = "Graph3"
lvItem.SubItems.AddRange(New String() {"Column2", "Column3"})
End Sub
Private Sub SetUpListViewColumns()
' TODO: Add code to set up listview columns
Dim lvColumnHeader As ColumnHeader
' Setting Column widths applies only to the current view, so this line
' explicitly sets the ListView to be showing the SmallIcon view
' before setting the column width
SetView(View.SmallIcon)
lvColumnHeader = ListView.Columns.Add("Column1")
' Set the SmallIcon view column width large enough so that the items
' do not overlap
' Note that the second and third column do not appear in SmallIcon
' view, so there is no need to set those while in SmallIcon view
lvColumnHeader.Width = 90
' Change the view to Details and set up the appropriate column
' widths for the Details view differently than SmallIcon view
SetView(View.Details)
' The first column needs to be slightly larger in Details view than it
' was for SmallIcon view, and Column2 and Column3 need explicit sizes
' set for Details view
lvColumnHeader.Width = 100
lvColumnHeader = ListView.Columns.Add("Column2")
lvColumnHeader.Width = 70
lvColumnHeader = ListView.Columns.Add("Column3")
lvColumnHeader.Width = 70
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Close this form
Me.Close()
End Sub
Private Sub ToolBarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolBarToolStripMenuItem.Click
'Toggle the visibility of the toolstrip and also the checked state of the associated menu item
ToolBarToolStripMenuItem.Checked = Not ToolBarToolStripMenuItem.Checked
ToolStrip.Visible = ToolBarToolStripMenuItem.Checked
End Sub
Private Sub StatusBarToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StatusBarToolStripMenuItem.Click
'Toggle the visibility of the statusstrip and also the checked state of the associated menu item
StatusBarToolStripMenuItem.Checked = Not StatusBarToolStripMenuItem.Checked
StatusStrip.Visible = StatusBarToolStripMenuItem.Checked
End Sub
'Change whether or not the folders pane is visible
Private Sub ToggleFoldersVisible()
'First toggle the checked state of the associated menu item
FoldersToolStripMenuItem.Checked = Not FoldersToolStripMenuItem.Checked
'Change the Folders toolbar button to be in sync
FoldersToolStripButton.Checked = FoldersToolStripMenuItem.Checked
' Collapse the Panel containing the TreeView.
Me.SplitContainer.Panel1Collapsed = Not FoldersToolStripMenuItem.Checked
End Sub
Private Sub FoldersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FoldersToolStripMenuItem.Click
ToggleFoldersVisible()
End Sub
Private Sub FoldersToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FoldersToolStripButton.Click
ToggleFoldersVisible()
End Sub
Private Sub SetView(ByVal View As System.Windows.Forms.View)
'Figure out which menu item should be checked
Dim MenuItemToCheck As ToolStripMenuItem = Nothing
Select Case View
Case View.Details
MenuItemToCheck = DetailsToolStripMenuItem
Case View.LargeIcon
MenuItemToCheck = LargeIconsToolStripMenuItem
Case View.List
MenuItemToCheck = ListToolStripMenuItem
Case View.SmallIcon
MenuItemToCheck = SmallIconsToolStripMenuItem
Case View.Tile
MenuItemToCheck = TileToolStripMenuItem
Case Else
Debug.Fail("Unexpected View")
View = View.Details
MenuItemToCheck = DetailsToolStripMenuItem
End Select
'Check the appropriate menu item and deselect all others under the Views menu
For Each MenuItem As ToolStripMenuItem In ListViewToolStripButton.DropDownItems
If MenuItem Is MenuItemToCheck Then
MenuItem.Checked = True
Else
MenuItem.Checked = False
End If
Next
'Finally, set the view requested
ListView.View = View
End Sub
Private Sub ListToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListToolStripMenuItem.Click
SetView(View.List)
End Sub
Private Sub DetailsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DetailsToolStripMenuItem.Click
SetView(View.Details)
End Sub
Private Sub LargeIconsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LargeIconsToolStripMenuItem.Click
SetView(View.LargeIcon)
End Sub
Private Sub SmallIconsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SmallIconsToolStripMenuItem.Click
SetView(View.SmallIcon)
End Sub
Private Sub TileToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TileToolStripMenuItem.Click
SetView(View.Tile)
End Sub
Private Sub OpenToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
Dim OpenFileDialog As New OpenFileDialog
OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
OpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
OpenFileDialog.ShowDialog(Me)
Dim FileName As String = OpenFileDialog.FileName
' TODO: Add code to open the file
End Sub
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim SaveFileDialog As New SaveFileDialog
SaveFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
SaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
SaveFileDialog.ShowDialog(Me)
Dim FileName As String = SaveFileDialog.FileName
' TODO: Add code here to save the current contents of the form to a file.
End Sub
Private Sub TreeView_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView.AfterSelect
' TODO: Add code to change the listview contents based on the currently-selected node of the treeview
LoadListView()
End Sub
End Class
|
WhiteHingeLtd/SurfacePicker
|
SurfacePicker/Explorer1.vb
|
Visual Basic
|
mit
| 8,039
|
Imports System
Imports System.Data
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Data.SqlClient
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here
'---------------------------------------------------------------------------------------
Namespace SimpleTalk.Phil.Factor
Public Class RegularExpressionFunctions
'
' RegExOptions function
'this is used simply to creat the bitmap that is passed to the various
'CLR routines
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExOptionEnumeration(ByVal IgnoreCase As SqlBoolean, _
ByVal MultiLine As SqlBoolean, _
ByVal ExplicitCapture As SqlBoolean, _
ByVal Compiled As SqlBoolean, _
ByVal SingleLine As SqlBoolean, _
ByVal IgnorePatternWhitespace As SqlBoolean, _
ByVal RightToLeft As SqlBoolean, _
ByVal ECMAScript As SqlBoolean, _
ByVal CultureInvariant As SqlBoolean) _
As SqlInt32
Dim Result As Integer
Result = (IIf(IgnoreCase.Value, RegexOptions.IgnoreCase, RegexOptions.None) Or _
IIf(MultiLine.Value, RegexOptions.Multiline, RegexOptions.None) Or _
IIf(ExplicitCapture.Value, RegexOptions.ExplicitCapture, _
RegexOptions.None) Or _
IIf(Compiled.Value, RegexOptions.Compiled, RegexOptions.None) Or _
IIf(SingleLine.Value, RegexOptions.Singleline, RegexOptions.None) Or _
IIf(IgnorePatternWhitespace.Value, RegexOptions.IgnorePatternWhitespace, _
RegexOptions.None) Or _
IIf(RightToLeft.Value, RegexOptions.RightToLeft, RegexOptions.None) Or _
IIf(ECMAScript.Value, RegexOptions.ECMAScript, RegexOptions.None) Or _
IIf(CultureInvariant.Value, RegexOptions.CultureInvariant, RegexOptions.None))
Return (Result)
End Function
'----------end of RegExEnumeration function
'
' RegExMatch function
'This method returns the first substring found in input that matches the
'regular expression pattern.
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExMatch(ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32 _
) As SqlString
If (input.IsNull OrElse pattern.IsNull) Then
Return String.Empty
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return Regex.Match(input.Value, pattern.Value, RegexOption).Value
End Function
'----------end of RegExMatch function
'end RegexOptions
'RegExIsMatch function
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExIsMatch( _
ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) As SqlBoolean
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlBoolean.False
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return Regex.IsMatch(input.Value, pattern.Value, RegexOption)
End Function '
' RegExIndex function
'This method returns the index of the first substring found in input that
'matches the regular expression pattern.
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExIndex(ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32 _
) As SqlInt32
If (input.IsNull OrElse pattern.IsNull) Then
Return 0
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return Regex.Match(input.Value, pattern.Value, RegexOption).Index
End Function
'----------end of RegExMatch function
' RegExEscape function
'This method 'escapes' a minimal set of characters (\, *, +, ?, |, {, [, (,),
'^,$,., #, and white space) by replacing them with their escape codes. This
'instructs the regular expression engine to interpret these characters
'literally rather than as metacharacters so you can pass any atring into
'the pattern harmlessly.
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExEscape(ByVal input As SqlString) As SqlString
If (input.IsNull) Then
Return String.Empty
End If
Return Regex.Escape(input.Value)
End Function
'----------end of RegEscape function
'
' RegExSplit function
'RegexSplit function Splits an input string into an array of substrings at the
'positions defined by a regular expression match.
'This method splits the string at a delimiter determined by a regular
'expression. The string is split as many times as possible. If no delimiter
'is found, the return value contains one element whose value is the original
'input parameter string.
<SqlFunction(DataAccess:=DataAccessKind.None, IsDeterministic:=True, _
IsPrecise:=True, Name:="RegExSplit", _
SystemDataAccess:=SystemDataAccessKind.None, _
FillRowMethodName:="NextSplitRow")> _
Public Shared Function RegExSplit( _
ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) _
As IEnumerable
If (input.IsNull OrElse pattern.IsNull) Then
Return Nothing
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return Regex.Split(input.Value, pattern.Value, RegexOption)
End Function
Private Shared Sub NextSplitRow(ByVal input As Object, _
<Out()> ByRef match As SqlString)
match = New SqlString(CStr(input))
End Sub
'----------end of RegexSplit function
'
' RegExReplace function
'SQL Server version with parameters like TSQL: REPLACE
'Within a specified input string, replaces all strings that match a specified
'regular expression with a specified replacement string. Specified options
'modify the matching operation.
'this works like the SQL 'Replace' function on steroids.
<SqlFunction(DataAccess:=DataAccessKind.None, IsDeterministic:=True, _
IsPrecise:=True, Name:="RegExReplace", _
SystemDataAccess:=SystemDataAccessKind.None)> _
Public Shared Function RegExReplace(ByVal input As SqlString, _
ByVal pattern As SqlString, _
ByVal replacement As SqlString) _
As SqlString
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlString.Null
End If
Return New SqlString(Regex.Replace(input.Value, pattern.Value, _
replacement.Value, RegexOptions.IgnoreCase Or RegexOptions.Multiline))
End Function
'----------end of RegexReplace function
'
' RegExReplacex function
'Logical version of the Regex Replace with parameters like the others
'Within a specified input string, replaces all strings that match a specified
'regular expression with a specified replacement string. Specified options
'modify the matching operation.
<SqlFunction(DataAccess:=DataAccessKind.None, IsDeterministic:=True, _
IsPrecise:=True, Name:="RegExReplacex", _
SystemDataAccess:=SystemDataAccessKind.None)> _
Public Shared Function RegExReplacex(ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal replacement As SqlString, _
ByVal Options As SqlInt32) _
As SqlString
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlString.Null
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return New SqlString(Regex.Replace(input.Value, pattern.Value, _
replacement.Value, RegexOption))
End Function
'----------end of RegexReplace function
'
' RegExMatches function
'Searches the specified input string for all occurrences of the regular
'expression supplied in a pattern parameter with matching options supplied
'in an options parameter.
<SqlFunction(DataAccess:=DataAccessKind.None, IsDeterministic:=True, _
IsPrecise:=True, Name:="RegExMatches", _
SystemDataAccess:=SystemDataAccessKind.None, _
FillRowMethodName:="NextMatchedRow")> _
Public Shared Function RegExMatches(ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) _
As IEnumerable
If (input.IsNull OrElse pattern.IsNull) Then
Return Nothing
End If
Dim RegexOption As New System.Text.RegularExpressions.RegexOptions
RegexOption = Options
Return Regex.Matches(input.Value, pattern.Value, RegexOption)
End Function
Private Shared Sub NextMatchedRow(ByVal input As Object, _
<Out()> ByRef match As SqlString, _
<Out()> ByRef matchIndex As SqlInt32, _
<Out()> ByRef matchLength As SqlInt32)
Dim match2 As Match = DirectCast(input, Match)
match = New SqlString(match2.Value)
matchIndex = New SqlInt32(match2.Index)
matchLength = New SqlInt32(match2.Length)
End Sub
End Class
End Namespace
|
ktaranov/sqlserver-kit
|
CLR/Regex/Fill_Factor/RegexSQLCLR.vb
|
Visual Basic
|
mit
| 11,147
|
' 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.Test.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class GotoTests
Inherits BasicTestBase
<WorkItem(543106, "DevDiv")>
<Fact()>
Public Sub BranchOutOfFinallyInLambda()
Dim compilation = CreateCompilationWithMscorlibAndReferences(
<compilation name="BranchOutOfFinallyInLambda">
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Class C1
shared Sub MAIN()
Dim lists = foo()
lists.Where(Function(ByVal item)
lab1:
Try
Catch ex As Exception
GoTo lab1
Finally
GoTo lab1
End Try
Return item.ToString() = String.Empty
End Function).ToList()
End Sub
Shared Function foo() As List(Of Integer)
Return Nothing
End Function
End Class
</file>
</compilation>, {SystemCoreRef})
AssertTheseDiagnostics(compilation,
<expected>
BC30101: Branching out of a 'Finally' is not valid.
GoTo lab1
~~~~
</expected>)
End Sub
<WorkItem(543392, "DevDiv")>
<Fact()>
Public Sub BranchOutOfFinallyInLambda_1()
CreateCompilationWithMscorlibAndReferences(
<compilation name="BranchOutOfFinallyInLambda">
<file name="a.vb">
Imports System.Collections.Generic
Imports System.Linq
Module Module1
Sub Main()
Dim lists As New List(Of Integer)
lists.Where(Function(ByVal item) GoTo lab1)
End Sub
End Module
</file>
</compilation>, {MsvbRef, SystemCoreRef}).AssertTheseDiagnostics(<expected>
BC30518: Overload resolution failed because no accessible 'Where' can be called with these arguments:
lists.Where(Function(ByVal item) GoTo lab1)
~~~~~
BC30201: Expression expected.
lists.Where(Function(ByVal item) GoTo lab1)
~
</expected>)
End Sub
<Fact()>
Public Sub NakedGoto()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="NakedGoto">
<file name="a.vb">
Module M
Sub Main()
GoTo
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""))
End Sub
<Fact()>
Public Sub GotoInvalidLabel()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoInvalidLabel">
<file name="a.vb">
Module M
Sub Main()
GoTo 1+2
3: GoTo Return
1: GoTo If(True,1, 2)
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedEOS, "+"),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_ExpectedIdentifier, ""),
Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""),
Diagnostic(ERRID.ERR_LabelNotDefined1, "").WithArguments(""))
End Sub
<Fact()>
Public Sub GotoOutOfMethod()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoOutOfMethod">
<file name="a.vb">
Structure struct
GoTo Labl
Const x = 1
Lab1:
Const y = 2
End Structure
</file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "GoTo Labl"),
Diagnostic(ERRID.ERR_InvOutsideProc, "Lab1:"))
End Sub
<Fact()>
Public Sub GotoOutOfMethod_1()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoOutOfMethod">
<file name="a.vb">
Namespace ns1
goto Labl
const x = 1
Lab1:
const y = 2
End namespace
</file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "goto Labl"),
Diagnostic(ERRID.ERR_InvOutsideProc, "Lab1:"),
Diagnostic(ERRID.ERR_InvalidInNamespace, "const x = 1"),
Diagnostic(ERRID.ERR_InvalidInNamespace, "const y = 2"))
End Sub
<Fact()>
Public Sub GotoOutOfMethod_2()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoOutOfMethod">
<file name="a.vb">
goto Labl
Lab1:
</file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "goto Labl"),
Diagnostic(ERRID.ERR_InvOutsideProc, "Lab1:"))
End Sub
<Fact()>
Public Sub GotoMultiLabel()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoMultiLabel">
<file name="a.vb">
Module Program
Sub Main(args As String())
Dim i = 0
GoTo Lab2,Lab1
Lab1:
i = 1
Lab2:
i = 2
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedEOS, ","))
End Sub
<WorkItem(543364, "DevDiv")>
<Fact()>
Public Sub LabelAfterElse()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LabelAfterElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim Flag1 = 1
GoTo 100
If Flag1 = 1 Then
Flag1 = 100
Else 100: Flag1 = 200
End If
Console.Write(Flag1)
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "100"),
Diagnostic(ERRID.ERR_LabelNotDefined1, "100").WithArguments("100"))
End Sub
<Fact()>
Public Sub LabelAfterElse_1()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LabelAfterElse">
<file name="a.vb">
Imports System
Module M
Sub Main()
Dim Flag1 = 1
GoTo 100
If Flag1 = 1 Then
Flag1 = 100
Else :100: Flag1 = 200
End If
Console.Write(Flag1)
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "100"),
Diagnostic(ERRID.ERR_LabelNotDefined1, "100").WithArguments("100"))
End Sub
<WorkItem(543364, "DevDiv")>
<Fact()>
Public Sub LabelAfterElse_NotNumberic()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LabelAfterElse">
<file name="a.vb">
Module Program
Sub Main(args As String())
Dim x = 1
If (x = 1)
lab1:
Else lab2:
End If
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "lab2").WithArguments("lab2"))
End Sub
<Fact()>
Public Sub LabelBeforeFirstCase()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LabelBeforeFirstCase">
<file name="a.vb">
Module M
Sub Main()
Dim Fruit As String = "Apple"
Select Case Fruit
label1: Case "Banana"
Exit Select
Case "Chair"
Exit Select
End Select
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedCase, "label1:"))
End Sub
<Fact()>
Public Sub LabelInDifferentMethod()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="LabelInDifferentMethod">
<file name="a.vb">
Module M
Public Sub Main()
GoTo label1
End Sub
Public Sub foo()
label1:
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_LabelNotDefined1, "label1").WithArguments("label1"))
End Sub
<Fact()>
Public Sub GotoDeeperScope()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="GotoDeeperScope">
<file name="a.vb">
Module M
Public Sub Main()
For i = 0 To 10
Label:
Next
GoTo Label
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_GotoIntoFor, "Label").WithArguments("Label"))
End Sub
<Fact()>
Public Sub BranchOutFromLambda()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="BranchOutFromLambda">
<file name="a.vb">
Delegate Function del(i As Integer) As Integer
Module Program
Sub Main(args As String())
Dim q As del = Function(x)
GoTo label2
Return x * x
End Function
label2:
Return
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_LabelNotDefined1, "label2").WithArguments("label2"))
End Sub
<Fact()>
Public Sub SameLabelNameInDifferentLambda()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SameLabelNameInDifferentLambda">
<file name="a.vb">
Imports System
Delegate Function del(i As Integer) As Integer
Module Program
Sub Main(args As String())
Dim q As del = Function(x)
GoTo label1
label1:
Return x * x
End Function
Dim p As del = Function(x)
GoTo label1
label1:
Return x * x
End Function
End Sub
End Module
</file>
</compilation>).AssertNoDiagnostics()
End Sub
<Fact()>
Public Sub SameLabelNameInDifferentScop_Lambda()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="SameLabelNameInDifferentScop_Lambda">
<file name="a.vb">
Imports System
Delegate Function del(i As Integer) As Integer
Module Program
Sub Main(args As String())
Dim p As del = Function(x)
GoTo label1
label1:
Return x * x
End Function
label1:
Return
End Sub
End Module
</file>
</compilation>).AssertNoDiagnostics()
End Sub
<Fact()>
Public Sub IllegalLabels()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="IllegalLabels">
<file name="a.vb">
Module Program
Sub Main(args As String())
'COMPILEERROR: BC30801, "11"
11A:
'COMPILEERROR: BC30801, "12"
12B:
'COMPILEERROR: BC30801, "16", BC30035
16F:
'COMPILEERROR: BC30801, "17"
17G:
'COMPILEERROR: BC30801, "19", BC30035
19I:
'COMPILEERROR: BC30801, "21"
21J:
'COMPILEERROR: BC30801, "23", BC30035
23L:
'COMPILEERROR: BC30801, "24"
24M:
'COMPILEERROR: BC30801, "25"
25N:
'COMPILEERROR: BC30801, "26"
26O:
'COMPILEERROR: BC30801, "27"
27P:
'COMPILEERROR: BC30801, "31", BC30035
31S:
'COMPILEERROR: BC30801, "32"
32T:
'COMPILEERROR: BC30801, "33"
33U:
'COMPILEERROR: BC30801, "34"
34V:
'COMPILEERROR: BC30801, "35"
35W:
'COMPILEERROR: BC30801, "36"
36X:
'COMPILEERROR: BC30801, "37"
37Y:
'COMPILEERROR: BC30801, "38"
38Z:
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "11"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "12"),
Diagnostic(ERRID.ERR_Syntax, "16F"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "17"),
Diagnostic(ERRID.ERR_Syntax, "19I"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "21"),
Diagnostic(ERRID.ERR_Syntax, "23L"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "24"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "25"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "26"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "27"),
Diagnostic(ERRID.ERR_Syntax, "31S"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "32"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "33"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "34"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "35"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "36"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "37"),
Diagnostic(ERRID.ERR_ObsoleteLineNumbersAreLabels, "38"))
End Sub
<Fact()>
Public Sub IllegalLabels_1()
CreateCompilationWithMscorlibAndVBRuntime(
<compilation name="IllegalLabels">
<file name="a.vb">
Module Program
Sub Main(args As String())
'COMPILEERROR: BC30035, "14D"
14D:
'COMPILEERROR: BC30495, "15E"
15E:
'COMPILEERROR: BC30035, "16F"
16F:
'COMPILEERROR: BC30035, "19I"
19I:
'COMPILEERROR: BC30035, "23L"
23L:
'COMPILEERROR: BC30035, "29R"
29R:
'COMPILEERROR: BC30035, "31S"
31S:
End Sub
End Module
</file>
</compilation>).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "14D"),
Diagnostic(ERRID.ERR_InvalidLiteralExponent, "15E"),
Diagnostic(ERRID.ERR_Syntax, "16F"),
Diagnostic(ERRID.ERR_Syntax, "19I"),
Diagnostic(ERRID.ERR_Syntax, "23L"),
Diagnostic(ERRID.ERR_Syntax, "29R"),
Diagnostic(ERRID.ERR_Syntax, "31S"))
End Sub
End Class
End Namespace
|
stjeong/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Binding/GotoTests.vb
|
Visual Basic
|
apache-2.0
| 13,987
|
'------------------------------------------------------------------------------
' <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.UO_UniSelectList.My.MySettings
Get
Return Global.UO_UniSelectList.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
RocketSoftware/multivalue-lab
|
U2/Demos/U2-Toolkit/.NET Samples/samples/VB.NET/UniVerse/UO_UniSelectList/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,936
|
' 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 Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
Imports Roslyn.Test.PdbUtilities
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class LocalsTests
Inherits ExpressionCompilerTestBase
<Fact>
Public Sub NoLocals()
Const source =
"Class C
Shared Sub M()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.Equal(0, assembly.Count)
Assert.Equal(0, locals.Count)
locals.Free()
End Sub
<Fact>
Public Sub Locals()
Const source =
"Class C
Sub M(a As Integer())
Dim b As String
a(1) += 1
SyncLock New C()
#ExternalSource(""test"", 999)
Dim c As Integer = 3
b = a(c).ToString()
#End ExternalSource
End SyncLock
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "a", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "b", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "c", expectedILOpt:=
"{
// Code size 3 (0x3)
.maxstack 1
.locals init (String V_0, //b
Integer& V_1,
Object V_2,
Boolean V_3,
Integer V_4) //c
IL_0000: ldloc.s V_4
IL_0002: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub LocalsAndPseudoVariables()
Const source =
"Class C
Sub M(o As Object)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
"C.M")
Dim aliases = ImmutableArray.Create(
ExceptionAlias(GetType(System.IO.IOException)),
ReturnValueAlias(2, GetType(String)),
ReturnValueAlias(),
ObjectIdAlias(2, GetType(Boolean)),
VariableAlias("o", "C"))
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim diagnostics = DiagnosticBag.GetInstance()
Dim testData = New CompilationTestData()
context.CompileGetLocals(
locals,
argumentsOnly:=True,
aliases:=aliases,
diagnostics:=diagnostics,
typeName:=typeName,
testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o")
locals.Clear()
testData = New CompilationTestData()
context.CompileGetLocals(
locals,
argumentsOnly:=False,
aliases:=aliases,
diagnostics:=diagnostics,
typeName:=typeName,
testData:=testData)
Assert.Equal(7, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "$exception", "Error", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 11 (0xb)
.maxstack 1
IL_0000: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetException() As System.Exception""
IL_0005: castclass ""System.IO.IOException""
IL_000a: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "$ReturnValue2", "Method M2 returned", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldc.i4.2
IL_0001: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(Integer) As Object""
IL_0006: castclass ""String""
IL_000b: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "$ReturnValue", "Method M returned", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetReturnValue(Integer) As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "$2", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""$2""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: unbox.any ""Boolean""
IL_000f: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "o", expectedILOpt:=
"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""o""
IL_0005: call ""Function Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(String) As Object""
IL_000a: castclass ""C""
IL_000f: ret
}")
VerifyLocal(testData, typeName, locals(5), "<>m5", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(6), "<>m6", "o", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}")
locals.Free()
End Sub
''' <summary>
''' No local signature (debugging a .dmp with no heap). Local
''' names are known but types are not so the locals are dropped.
''' Expressions that do not involve locals can be evaluated however.
''' </summary>
<Fact>
Public Sub NoLocalSignature()
Const source =
"Class C
Sub M(a As Integer())
Dim b As String
a(1) += 1
SyncLock New C()
#ExternalSource(""test"", 999)
Dim c As Integer = 3
b = a(c).ToString()
#End ExternalSource
End SyncLock
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes), includeLocalSignatures:=False)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "a", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}")
locals.Free()
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("b", errorMessage, testData, DebuggerDiagnosticFormatter.Instance)
Assert.Equal(errorMessage, "error BC30451: 'b' is not declared. It may be inaccessible due to its protection level.")
testData = New CompilationTestData()
context.CompileExpression("a(1)", errorMessage, testData)
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 4 (0x4)
.maxstack 2
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: ldelem.i4
IL_0003: ret
}")
End Sub
<Fact>
Public Sub [Me]()
Const source = "
Class C
Sub M([Me] As Object)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}
")
' Dev11 shows "Me" in the Locals window and "[Me]" in the Autos window.
VerifyLocal(testData, typeName, locals(1), "<>m1", "[Me]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
")
locals.Free()
End Sub
<Fact>
Public Sub ArgumentsOnly()
Const source = "
Class C
Sub M(Of T)(x As T)
Dim y As Object = x
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=True, typeName:=typeName, testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0(Of T)", "x", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Object V_0) //y
IL_0000: ldarg.1
IL_0001: ret
}",
expectedGeneric:=True)
locals.Free()
End Sub
''' <summary>
''' Compiler-generated locals should be ignored.
''' </summary>
<Fact>
Public Sub CompilerGeneratedLocals()
Const source = "
Class C
Shared Function F(args As Object()) As Boolean
If args Is Nothing Then
Return True
End If
For Each o In args
#ExternalSource(""test"", 999)
System.Console.WriteLine() ' Force non-hidden sequence point
#End ExternalSource
Next
DirectCast(Function() args(0), System.Func(Of Object))()
Return False
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "args", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_args As Object()""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "o", expectedILOpt:=
"{
// Code size 3 (0x3)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
Boolean V_1, //F
Boolean V_2,
Object() V_3,
Integer V_4,
Object V_5, //o
Boolean V_6)
IL_0000: ldloc.s V_5
IL_0002: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub Constants()
Const source = "
Class C
Const x As Integer = 2
Shared Function F(w As Integer) As Integer
#ExternalSource(""test"", 888)
System.Console.WriteLine() ' Force non-hidden sequence point
#End ExternalSource
Const y As Integer = 3
Const v As Object = Nothing
If v Is Nothing orelse w < 2 Then
Const z As String = ""str""
#ExternalSource(""test"", 999)
Dim u As String = z
w += z.Length
#End ExternalSource
End If
Return w + x + y
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=888)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2)
IL_0000: ldc.i4.3
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "v", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2)
IL_0000: ldnull
IL_0001: ret
}
")
context = CreateMethodContext(
runtime,
methodName:="C.F",
atLineNumber:=999) ' Changed this (was Nothing)
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(6, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w")
VerifyLocal(testData, typeName, locals(1), "<>m1", "F")
VerifyLocal(testData, typeName, locals(2), "<>m2", "u")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
VerifyLocal(testData, typeName, locals(4), "<>m4", "v", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
VerifyLocal(testData, typeName, locals(5), "<>m5", "z", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Integer V_0, //F
Boolean V_1,
String V_2) //u
IL_0000: ldstr ""str""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ConstantEnum()
Const source =
"Enum E
A
B
End Enum
Class C
Shared Sub M(x As E)
Const y = E.B
End Sub
Shared Sub Main()
M(E.A)
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugExe)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
Dim method = DirectCast(testData.GetMethodData("<>x.<>m0").Method, MethodSymbol)
Assert.Equal(method.Parameters(0).Type, method.ReturnType)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}")
method = DirectCast(testData.GetMethodData("<>x.<>m1").Method, MethodSymbol)
Assert.Equal(method.Parameters(0).Type, method.ReturnType)
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ConstantEnumAndTypeParameter()
Const source =
"Class C(Of T)
Enum E
A
End Enum
Friend Shared Sub M(Of U As T)()
Const x As C(Of T).E = E.A
Const y As C(Of U).E = Nothing
End Sub
End Class
Class P
Shared Sub Main()
C(Of Object).M(Of String)()
End Sub
End Class"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugExe)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, "<>x(Of T)", locals(0), "<>m0(Of U)", "x", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(1), "<>m1(Of U)", "y", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(2), "<>m2(Of U)", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedGeneric:=True, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U)..ctor()""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub CapturedLocalsOutsideLambda()
Const source = "
Imports System
Class C
Shared Sub F(f As Func(Of Object))
End Sub
Sub M(x As C)
Dim y As New C()
F(Function() If(x, If(y, Me)))
If x IsNot Nothing
#ExternalSource(""test"", 999)
Dim z = 6
Dim w = 7
F(Function() If(y, DirectCast(w, Object)))
#End ExternalSource
End If
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(5, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_x As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "z", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.3
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "w", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Boolean V_1,
C._Closure$__2-1 V_2, //$VB$Closure_1
Integer V_3) //z
IL_0000: ldloc.2
IL_0001: ldfld ""C._Closure$__2-1.$VB$Local_w As Integer""
IL_0006: ret
}")
End Sub
<Fact>
Public Sub CapturedLocalsInsideLambda()
Const source = "
Imports System
Class C
Shared Sub F(ff As Func(Of Object, Object))
ff(Nothing)
End Sub
Sub M()
Dim x As New Object()
F(Function(_1)
Dim y As New Object()
F(Function(_2) y)
Return If(x, Me)
End Function)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__2-0._Lambda$__1")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 2)
VerifyLocal(testData, typeName, locals(0), "<>m0", "_2", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As Object""
IL_0006: ret
}")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__2-1._Lambda$__0")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 4)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-1.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "_1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__2-0.$VB$Local_y As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__2-0 V_0, //$VB$Closure_0
Object V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__2-1.$VB$Local_x As Object""
IL_0006: ret
}")
End Sub
<Fact>
Public Sub NestedLambdas()
Const source = "
Imports System
Class C
Shared Sub Main()
Dim f As Func(Of Object, Object, Object, Object, Func(Of Object, Object, Object, Func(Of Object, Object, Func(Of Object, Object)))) =
Function(x1, x2, x3, x4)
If x1 Is Nothing Then Return Nothing
Return Function(y1, y2, y3)
If If(y1, x2) Is Nothing Then Return Nothing
Return Function(z1, z2)
If If(z1, If(y2, x3)) Is Nothing Then Return Nothing
Return Function(w1)
If If(z2, If(y3, x4)) Is Nothing Then Return Nothing
Return w1
End Function
End Function
End Function
End Function
f(1, 2, 3, 4)(5, 6, 7)(8, 9)(10)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__._Lambda$__1-0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 4)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-0 V_0, //$VB$Closure_0
System.Func(Of Object, Object, Object, System.Func(Of Object, Object, System.Func(Of Object, Object))) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_x2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "x3")
VerifyLocal(testData, typeName, locals(2), "<>m2", "x4")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x1")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__1")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 6)
VerifyLocal(testData, typeName, locals(0), "<>m0", "y2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-1 V_0, //$VB$Closure_0
System.Func(Of Object, Object, System.Func(Of Object, Object)) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-1.$VB$Local_y2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y3")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y1")
VerifyLocal(testData, typeName, locals(3), "<>m3", "x2")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x3", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-1 V_0, //$VB$Closure_0
System.Func(Of Object, Object, System.Func(Of Object, Object)) V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_x3 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x4")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-1._Lambda$__2")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 7)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (C._Closure$__1-2 V_0, //$VB$Closure_0
System.Func(Of Object, Object) V_1,
Boolean V_2)
IL_0000: ldloc.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$Local_z2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "z1")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y2")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y3")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x2")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x3", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (C._Closure$__1-2 V_0, //$VB$Closure_0
System.Func(Of Object, Object) V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-1.$VB$NonLocal_$VB$Closure_2 As C._Closure$__1-0""
IL_0006: ldfld ""C._Closure$__1-0.$VB$Local_x3 As Object""
IL_000b: ret
}")
VerifyLocal(testData, typeName, locals(6), "<>m6", "x4")
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-2._Lambda$__3")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(locals.Count, 7)
VerifyLocal(testData, typeName, locals(0), "<>m0", "w1")
VerifyLocal(testData, typeName, locals(1), "<>m1", "z2", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0,
Boolean V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$Local_z2 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "y2")
VerifyLocal(testData, typeName, locals(3), "<>m3", "y3")
VerifyLocal(testData, typeName, locals(4), "<>m4", "x2")
VerifyLocal(testData, typeName, locals(5), "<>m5", "x3")
VerifyLocal(testData, typeName, locals(6), "<>m6", "x4", expectedILOpt:=
"{
// Code size 17 (0x11)
.maxstack 1
.locals init (Object V_0,
Boolean V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-2.$VB$NonLocal_$VB$Closure_3 As C._Closure$__1-1""
IL_0006: ldfld ""C._Closure$__1-1.$VB$NonLocal_$VB$Closure_2 As C._Closure$__1-0""
IL_000b: ldfld ""C._Closure$__1-0.$VB$Local_x4 As Object""
IL_0010: ret
}")
locals.Free()
End Sub
''' <summary>
''' Should not include "Me" inside display class instance method if
''' "Me" is not captured.
''' </summary>
<Fact>
Public Sub NoMeInsideDisplayClassInstanceMethod()
Const source = "
Imports System
Class C
Sub M(Of T As Class)(x As T)
Dim f As Func(Of Object, Func(Of T, Object)) = Function(y) _
Function(z)
return If(x, If(DirectCast(y, Object), z))
End Function
f(2)(x)
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
VerifyLocal(testData, "<>x(Of $CLS0)", locals(0), "<>m0", "y")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(1), "<>m1", "x")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(2), "<>m2", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-1._Lambda$__1")
testData = New CompilationTestData()
locals.Clear()
typeName = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, "<>x(Of $CLS0)", locals(0), "<>m0", "z")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(1), "<>m1", "y")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(2), "<>m2", "x")
VerifyLocal(testData, "<>x(Of $CLS0)", locals(3), "<>m3", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult)
locals.Free()
End Sub
<Fact>
Public Sub GenericMethod()
Const source = "
Class A (Of T)
Structure B(Of U, V)
Sub M(Of W)(o As A(Of U).B(Of V, Object)())
Dim t1 As T = Nothing
Dim u1 As U = Nothing
Dim w1 As W = Nothing
End Sub
End Structure
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="A.B.M")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(6, locals.Count)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(0), "<>m0(Of W)", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldarg.0
IL_0001: ldobj ""A(Of T).B(Of U, V)""
IL_0006: ret
}",
expectedGeneric:=True)
Dim method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m0(Of W)").Method, MethodSymbol)
Dim containingType = method.ContainingType
Dim containingTypeTypeParameters = containingType.TypeParameters
Dim typeParameterT As TypeParameterSymbol = containingTypeTypeParameters(0)
Dim typeParameterU As TypeParameterSymbol = containingTypeTypeParameters(1)
Dim typeParameterV As TypeParameterSymbol = containingTypeTypeParameters(2)
Dim returnType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal(typeParameterU, returnType.TypeArguments(0))
Assert.Equal(typeParameterV, returnType.TypeArguments(1))
returnType = returnType.ContainingType
Assert.Equal(typeParameterT, returnType.TypeArguments(0))
VerifyLocal(testData, "<>x(Of T, U, V)", locals(1), "<>m1(Of W)", "o", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldarg.1
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m1(Of W)").Method, MethodSymbol)
' method.ReturnType: A(Of U).B(Of V, object)()
returnType = DirectCast(DirectCast(method.ReturnType, ArrayTypeSymbol).ElementType, NamedTypeSymbol)
Assert.Equal(typeParameterV, returnType.TypeArguments(0))
returnType = returnType.ContainingType
Assert.Equal(typeParameterU, returnType.TypeArguments(0))
VerifyLocal(testData, "<>x(Of T, U, V)", locals(2), "<>m2(Of W)", "t1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.0
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m2(Of W)").Method, MethodSymbol)
Assert.Equal(typeParameterT, method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(3), "<>m3(Of W)", "u1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.1
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m3(Of W)").Method, MethodSymbol)
Assert.Equal(typeParameterU, method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(4), "<>m4(Of W)", "w1", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: ldloc.2
IL_0001: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m4(Of W)").Method, MethodSymbol)
Assert.Equal(method.TypeParameters.Single(), method.ReturnType)
VerifyLocal(testData, "<>x(Of T, U, V)", locals(5), "<>m5(Of W)", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (T V_0, //t1
U V_1, //u1
W V_2) //w1
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U, V, W)..ctor()""
IL_0005: ret
}",
expectedGeneric:=True)
method = DirectCast(testData.GetMethodData("<>x(Of T, U, V).<>m5(Of W)").Method, MethodSymbol)
returnType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal(typeParameterT, returnType.TypeArguments(0))
Assert.Equal(typeParameterU, returnType.TypeArguments(1))
Assert.Equal(typeParameterV, returnType.TypeArguments(2))
Assert.Equal(method.TypeParameters.Single(), returnType.TypeArguments(3))
' Verify <>c__TypeVariables types was emitted (#976772)
Using metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))
Dim reader = metadata.MetadataReader
Dim typeDef = reader.GetTypeDef("<>c__TypeVariables")
reader.CheckTypeParameters(typeDef.GetGenericParameters(), "T", "U", "V", "W")
End Using
locals.Free()
End Sub
<Fact>
Public Sub GenericLambda()
Const source = "
Imports System
Class C(Of T As Class)
Shared Sub M(Of U)(t1 As T)
Dim u1 As U = Nothing
Dim f As Func(Of Object) = Function() If(t1, DirectCast(u1, Object))
f()
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__1-0._Lambda$__0")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(3, locals.Count)
' NOTE: $CLS0 does not appear in the UI.
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(0), "<>m0", "t1")
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(1), "<>m1", "u1", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T)._Closure$__1-0(Of $CLS0).$VB$Local_u1 As $CLS0""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T, $CLS0)", locals(2), "<>m2", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, $CLS0)..ctor()""
IL_0005: ret
}")
Dim method = DirectCast(testData.GetMethodData("<>x(Of T, $CLS0).<>m1").Method, MethodSymbol)
Dim containingType = method.ContainingType
Assert.Equal(containingType.TypeParameters(1), method.ReturnType)
locals.Free()
End Sub
<Fact>
Public Sub Iterator_InstanceMethod()
Const source = "
Imports System.Collections
Class C
Private ReadOnly _c As Object()
Friend Sub New(c As Object())
_c = c
End Sub
Friend Iterator Function F() As IEnumerable
For Each o In _c
#ExternalSource(""test"", 999)
Yield o
#End ExternalSource
Next
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_F.MoveNext",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
Boolean V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_F.$VB$ResumableLocal_o$2 As Object""
IL_0006: ret
}")
locals.Free()
End Sub
<Fact()>
Public Sub Iterator_StaticMethod_Generic()
Const source = "
Imports System.Collections.Generic
Class C
Friend Shared Iterator Function F(Of T)(o As T()) As IEnumerable(Of T)
For i = 1 To o.Length
#ExternalSource(""test"", 999)
Dim t1 As T = Nothing
Yield t1
Yield o(i)
#End ExternalSource
Next
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_1_F.MoveNext",
atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, "<>x(Of T)", locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$Local_o As T()""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(1), "<>m1", "i", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$ResumableLocal_i$1 As Integer""
IL_0006: ret
}")
VerifyLocal(testData, "<>x(Of T)", locals(2), "<>m2", "t1", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_F(Of T).$VB$ResumableLocal_t1$2 As T""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T)", locals(3), "<>m3", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 6 (0x6)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T)..ctor()""
IL_0005: ret
}")
locals.Free()
End Sub
<Fact, WorkItem(1002672, "DevDiv")>
Public Sub Async_InstanceMethod_Generic()
Const source = "
Imports System.Threading.Tasks
Structure S(Of T As Class)
Private x As T
Friend Async Function F(Of U As Class)(y As u) As Task(Of Object)
Dim z As T = Nothing
Return If(Me.x, If(DirectCast(y, Object), z))
End Function
End Structure
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="S.VB$StateMachine_2_F.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(4, locals.Count)
VerifyLocal(testData, "<>x(Of T, U)", locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Object) V_2,
T V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""S(Of T).VB$StateMachine_2_F(Of U).$VB$Me As S(Of T)""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T, U)", locals(1), "<>m1", "y", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Object) V_2,
T V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""S(Of T).VB$StateMachine_2_F(Of U).$VB$Local_y As U""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T, U)", locals(2), "<>m2", "z", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Object V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Object) V_2,
T V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld ""S(Of T).VB$StateMachine_2_F(Of U).$VB$ResumableLocal_z$0 As T""
IL_0006: ret
}
")
VerifyLocal(testData, "<>x(Of T, U)", locals(3), "<>m3", "<>TypeVariables", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:="
{
// Code size 6 (0x6)
.maxstack 1
.locals init (Object V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Object) V_2,
T V_3,
System.Exception V_4)
IL_0000: newobj ""Sub <>c__TypeVariables(Of T, U)..ctor()""
IL_0005: ret
}
")
locals.Free()
End Sub
<Fact, WorkItem(1002672, "DevDiv")>
Public Sub Async_StaticMethod()
Const source = "
Imports System.Threading.Tasks
Class C
Shared Async Function F(o As Object) As Task(Of Object)
Return o
End Function
Shared Async Function M(x As Object) As task
Dim y = Await F(x)
Await F(y)
End Function
End Class
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_1,
C.VB$StateMachine_2_M V_2,
Object V_3,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$Local_x As Object""
IL_0006: ret
}
")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:="
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_1,
C.VB$StateMachine_2_M V_2,
Object V_3,
System.Runtime.CompilerServices.TaskAwaiter(Of Object) V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_y$0 As Object""
IL_0006: ret
}
")
locals.Free()
End Sub
<WorkItem(995976)>
<WorkItem(997613)>
<WorkItem(1002672)>
<WorkItem(1085911)>
<Fact>
Public Sub AsyncAndLambda()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Async Function F() As Task
End Function
Shared Sub G(a As Action)
a()
End Sub
Shared Async Function M(x As Integer) As Task(Of Integer)
Dim y = x + 1
Await F()
G(Sub()
x = x + 2
y = y + 2
End Sub)
x = x + y
Return x
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_3_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Integer) V_2,
System.Runtime.CompilerServices.TaskAwaiter V_3,
C.VB$StateMachine_3_M V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$Local_x As Integer""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (Integer V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Integer) V_2,
System.Runtime.CompilerServices.TaskAwaiter V_3,
C.VB$StateMachine_3_M V_4,
System.Exception V_5)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$ResumableLocal_$VB$Closure_$0 As C._Closure$__3-0""
IL_0006: ldfld ""C._Closure$__3-0.$VB$Local_y As Integer""
IL_000b: ret
}")
locals.Free()
End Sub
<WorkItem(2240)>
<Fact>
Public Sub AsyncLambda()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Sub M()
Dim f As Func(Of Integer, Task) = Async Function (x)
Dim y = 42
End Function
End Sub
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C._Closure$__.VB$StateMachine___Lambda$__1-0.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Threading.Tasks.Task V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__.VB$StateMachine___Lambda$__1-0.$VB$Local_x As Integer""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Threading.Tasks.Task V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__.VB$StateMachine___Lambda$__1-0.$VB$ResumableLocal_y$0 As Integer""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(996571)>
<Fact>
Public Sub MissingReference()
Const source0 =
"Public Class A
End Class
Public Structure B
End Structure"
Const source1 =
"Class C
Shared Sub M(a As A, b As B, c As C)
End Sub
End Class"
Dim comp0 = CreateCompilationWithMscorlib({source0}, options:=TestOptions.DebugDll)
Dim comp1 = CreateCompilationWithMscorlib({source1}, options:=TestOptions.DebugDll, references:={comp0.EmitToImageReference()})
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp1.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef), ' no reference to compilation0
exeBytes,
New SymReader(pdbBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData, expectedDiagnostics:=
{
Diagnostic(ERRID.ERR_TypeRefResolutionError3, "a").WithArguments("A", "Test.dll").WithLocation(1, 1)
})
Assert.Equal(0, locals.Count)
locals.Free()
End Sub
<Fact>
Public Sub AssignmentToLockLocal()
Const source = "
Class C
Sub M(o As Object)
SyncLock(o)
#ExternalSource(""test"", 999)
Dim x As Integer = 1
#End ExternalSource
End SyncLock
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M",
atLineNumber:=999)
Dim errorMessage As String = Nothing
Dim testData As New CompilationTestData()
context.CompileAssignment("o", "Nothing", errorMessage, testData, DebuggerDiagnosticFormatter.Instance)
Assert.Null(errorMessage) ' In regular code, there would be an error about modifying a lock local.
testData.GetMethodData("<>x.<>m0").VerifyIL(
"{
// Code size 4 (0x4)
.maxstack 1
.locals init (Object V_0,
Boolean V_1,
Integer V_2) //x
IL_0000: ldnull
IL_0001: starg.s V_1
IL_0003: ret
}")
End Sub
<WorkItem(1015887)>
<Fact>
Public Sub LocalDateConstant()
Const source = "
Class C
Shared Sub M()
Const d = #2010/01/02#
Dim dt As New System.DateTime(2010, 1, 2) ' It's easier to figure out the signature to pass if this is here.
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
context.CompileAssignment("d", "Nothing", errorMessage, formatter:=DebuggerDiagnosticFormatter.Instance)
Assert.Equal("error BC30074: Constant cannot be the target of an assignment.", errorMessage)
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim testData As New CompilationTestData()
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "dt", expectedILOpt:=
"{
// Code size 2 (0x2)
.maxstack 1
.locals init (Date V_0) //dt
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "d", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 15 (0xf)
.maxstack 1
.locals init (Date V_0) //dt
IL_0000: ldc.i8 0x8cc5955a94ec000
IL_0009: newobj ""Sub Date..ctor(Long)""
IL_000e: ret
}")
End Sub
<WorkItem(1015887)>
<Fact>
Public Sub LocalDecimalConstant()
Const source = "
Class C
Shared Sub M()
Const d As Decimal = 1.5D
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim references As ImmutableArray(Of MetadataReference) = Nothing
comp.EmitAndGetReferences(exeBytes, pdbBytes, references)
Dim runtime = CreateRuntimeInstance(ExpressionCompilerUtilities.GenerateUniqueName(), references, exeBytes, New SymReader(pdbBytes, exeBytes))
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
context.CompileAssignment("d", "Nothing", errorMessage, formatter:=DebuggerDiagnosticFormatter.Instance)
Assert.Equal("error BC30074: Constant cannot be the target of an assignment.", errorMessage)
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim testData As New CompilationTestData()
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "d", expectedFlags:=DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 5
IL_0000: ldc.i4.s 15
IL_0002: ldc.i4.0
IL_0003: ldc.i4.0
IL_0004: ldc.i4.0
IL_0005: ldc.i4.1
IL_0006: newobj ""Sub Decimal..ctor(Integer, Integer, Integer, Boolean, Byte)""
IL_000b: ret
}")
End Sub
<Fact, WorkItem(1022165), WorkItem(1028883), WorkItem(1034204)>
Public Sub KeywordIdentifiers()
Const source = "
Class C
Sub M([Nothing] As Integer)
Dim [Me] = 1
Dim [True] = ""t""c
Dim [Namespace] = ""NS""
End Sub
End Class"
Dim compilation0 = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation0)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(assembly.Count, 0)
Assert.Equal(locals.Count, 5)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldarg.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "[Nothing]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldarg.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(2), "<>m2", "[Me]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.0
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(3), "<>m3", "[True]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.1
IL_0001: ret
}")
VerifyLocal(testData, typeName, locals(4), "<>m4", "[Namespace]", expectedILOpt:="
{
// Code size 2 (0x2)
.maxstack 1
.locals init (Integer V_0, //Me
Char V_1, //True
String V_2) //Namespace
IL_0000: ldloc.2
IL_0001: ret
}")
locals.Free()
End Sub
<Fact>
Public Sub ExtensionIterator()
Const source = "
Module M
<System.Runtime.CompilerServices.Extension>
Iterator Function F(x As Integer) As System.Collections.IEnumerable
Yield x
End Function
End Module
"
Const expectedIL = "
{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""M.VB$StateMachine_0_F.$VB$Local_x As Integer""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, "M.VB$StateMachine_0_F.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Assert.Equal(1, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=expectedIL)
Assert.Equal(SpecialType.System_Int32, testData.GetMethodData(typeName & ".<>m0").Method.ReturnType.SpecialType)
locals.Free()
testData = New CompilationTestData()
Dim errorMessage As String = Nothing
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
Dim methodData = testData.GetMethodData("<>x.<>m0")
methodData.VerifyIL(expectedIL)
Assert.Equal(SpecialType.System_Int32, methodData.Method.ReturnType.SpecialType)
End Sub
<WorkItem(1014763)>
<Fact>
Public Sub TypeVariablesTypeParameterNames()
Const source = "
Imports System.Collections.Generic
Class C
Iterator Shared Function I(Of T)() As IEnumerable(Of T)
Yield Nothing
End Function
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, "C.VB$StateMachine_1_I.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.NotNull(assembly)
Assert.NotEqual(0, assembly.Count)
Dim local = locals.Single()
Assert.Equal("<>TypeVariables", local.LocalName)
Assert.Equal("<>m0", local.MethodName)
Dim method = testData.GetMethodData("<>x(Of T).<>m0").Method
Dim typeVariablesType = DirectCast(method.ReturnType, NamedTypeSymbol)
Assert.Equal("T", typeVariablesType.TypeParameters.Single().Name)
Assert.Equal("T", typeVariablesType.TypeArguments.Single().Name)
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedIteratorDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Imports System.Collections.Generic
Class C
Iterator Function M1(x As Integer, y As Integer) As IEnumerable(Of Integer)
Dim local = 0
Yield local
End Function
Iterator Function M1(x As Integer, y As Single) As IEnumerable(Of Single)
Dim local = 0.0F
Yield local
End Function
Shared Iterator Function M2(x As Integer, y As Single) As IEnumerable(Of Single)
Dim local = 0.0F
Yield local
End Function
Shared Iterator Function M2(Of T)(x As Integer, y As T) As IEnumerable(Of T)
Dim local As T = Nothing
Yield local
End Function
Shared Iterator Function M2(x As Integer, y As Integer) As IEnumerable(Of Integer)
Dim local = 0
Yield local
End Function
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim ilTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C.{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
' M1(Integer, Integer)
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "y"))
locals.Clear()
' M1(Integer, Single)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, Single)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, T)
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
typeName += "(Of T)"
displayClassName += "(Of T)"
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "T", displayClassName, "y"))
locals.Clear()
' M2(Integer, Integer)
displayClassName = "VB$StateMachine_5_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Integer", displayClassName, "y"))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedAsyncDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Imports System.Threading.Tasks
Class C
Async Function M1(x As Integer) As Task(Of Integer)
Dim local = 0
Return local
End Function
Async Function M1(x As Integer, y As Single) As Task(Of Single)
Dim local = 0.0F
Return local
End Function
Shared Async Function M2(x As Integer, y As Single) As Task(Of Single)
Dim local = 0.0F
return local
End Function
Shared Async Function M2(Of T)(x As T) As Task(Of T)
Dim local As T = Nothing
Return local
End Function
Shared Async Function M2(x As Integer) As Task(Of Integer)
Dim local = 0
Return local
End Function
End Class"
Dim compilation = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim ilTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init ({0} V_0,
Integer V_1,
System.Threading.Tasks.Task(Of {0}) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.{2}.$VB$Local_{3} As {1}""
IL_0006: ret
}}"
' M1(Integer)
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", "Integer", displayClassName, "x"))
locals.Clear()
' M1(Integer, Single)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Single", "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", "Single", displayClassName, "y"))
locals.Clear()
' M2(Integer, Single)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Single", "Integer", displayClassName, "x"))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(ilTemplate, "Single", "Single", displayClassName, "y"))
locals.Clear()
' M2(T)
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "T", "T", displayClassName + "(Of T)", "x"))
locals.Clear()
' M2(Integer)
displayClassName = "VB$StateMachine_5_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(ilTemplate, "Integer", "Integer", displayClassName, "x"))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub MultipleLambdasDifferentParameterNames_ArgumentsOnly()
Dim source = "
Imports System
Class C
Sub M1(x As Integer)
Dim a As Action(Of Integer) = Sub(y) x.ToString()
Dim f As Func(Of Integer, Integer) = Function(z) x
End Sub
Shared Sub M2(Of T)(x As Integer)
Dim a As Action(Of Integer) = Sub(y) y.ToString()
Dim f As Func(Of Integer, Integer) = Function(z) z
Dim g As Func(Of T, T) = Function(ti) ti
End Sub
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim voidRetILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.{0}
IL_0001: ret
}}"
Dim funcILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0)
IL_0000: ldarg.{1}
IL_0001: ret
}}"
' Sub(y) x.ToString()
displayClassName = "_Closure$__1-0"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__0", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "y", expectedILOpt:=String.Format(voidRetILTemplate, 1))
locals.Clear()
' Function(z) x
displayClassName = "_Closure$__1-0"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__1", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=String.Format(funcILTemplate, "Integer", 1))
locals.Clear()
' Sub(y) y.ToString()
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-0", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "y", expectedILOpt:=String.Format(voidRetILTemplate, 1))
locals.Clear()
' Function(z) z
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-1", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "z", expectedILOpt:=String.Format(funcILTemplate, "Integer", 1))
locals.Clear()
' Function(ti) ti
displayClassName = "_Closure$__2"
GetLocals(runtime, "C." + displayClassName + "._Lambda$__2-2", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of $CLS0)", locals(0), "<>m0", "ti", expectedILOpt:=String.Format(funcILTemplate, "$CLS0", 1))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub OverloadedRegularMethodDifferentParameterTypes_ArgumentsOnly()
Dim source = "
Class C
Sub M1(x As Integer, y As Integer)
Dim local = 0
End Sub
Function M1(x As Integer, y As String) As String
Dim local As String = Nothing
return local
End Function
Shared Sub M2(x As Integer, y As String)
Dim local As String = Nothing
End Sub
Shared Function M2(Of T)(x As Integer, y As T) As T
Dim local As T = Nothing
Return local
End Function
Shared Function M2(x As Integer, ByRef y As Integer) As Integer
Dim local As Integer = 0
Return local
End Function
End Class"
Dim compilation = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim voidRetILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0) //local
IL_0000: ldarg.{1}
IL_0001: ret
}}"
Dim funcILTemplate = "
{{
// Code size 2 (0x2)
.maxstack 1
.locals init ({0} V_0, {1}
{0} V_1) //local
IL_0000: ldarg.{2}
IL_0001: ret
}}"
Dim refParamILTemplate = "
{{
// Code size 3 (0x3)
.maxstack 1
.locals init ({0} V_0, {1}
{0} V_1) //local
IL_0000: ldarg.{2}
IL_0001: ldind.i4
IL_0002: ret
}}"
' M1(Integer, Integer)
GetLocals(runtime, "C.M1(Int32,Int32)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(voidRetILTemplate, "Integer", 1))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(voidRetILTemplate, "Integer", 2))
locals.Clear()
' M1(Integer, String)
GetLocals(runtime, "C.M1(Int32,String)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(funcILTemplate, "String", "//M1", 1))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(funcILTemplate, "String", "//M1", 2))
locals.Clear()
' M2(Integer, String)
GetLocals(runtime, "C.M2(Int32,String)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(voidRetILTemplate, "String", 0))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(voidRetILTemplate, "String", 1))
locals.Clear()
' M2(Integer, T)
GetLocals(runtime, "C.M2(Int32,T)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0(Of T)", "x", expectedILOpt:=String.Format(funcILTemplate, "T", "//M2", 0), expectedGeneric:=True)
VerifyLocal(testData, typeName, locals(1), "<>m1(Of T)", "y", expectedILOpt:=String.Format(funcILTemplate, "T", "//M2", 1), expectedGeneric:=True)
locals.Clear()
' M2(Integer, Integer)
GetLocals(runtime, "C.M2(Int32,Int32)", argumentsOnly:=True, locals:=locals, count:=2, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=String.Format(funcILTemplate, "Integer", "//M2", 0))
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=String.Format(refParamILTemplate, "Integer", "//M2", 1))
locals.Clear()
locals.Free()
End Sub
<Fact, WorkItem(1063254)>
Public Sub MultipleMethodsLocalConflictsWithParameterName_ArgumentsOnly()
Dim source = "
Imports System.Collections.Generic
Imports System.Threading.Tasks
Class C(Of T)
Iterator Function M1() As IEnumerable(Of Integer)
Dim x = 0
Yield x
End Function
Iterator Function M1(x As Integer) As IEnumerable(Of Integer)
Yield x
End Function
Iterator Function M2(x As Integer) As IEnumerable(Of Integer)
Yield x
End Function
Iterator Function M2() As IEnumerable(Of Integer)
Dim x = 0
Yield x
End Function
Shared Async Function M3() As Task(Of T)
Dim x As T = Nothing
return x
End Function
Shared Async Function M3(x As T) As Task(Of T)
Return x
End Function
Shared Async Function M4(x As T) As Task(Of T)
Return x
End Function
Shared Async Function M4() As Task(Of T)
Dim x As T = Nothing
Return x
End Function
End Class"
Dim compilation = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(compilation)
Dim displayClassName As String
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
Dim iteratorILTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
{0} V_1)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T).{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
Dim asyncILTemplate = "
{{
// Code size 7 (0x7)
.maxstack 1
.locals init ({0} V_0,
Integer V_1,
System.Threading.Tasks.Task(Of {0}) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C(Of T).{1}.$VB$Local_{2} As {0}""
IL_0006: ret
}}"
' M1()
displayClassName = "VB$StateMachine_1_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M1(Integer)
displayClassName = "VB$StateMachine_2_M1"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(iteratorILTemplate, "Integer", displayClassName, "x"))
locals.Clear()
' M2(Integer)
displayClassName = "VB$StateMachine_3_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(iteratorILTemplate, "Integer", displayClassName, "x"))
locals.Clear()
' M2()
displayClassName = "VB$StateMachine_4_M2"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M3()
displayClassName = "VB$StateMachine_5_M3"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
' M3(Integer)
displayClassName = "VB$StateMachine_6_M3"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(asyncILTemplate, "T", displayClassName, "x"))
locals.Clear()
' M4(Integer)
displayClassName = "VB$StateMachine_7_M4"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName + "(Of T)", locals(0), "<>m0", "x", expectedILOpt:=String.Format(asyncILTemplate, "T", displayClassName, "x"))
locals.Clear()
' M4()
displayClassName = "VB$StateMachine_8_M4"
GetLocals(runtime, "C." + displayClassName + ".MoveNext", argumentsOnly:=True, locals:=locals, count:=0, typeName:=typeName, testData:=testData)
locals.Clear()
locals.Free()
End Sub
<WorkItem(1115044, "DevDiv")>
<Fact>
Public Sub CaseSensitivity()
Const source = "
Class C
Shared Sub M(p As Integer)
Dim s As String
End Sub
End Class
"
Dim comp = CreateCompilationWithMscorlib({source}, options:=TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.M")
Dim errorMessage As String = Nothing
Dim testData As CompilationTestData
testData = New CompilationTestData()
context.CompileExpression("P", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0) //s
IL_0000: ldarg.0
IL_0001: ret
}
")
testData = New CompilationTestData()
context.CompileExpression("S", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL("
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0) //s
IL_0000: ldloc.0
IL_0001: ret
}
")
End Sub
<WorkItem(1115030)>
<Fact>
Public Sub CatchInAsyncStateMachine()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Shared Function F() As Object
Throw New ArgumentException()
End Function
Shared Async Function M() As Task
Dim o As Object
Try
o = F()
Catch e As Exception
#ExternalSource(""test"", 999)
o = e
#End ExternalSource
End Try
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_M.MoveNext",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Exception V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_o$0 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "e", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Exception V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_e$1 As System.Exception""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(1115030)>
<Fact>
Public Sub CatchInIteratorStateMachine()
Const source =
"Imports System
Imports System.Collections
Class C
Shared Function F() As Object
Throw New ArgumentException()
End Function
Shared Iterator Function M() As IEnumerable
Dim o As Object
Try
o = F()
Catch e As Exception
#ExternalSource(""test"", 999)
o = e
#End ExternalSource
End Try
Yield o
End Function
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(
runtime,
methodName:="C.VB$StateMachine_2_M.MoveNext",
atLineNumber:=999)
Dim testData = New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "o", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_o$0 As Object""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "e", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Boolean V_0,
Integer V_1,
System.Exception V_2)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_2_M.$VB$ResumableLocal_e$1 As System.Exception""
IL_0006: ret
}")
locals.Free()
End Sub
<WorkItem(947)>
<Fact>
Public Sub DuplicateEditorBrowsableAttributes()
Const libSource = "
Namespace System.ComponentModel
Public Enum EditorBrowsableState
Always = 0
Never = 1
Advanced = 2
End Enum
<AttributeUsage(AttributeTargets.All)>
Friend NotInheritable Class EditorBrowsableAttribute
Inherits Attribute
Public Sub New(state As EditorBrowsableState)
End Sub
End Class
End Namespace
"
Const source = "
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)>
Class C
Sub M()
End Sub
End Class
"
Dim libRef = CreateCompilationWithMscorlib({libSource}, options:=TestOptions.DebugDll).EmitToImageReference()
Dim comp = CreateCompilationWithReferences({VisualBasicSyntaxTree.ParseText(source)}, {MscorlibRef, SystemRef}, TestOptions.DebugDll)
Dim exeBytes As Byte() = Nothing
Dim pdbBytes As Byte() = Nothing
Dim unusedReferences As ImmutableArray(Of MetadataReference) = Nothing
Dim result = comp.EmitAndGetReferences(exeBytes, pdbBytes, unusedReferences)
Assert.True(result)
' Referencing SystemCoreRef and SystemXmlLinqRef will cause Microsoft.VisualBasic.Embedded to be compiled
' and it depends on EditorBrowsableAttribute.
Dim runtimeReferences = ImmutableArray.Create(MscorlibRef, SystemRef, SystemCoreRef, SystemXmlLinqRef, libRef)
Dim runtime = CreateRuntimeInstance(GetUniqueName(), runtimeReferences, exeBytes, New SymReader(pdbBytes))
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, "C.M", argumentsOnly:=False, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
Assert.Equal("Me", locals.Single().LocalName)
locals.Free()
End Sub
<WorkItem(2089, "https://github.com/dotnet/roslyn/issues/2089")>
<Fact>
Public Sub MultipleMeFields()
Const source =
"Imports System
Imports System.Threading.Tasks
Class C
Async Shared Function F(a As Action) As Task
a()
End Function
Sub G(s As String)
End Sub
Async Sub M()
Dim s As String = Nothing
Await F(Sub() G(s))
End Sub
End Class"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, methodName:="C.VB$StateMachine_3_M.MoveNext")
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me", expectedILOpt:=
"{
// Code size 7 (0x7)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.VB$StateMachine_3_M V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$Me As C""
IL_0006: ret
}")
VerifyLocal(testData, typeName, locals(1), "<>m1", "s", expectedILOpt:=
"{
// Code size 12 (0xc)
.maxstack 1
.locals init (Integer V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.VB$StateMachine_3_M V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_3_M.$VB$ResumableLocal_$VB$Closure_$0 As C._Closure$__3-0""
IL_0006: ldfld ""C._Closure$__3-0.$VB$Local_s As String""
IL_000b: ret
}")
locals.Free()
End Sub
<WorkItem(2336, "https://github.com/dotnet/roslyn/issues/2336")>
<Fact>
Public Sub LocalsOnAsyncEndSub()
Const source = "
Imports System
Imports System.Threading.Tasks
Class C
Async Sub M()
Dim s As String = Nothing
#ExternalSource(""test"", 999)
End Sub
#End ExternalSource
End Class
"
Dim comp = CreateCompilationWithReferences(
MakeSources(source),
{MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929},
TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim context = CreateMethodContext(runtime, methodName:="C.VB$StateMachine_1_M.MoveNext", atLineNumber:=999)
Dim testData As New CompilationTestData()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim typeName As String = Nothing
context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=typeName, testData:=testData)
Assert.Equal(2, locals.Count)
VerifyLocal(testData, typeName, locals(0), "<>m0", "Me")
VerifyLocal(testData, typeName, locals(1), "<>m1", "s")
locals.Free()
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_FromParameter()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Let y = x.ToString()
Let z = x.GetHashCode()
Select x & y & z
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-2"
Const zIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$z As Integer""
IL_0006: ret
}
"
Const xIL = "
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_0006: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_000b: ret
}
"
Const yIL = "
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_0006: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_000b: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_FromDisplayClassField()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Let y = x.ToString()
Let z = x.GetHashCode()
Select x.Select(Function(c) y & z)
End Sub
End Class
"
Const methodName = "C._Closure$__1-0._Lambda$__3"
Const cIL = "
{
// Code size 2 (0x2)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.1
IL_0001: ret
}
"
Const zIL = "
{
// Code size 12 (0xc)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$z As Integer""
IL_000b: ret
}
"
Const xIL = "
{
// Code size 17 (0x11)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_000b: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_0010: ret
}
"
Const yIL = "
{
// Code size 17 (0x11)
.maxstack 1
.locals init (String V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C._Closure$__1-0.$VB$Local_$VB$It As VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer)""
IL_0006: ldfld ""VB$AnonymousType_1(Of VB$AnonymousType_0(Of String, String), Integer).$$VB$It As VB$AnonymousType_0(Of String, String)""
IL_000b: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_0010: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=4, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "c", expectedILOpt:=cIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(3), "<>m3", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("c", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(cIL)
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_It1()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args, y In args
From z In args
Select x & y & z
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-3"
Const zIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ret
}
"
Const xIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_0(Of String, String).$x As String""
IL_0006: ret
}
"
Const yIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ldfld ""VB$AnonymousType_0(Of String, String).$y As String""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "z", expectedILOpt:=zIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "y", expectedILOpt:=yIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_It2()
Const source = "
Imports System.Linq
Class C
Sub M(nums As Integer())
Dim q = From x In nums
Join y In nums
Join z In nums
On z Equals y
On x Equals y And z Equals x
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-5"
Const xIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
"
Const yIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ldfld ""VB$AnonymousType_1(Of Integer, Integer).$y As Integer""
IL_0006: ret
}
"
Const zIL = "
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.2
IL_0001: ldfld ""VB$AnonymousType_1(Of Integer, Integer).$z As Integer""
IL_0006: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=3, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=xIL)
VerifyLocal(testData, typeName, locals(1), "<>m1", "y", expectedILOpt:=yIL)
VerifyLocal(testData, typeName, locals(2), "<>m2", "z", expectedILOpt:=zIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
testData = New CompilationTestData()
context.CompileExpression("y", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(yIL)
testData = New CompilationTestData()
context.CompileExpression("z", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(zIL)
End Sub
<WorkItem(1139013, "DevDiv")>
<Fact>
Public Sub TransparentIdentifiers_ItAnonymous()
Const source = "
Imports System.Linq
Class C
Sub M(args As String())
Dim concat =
From x In args
Group y = x.GetHashCode() By x
Into s = Sum(y + 3)
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-2"
Const xIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "x", expectedILOpt:=xIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("x", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
End Sub
<WorkItem(3236, "https://github.com/dotnet/roslyn/pull/3236")>
<Fact>
Public Sub AnonymousTypeParameter()
Const source = "
Imports System.Linq
Class C
Shared Sub Main(args As String())
Dim anonymousTypes =
From a In args
Select New With {.Value = a, .Length = a.Length}
Dim values =
From t In anonymousTypes
Select t.Value
End Sub
End Class
"
Const methodName = "C._Closure$__._Lambda$__1-1"
Const xIL = "
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.1
IL_0001: ret
}
"
Dim comp = CreateCompilationWithMscorlib({source}, {SystemCoreRef, MsvbRef}, TestOptions.DebugDll)
Dim runtime = CreateRuntimeInstance(comp)
Dim typeName As String = Nothing
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
Dim testData As CompilationTestData = Nothing
GetLocals(runtime, methodName, argumentsOnly:=False, locals:=locals, count:=1, typeName:=typeName, testData:=testData)
VerifyLocal(testData, typeName, locals(0), "<>m0", "t", expectedILOpt:=xIL)
locals.Free()
Dim context = CreateMethodContext(runtime, methodName)
Dim errorMessage As String = Nothing
testData = New CompilationTestData()
context.CompileExpression("t", errorMessage, testData)
Assert.Null(errorMessage)
testData.GetMethodData("<>x.<>m0").VerifyIL(xIL)
End Sub
<WorkItem(955, "https://github.com/aspnet/Home/issues/955")>
<Fact>
Public Sub ConstantWithErrorType()
Const source = "
Module Module1
Sub Main()
Const a = 1
End Sub
End Module"
Dim comp = CreateCompilationWithMscorlib({source}, {MsvbRef}, options:=TestOptions.DebugExe)
Dim runtime = CreateRuntimeInstance(comp)
Dim badConst = New MockSymUnmanagedConstant(
"a",
1,
Function(bufferLength As Integer, ByRef count As Integer, name() As Byte)
count = 0
Return DiaSymReader.SymUnmanagedReaderExtensions.E_NOTIMPL
End Function)
Dim debugInfo = New MethodDebugInfoBytes.Builder(constants:={badConst}).Build()
Dim locals = ArrayBuilder(Of LocalAndMethod).GetInstance()
GetLocals(runtime, "Module1.Main", debugInfo, locals, count:=0)
locals.Free()
End Sub
Private Shared Sub GetLocals(runtime As RuntimeInstance, methodName As String, argumentsOnly As Boolean, locals As ArrayBuilder(Of LocalAndMethod), count As Integer, ByRef typeName As String, ByRef testData As CompilationTestData)
Dim context = CreateMethodContext(runtime, methodName)
testData = New CompilationTestData()
Dim assembly = context.CompileGetLocals(locals, argumentsOnly, typeName, testData)
Assert.NotNull(assembly)
If count = 0 Then
Assert.Equal(0, assembly.Count)
Else
Assert.InRange(assembly.Count, 0, Integer.MaxValue)
End If
Assert.Equal(count, locals.Count)
End Sub
Private Shared Sub GetLocals(runtime As RuntimeInstance, methodName As String, debugInfo As MethodDebugInfoBytes, locals As ArrayBuilder(Of LocalAndMethod), count As Integer)
Dim blocks As ImmutableArray(Of MetadataBlock) = Nothing
Dim moduleVersionId As Guid = Nothing
Dim methodToken = 0
Dim localSignatureToken = 0
GetContextState(runtime, methodName, blocks, moduleVersionId, symReader:=Nothing, methodOrTypeToken:=methodToken, localSignatureToken:=localSignatureToken)
Dim symReader = New MockSymUnmanagedReader(
New Dictionary(Of Integer, MethodDebugInfoBytes)() From
{
{methodToken, debugInfo}
}.ToImmutableDictionary())
Dim context = EvaluationContext.CreateMethodContext(
Nothing,
blocks,
MakeDummyLazyAssemblyReaders(),
symReader,
moduleVersionId,
methodToken,
methodVersion:=1,
ilOffset:=0,
localSignatureToken:=localSignatureToken)
Dim assembly = context.CompileGetLocals(locals, argumentsOnly:=False, typeName:=Nothing, testData:=Nothing)
Assert.NotNull(assembly)
If count = 0 Then
Assert.Equal(0, assembly.Count)
Else
Assert.InRange(assembly.Count, 0, Integer.MaxValue)
End If
Assert.Equal(count, locals.Count)
End Sub
End Class
End Namespace
|
VPashkov/roslyn
|
src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/LocalsTests.vb
|
Visual Basic
|
apache-2.0
| 121,123
|
' 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.Diagnostics
Imports System.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualBasic
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
Partial Friend Class TriviaDataFactory
''' <summary>
''' represents a general trivia between two tokens. slightly more expensive than others since it
''' needs to calculate stuff unlike other cases
''' </summary>
Private Class LineContinuationTrivia
Inherits AbstractLineBreakTrivia
Public Sub New(optionSet As OptionSet,
originalString As String,
indentation As Integer)
MyBase.New(optionSet, originalString, 1, indentation, False)
End Sub
Protected Overrides Function CreateStringFromState() As String
Contract.ThrowIfFalse(Me.SecondTokenIsFirstTokenOnLine)
Dim builder = StringBuilderPool.Allocate()
builder.Append(" "c)
builder.Append(SyntaxFacts.GetText(SyntaxKind.LineContinuationTrivia))
builder.AppendIndentationString(Me.Spaces, Me.OptionSet.GetOption(FormattingOptions.UseTabs, LanguageNames.VisualBasic), Me.OptionSet.GetOption(FormattingOptions.TabSize, LanguageNames.VisualBasic))
Return StringBuilderPool.ReturnAndFree(builder)
End Function
Public Overrides Function WithIndentation(indentation As Integer,
context As FormattingContext,
formattingRules As ChainedFormattingRules,
cancellationToken As CancellationToken) As TriviaData
If Me.Spaces = indentation Then
Return Me
End If
Return New LineContinuationTrivia(Me.OptionSet, Me._original, indentation)
End Function
End Class
End Class
End Namespace
|
bbarry/roslyn
|
src/Workspaces/VisualBasic/Portable/Formatting/Engine/Trivia/TriviaDataFactory.LineContinuationTrivia.vb
|
Visual Basic
|
apache-2.0
| 2,494
|
Module modUmlaut
Public Function Umlaut(ByVal Zeichen As Char) As Char
Select Case Zeichen
Case "ä", "à"
Umlaut = "a"
Case "Ä", "À"
Umlaut = "A"
Case "ö"
Umlaut = "o"
Case "Ö"
Umlaut = "O"
Case "é", "è", "ë"
Umlaut = "e"
Case "ü"
Umlaut = "u"
Case "Ü"
Umlaut = "U"
Case Else
Umlaut = Zeichen
End Select
End Function
End Module
|
severinkaderli/gibb
|
Lehrjahr_2/Modul_318/KaderliS_Sortieren/KaderliS_Sortieren/modUmlaut.vb
|
Visual Basic
|
mit
| 590
|
Namespace _09_Galleries
Friend NotInheritable Class Program
''' <summary>
''' The main entry point for the application.
''' </summary>
Private Sub New()
End Sub
<STAThread>
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New Form1())
End Sub
End Class
End Namespace
|
joergkrause/netrix
|
NetrixDemo/RibbonLib/Samples/VB/09-Galleries/Program.vb
|
Visual Basic
|
mit
| 368
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fFechas_Seguimientos_Compras"
'-------------------------------------------------------------------------------------------'
Partial Class fFechas_Seguimientos_Compras
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 loComandoSeleccionar As New StringBuilder()
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" SELECT CAST(Compras.Seg_Adm as XML) AS seguimiento INTO #xmlData from Compras")
loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" SELECT '1' AS Tabla, ")
loComandoSeleccionar.AppendLine(" Compras.Cod_Pro, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Compras.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Compras.Nom_Pro = '') THEN Proveedores.Nom_Pro ELSE Compras.Nom_Pro END) END) AS Nom_Pro, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Compras.Nom_Pro = '') THEN Proveedores.Rif ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Compras.Rif = '') THEN Proveedores.Rif ELSE Compras.Rif END) END) AS Rif, ")
loComandoSeleccionar.AppendLine(" Proveedores.Nit, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Compras.Nom_Pro = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (SUBSTRING(Compras.Dir_Fis,1, 200) = '') THEN SUBSTRING(Proveedores.Dir_Fis,1, 200) ELSE SUBSTRING(Compras.Dir_Fis,1, 200) END) END) AS Dir_Fis, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Proveedores.Generico = 0 AND Compras.Nom_Pro = '') THEN Proveedores.Telefonos ELSE ")
loComandoSeleccionar.AppendLine(" (CASE WHEN (Compras.Telefonos = '') THEN Proveedores.Telefonos ELSE Compras.Telefonos END) END) AS Telefonos, ")
loComandoSeleccionar.AppendLine(" Proveedores.Fax, ")
loComandoSeleccionar.AppendLine(" Compras.Documento, ")
loComandoSeleccionar.AppendLine(" Compras.Factura, ")
loComandoSeleccionar.AppendLine(" Compras.Control, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Reg, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Pag, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Rec, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Doc, ")
loComandoSeleccionar.AppendLine(" Compras.Fecha1, ")
loComandoSeleccionar.AppendLine(" Compras.Fecha2, ")
loComandoSeleccionar.AppendLine(" Compras.Fecha3, ")
loComandoSeleccionar.AppendLine(" Compras.Fecha4, ")
loComandoSeleccionar.AppendLine(" Compras.Fecha5, ")
loComandoSeleccionar.AppendLine(" Compras.Comentario, ")
loComandoSeleccionar.AppendLine(" Formas_Pagos.Nom_For, ")
loComandoSeleccionar.AppendLine(" Compras.Cod_Ven, ")
loComandoSeleccionar.AppendLine(" Vendedores.Nom_Ven, ")
loComandoSeleccionar.AppendLine(" NULL as se_renglon,")
loComandoSeleccionar.AppendLine(" NULL as se_fecha,")
loComandoSeleccionar.AppendLine(" NULL as se_contacto,")
loComandoSeleccionar.AppendLine(" NULL as se_accion,")
loComandoSeleccionar.AppendLine(" NULL as se_medio,")
loComandoSeleccionar.AppendLine(" NULL as se_comentario,")
loComandoSeleccionar.AppendLine(" NULL as se_prioridad,")
loComandoSeleccionar.AppendLine(" NULL as se_etapa,")
loComandoSeleccionar.AppendLine(" NULL as se_usuario")
loComandoSeleccionar.AppendLine(" FROM Compras ")
loComandoSeleccionar.AppendLine(" JOIN Proveedores ON (Compras.Cod_Pro = Proveedores.Cod_Pro) ")
loComandoSeleccionar.AppendLine(" JOIN Formas_Pagos ON (Compras.Cod_For = Formas_Pagos.Cod_For) ")
loComandoSeleccionar.AppendLine(" JOIN Vendedores ON (Compras.Cod_Ven = Vendedores.Cod_Ven) ")
loComandoSeleccionar.AppendLine(" WHERE " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" ")
loComandoSeleccionar.AppendLine(" SELECT '2' AS Tabla, ")
loComandoSeleccionar.AppendLine(" NULL AS Cod_Pro, ")
loComandoSeleccionar.AppendLine(" NULL AS Nom_Pro, ")
loComandoSeleccionar.AppendLine(" NULL AS Rif, ")
loComandoSeleccionar.AppendLine(" NULL AS Nit, ")
loComandoSeleccionar.AppendLine(" NULL AS Dir_Fis, ")
loComandoSeleccionar.AppendLine(" NULL AS Telefonos, ")
loComandoSeleccionar.AppendLine(" NULL AS Fax, ")
loComandoSeleccionar.AppendLine(" NULL AS Documento, ")
loComandoSeleccionar.AppendLine(" NULL AS Factura, ")
loComandoSeleccionar.AppendLine(" NULL AS Control, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Ini, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Fin, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Reg, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Pag, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Rec, ")
loComandoSeleccionar.AppendLine(" NULL AS Fec_Doc, ")
loComandoSeleccionar.AppendLine(" NULL AS Fecha1, ")
loComandoSeleccionar.AppendLine(" NULL AS Fecha2, ")
loComandoSeleccionar.AppendLine(" NULL AS Fecha3, ")
loComandoSeleccionar.AppendLine(" NULL AS Fecha4, ")
loComandoSeleccionar.AppendLine(" NULL AS Fecha5, ")
loComandoSeleccionar.AppendLine(" NULL AS Comentario, ")
loComandoSeleccionar.AppendLine(" NULL AS Nom_For, ")
loComandoSeleccionar.AppendLine(" NULL AS Cod_Ven, ")
loComandoSeleccionar.AppendLine(" NULL AS Nom_Ven, ")
loComandoSeleccionar.AppendLine(" ROW_NUMBER() OVER (ORDER BY D.C.value('@status', 'Varchar(15)') DESC) as se_renglon,")
loComandoSeleccionar.AppendLine(" D.C.value('@fecha', 'datetime') as se_fecha,")
loComandoSeleccionar.AppendLine(" D.C.value('@contacto', 'Varchar(300)') as se_contacto,")
loComandoSeleccionar.AppendLine(" D.C.value('@accion', 'Varchar(300)') as se_accion,")
loComandoSeleccionar.AppendLine(" D.C.value('@medio', 'Varchar(300)') as se_medio,")
loComandoSeleccionar.AppendLine(" D.C.value('@comentario', 'Varchar(5000)') as se_comentario,")
loComandoSeleccionar.AppendLine(" D.C.value('@prioridad', 'Varchar(300)') as se_prioridad,")
loComandoSeleccionar.AppendLine(" D.C.value('@etapa', 'Varchar(300)') as se_etapa,")
loComandoSeleccionar.AppendLine(" D.C.value('@usuario', 'Varchar(100)') as se_usuario")
loComandoSeleccionar.AppendLine(" FROM #xmlData")
loComandoSeleccionar.AppendLine(" CROSS APPLY seguimiento.nodes('elementos/elemento') D(c) -- recuerda que seguimiento es el nombre del campo donde esta el XML")
loComandoSeleccionar.AppendLine(" ORDER BY tabla, compras.documento DESC ,se_renglon")
'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'--------------------------------------------------'
' Carga la imagen del logo en cusReportes '
'--------------------------------------------------'
Me.mCargarLogoEmpresa(laDatosReporte.Tables(0), "LogoEmpresa")
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fFechas_Seguimientos_Compras", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfFechas_Seguimientos_Compras.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
'-------------------------------------------------------------------------------------------'
' MAT: 28/07/11: Programacion inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fFechas_Seguimientos_Compras.aspx.vb
|
Visual Basic
|
mit
| 10,434
|
Imports Leviathan.Visualisation
Namespace Commands
Partial Public Class CommandFileOutput
Implements ICommandsOutput
Implements ICommandsOutputWriter
#Region " ICommandsOutput Implementation "
Private Sub Write_Outputs( _
ParamArray ByVal values As IFixedWidthWriteable() _
) Implements ICommandsOutput.Show_Outputs
If Not values Is Nothing Then
For i As Integer = 0 To values.Count - 1
If HasWritten OrElse i > 0 Then TerminateLine()
HasWritten = True
values(i).Write(CharacterWidth, Me, 0)
Next
End If
End Sub
Private Sub Write_Close() Implements ICommandsOutput.Close
For i As Integer = 0 To ToFiles.Length - 1
ToFiles(i).Close()
Next
End Sub
#End Region
#Region " ICommandsOutputWriter Implementation "
Private Sub Write( _
ByVal value As String, _
ByVal type As InformationType _
) _
Implements ICommandsOutputWriter.Write
If Not String.IsNullOrEmpty(value) Then
For i As Integer = 0 To ToFiles.Length - 1
If ToFiles(i).CanWrite Then ToFiles(i).Write(Encoder.GetBytes(value), 0, Encoder.GetByteCount(value))
Next
End If
End Sub
Private Function FixedWidthWrite( _
ByRef value As String, _
ByVal width As Integer, _
ByVal type as InformationType _
) As Boolean _
Implements ICommandsOutputWriter.FixedWidthWrite
Dim returnValue As Boolean
Dim lengthWritten As Integer
If Not String.IsNullOrEmpty(value) Then _
Write(CubeControl.MaxWidthWrite(value, width, lengthWritten, returnValue), type)
' Write the Padding Spaces
Write(New String(SPACE, width - lengthWritten), InformationType.None)
Return returnValue
End Function
Private Sub TerminateLine( _
Optional numberOfTimes As System.Int32 = 1 _
) _
Implements ICommandsOutputWriter.TerminateLine
For i As Integer = 1 To numberOfTimes
Write(Environment.NewLine, InformationType.None)
Next
End Sub
#End Region
End Class
End Namespace
|
thiscouldbejd/Leviathan
|
_Commands/Partials/CommandFileOutput.vb
|
Visual Basic
|
mit
| 2,035
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' 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.
#End Region
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Windows.Forms.Design
<ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip)> Public Class BarFormatterPicker
Inherits ToolStripControlHost
Public Event SelectedEntryChanged(sender As Object, e As EventArgs)
Private Const NoBarFormatter As String = "(None)"
Private mCombo As ComboBox
Public Sub New()
MyBase.New(New ComboBox())
mCombo = DirectCast(MyBase.Control, ComboBox)
mCombo.DropDownStyle = ComboBoxStyle.DropDownList
mCombo.Sorted = False
End Sub
Public Sub Initialise()
mCombo.Items.Clear()
mCombo.Items.Add(NoBarFormatter)
For Each factoryEntry In BarFormatters.GetAvailableBarFormatterFactories
mCombo.Items.Add(factoryEntry)
Next
End Sub
Public Shadows ReadOnly Property Control() As Control
Get
Throw New NotSupportedException
End Get
End Property
Protected Overrides Sub OnSubscribeControlEvents(c As System.Windows.Forms.Control)
MyBase.OnSubscribeControlEvents(c)
Dim combo = CType(c, ComboBox)
AddHandler combo.SelectedIndexChanged, AddressOf handleSelectionChange
End Sub
<Category("Appearance")> Public Property DropDownHeight() As Integer
Get
Return mCombo.DropDownHeight
End Get
Set
mCombo.DropDownHeight = value
End Set
End Property
<Category("Appearance")> Public Property DropDownWidth() As Integer
Get
Return mCombo.DropDownWidth
End Get
Set
mCombo.DropDownWidth = value
End Set
End Property
<Category("Appearance")> Public Property FlatStyle() As FlatStyle
Get
Return mCombo.FlatStyle
End Get
Set
mCombo.FlatStyle = value
End Set
End Property
<Category("Appearance")> Public Property IntegralHeight() As Boolean
Get
Return mCombo.IntegralHeight
End Get
Set
mCombo.IntegralHeight = value
End Set
End Property
<Browsable(False)> Public ReadOnly Property SelectedEntry() As BarFormatterFactoryListEntry
Get
If mCombo.SelectedIndex = -1 Or mCombo.SelectedIndex = 0 Then
Return Nothing
Else
Return DirectCast(mCombo.SelectedItem, BarFormatterFactoryListEntry)
End If
End Get
End Property
Public Sub SelectItem(factoryName As String, libraryName As String)
If factoryName = "" Then
mCombo.SelectedIndex = mCombo.FindStringExact(NoBarFormatter)
Else
mCombo.SelectedIndex = mCombo.Items.IndexOf(New BarFormatterFactoryListEntry With {.FactoryName = factoryName, .LibraryName = libraryName})
End If
End Sub
Private Sub handleSelectionChange(sender As Object, e As EventArgs)
RaiseEvent SelectedEntryChanged(sender, e)
End Sub
End Class
|
tradewright/tradebuild-platform.net
|
src/BarFormatters/BarFormatterPicker.vb
|
Visual Basic
|
mit
| 4,254
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' 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.
#End Region
'------------------------------------------------------------------------------
' <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>
'------------------------------------------------------------------------------
Namespace My
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.1.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.TradeWright.Trading.TradeBuild.Config.My.MySettings
Get
Return Global.TradeWright.Trading.TradeBuild.Config.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
tradewright/tradebuild-platform.net
|
src/ConfigUtils/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 4,101
|
Module Module1
Function IndexOf(n As Integer, s As Integer()) As Integer
For ii = 1 To s.Length
Dim i = ii - 1
If s(i) = n Then
Return i
End If
Next
Return -1
End Function
Function GetDigits(n As Integer, le As Integer, digits As Integer()) As Boolean
While n > 0
Dim r = n Mod 10
If r = 0 OrElse IndexOf(r, digits) >= 0 Then
Return False
End If
le -= 1
digits(le) = r
n \= 10
End While
Return True
End Function
Function RemoveDigit(digits As Integer(), le As Integer, idx As Integer) As Integer
Dim pows = {1, 10, 100, 1000, 10000}
Dim sum = 0
Dim pow = pows(le - 2)
For ii = 1 To le
Dim i = ii - 1
If i = idx Then
Continue For
End If
sum += digits(i) * pow
pow \= 10
Next
Return sum
End Function
Sub Main()
Dim lims = {{12, 97}, {123, 986}, {1234, 9875}, {12345, 98764}}
Dim count(5) As Integer
Dim omitted(5, 10) As Integer
Dim upperBound = lims.GetLength(0)
For ii = 1 To upperBound
Dim i = ii - 1
Dim nDigits(i + 2 - 1) As Integer
Dim dDigits(i + 2 - 1) As Integer
Dim blank(i + 2 - 1) As Integer
For n = lims(i, 0) To lims(i, 1)
blank.CopyTo(nDigits, 0)
Dim nOk = GetDigits(n, i + 2, nDigits)
If Not nOk Then
Continue For
End If
For d = n + 1 To lims(i, 1) + 1
blank.CopyTo(dDigits, 0)
Dim dOk = GetDigits(d, i + 2, dDigits)
If Not dOk Then
Continue For
End If
For nixt = 1 To nDigits.Length
Dim nix = nixt - 1
Dim digit = nDigits(nix)
Dim dix = IndexOf(digit, dDigits)
If dix >= 0 Then
Dim rn = RemoveDigit(nDigits, i + 2, nix)
Dim rd = RemoveDigit(dDigits, i + 2, dix)
If (n / d) = (rn / rd) Then
count(i) += 1
omitted(i, digit) += 1
If count(i) <= 12 Then
Console.WriteLine("{0}/{1} = {2}/{3} by omitting {4}'s", n, d, rn, rd, digit)
End If
End If
End If
Next
Next
Next
Console.WriteLine()
Next
For i = 2 To 5
Console.WriteLine("There are {0} {1}-digit fractions of which:", count(i - 2), i)
For j = 1 To 9
If omitted(i - 2, j) = 0 Then
Continue For
End If
Console.WriteLine("{0,6} have {1}'s omitted", omitted(i - 2, j), j)
Next
Console.WriteLine()
Next
End Sub
End Module
|
ncoe/rosetta
|
Fraction_reduction/Visual Basic .NET/FractionReduction/Module1.vb
|
Visual Basic
|
mit
| 3,256
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.5477
'
' 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("MP3_Player.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
|
hhaslam11/Visual-Basic-Projects
|
MP3 Player/MP3 Player/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,736
|
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports BaseClasses
''' <summary>
''' Adds a jquery theme to the page.
''' </summary>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a jquery theme to the page.")> _
Public Class ThemeAdder
Inherits WebControl
Public Enum themes
black_tie = 1
blitzer = 2
cupertino = 3
dark_hive = 4
dot_luv = 5
eggplant = 6
excite_bike = 7
flick = 8
hot_sneaks = 9
humanity = 10
le_frog = 11
minc_choc = 12
overcast = 13
pepper_grinder = 14
redmond = 15
smoothness = 16
south_street = 17
start = 18
sunny = 19
swanky_purse = 20
trontastic = 21
ui_darkness = 22
ui_lightness = 23
vader = 24
aristo = 25
bootstrap = 26
united = 27
absolution = 28
delta = 29
selene = 30
metro = 31
custom = 255
End Enum
Protected Overrides ReadOnly Property TagKey() _
As HtmlTextWriterTag
Get
Return HtmlTextWriterTag.Link
End Get
End Property
Private Shared bodyCssFix As String = ".ui-widget{ font-size:0.8em; } input.ui-button{ padding: 0.2em 1em; }"
#Region "Theme Adding Function"
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="themepath"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddCustomTheme(ByRef page As Page, ByVal themepath As String, Optional ByVal ThemeButtons As Boolean = True, Optional ByVal ThemeBody As Boolean = True, Optional ByVal ThemeTextBoxes As Boolean = True, Optional ByVal ThemeCheckandRadioButtons As Boolean = True)
AddTheme(page, themes.custom, ThemeButtons, ThemeBody, ThemeTextBoxes, ThemeCheckandRadioButtons, themepath)
End Sub
''' <summary>
''' Gets the themeAdder object for the specified page.
''' </summary>
''' <param name="page"></param>
''' <returns></returns>
''' <remarks></remarks>
<System.ComponentModel.Description("Gets the themeAdder object for the specified page.")> _
Public Shared Function getThemeAdder(ByVal page As Page) As ThemeAdder
If page.Items("themeAdder") Is Nothing Then
page.Items("themeAdder") = New ThemeAdder
page.Header.Controls.Add(page.Items("themeAdder"))
jQueryInclude.RegisterJQuery(page)
End If
Return page.Items("themeAdder")
End Function
#Region "Add Theme"
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page)
Dim ta As ThemeAdder = getThemeAdder(page)
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean, ByVal ThemeBody As Boolean)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
ta.themeBody = ThemeBody
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean, ByVal ThemeBody As Boolean, ByVal ThemeTextBoxes As Boolean)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
ta.themeBody = ThemeBody
ta.themeTextBoxes = ThemeTextBoxes
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean, ByVal ThemeBody As Boolean, ByVal ThemeTextBoxes As Boolean, ByVal ThemeCheckandRadioButtons As Boolean)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
ta.themeBody = ThemeBody
ta.themeTextBoxes = ThemeTextBoxes
ta.themeCheckboxes = ThemeCheckandRadioButtons
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean, ByVal ThemeBody As Boolean, ByVal ThemeTextBoxes As Boolean, ByVal ThemeCheckandRadioButtons As Boolean, ByVal themepath As String)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
ta.themeBody = ThemeBody
ta.themeTextBoxes = ThemeTextBoxes
ta.themeCheckboxes = ThemeCheckandRadioButtons
ta.customThemePath = themepath
End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <param name="theme"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddTheme(ByRef page As Page, ByVal theme As themes, ByVal ThemeButtons As Boolean, ByVal ThemeBody As Boolean, ByVal ThemeTextBoxes As Boolean, ByVal ThemeCheckandRadioButtons As Boolean, ByVal themepath As String, ByVal fadeEffect As Boolean)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.theme = theme
ta.themeButtons = ThemeButtons
ta.themeBody = ThemeBody
ta.themeTextBoxes = ThemeTextBoxes
ta.themeCheckboxes = ThemeCheckandRadioButtons
ta.customThemePath = themepath
ta.fadeEffect = fadeEffect
End Sub
#End Region
'Friend Shared Sub AddThemeFiles(ByRef page As Page, ByVal theme As themes, Optional ByVal ThemeButtons As Boolean = True, _
' Optional ByVal ThemeBody As Boolean = True, Optional ByVal ThemeTextBoxes As Boolean = True, _
' Optional ByVal ThemeCheckandRadioButtons As Boolean = True, Optional ByVal themepath As String = "", _
' Optional ByVal fadeEffect As Boolean = True)
' Dim ta As ThemeAdder = getThemeAdder(page)
' ta.themeButtons = ThemeButtons
' ta.themeBody = ThemeBody
' ta.themeTextBoxes = ThemeTextBoxes
' ta.themeCheckboxes = ThemeCheckandRadioButtons
' ta.customThemePath = themepath
' ta.fadeEffect = fadeEffect
'End Sub
''' <summary>
''' Adds a theme to the page.
''' </summary>
''' <param name="page"></param>
''' <remarks></remarks>
<System.ComponentModel.Description("Adds a theme to the page.")> _
Public Shared Sub AddThemeToIframe(ByRef page As Page, Optional ByVal themeBody As Boolean = True)
Dim ta As ThemeAdder = getThemeAdder(page)
ta.themeBody = themeBody
ta.isIframe = True
End Sub
#End Region
#Region "ThemeAdder Component"
'Private Sub jQueryInclude_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' ' BaseVirtualPathProvider.registerVirtualPathProvider()
' If _customeThemePath.Length > 0 Then
' AddTheme(Me.Page, theme, themeButtons, themeBody, themeTextBoxes, themeCheckboxes, customThemePath)
' Else
' AddTheme(Me.Page, theme, themeButtons, themeBody, themeTextBoxes, themeCheckboxes)
' End If
'End Sub
Private WithEvents pg As Page
Public Overrides Property Page As System.Web.UI.Page
Get
Return MyBase.Page
End Get
Set(value As System.Web.UI.Page)
MyBase.Page = value
pg = value
End Set
End Property
Private _customeThemePath As String = ""
Public Property customThemePath() As String
Get
Return _customeThemePath
End Get
Set(ByVal value As String)
_customeThemePath = value
End Set
End Property
Private _themeButtons As Boolean = True
Public Property themeButtons() As Boolean
Get
Return _themeButtons
End Get
Set(ByVal value As Boolean)
_themeButtons = value
End Set
End Property
Private _themeBody As Boolean = False
Public Property themeBody() As Boolean
Get
Return _themeBody
End Get
Set(ByVal value As Boolean)
_themeBody = value
End Set
End Property
Private fadeEffectValue As Boolean = True
Public Property fadeEffect() As Boolean
Get
Return fadeEffectValue
End Get
Set(ByVal value As Boolean)
fadeEffectValue = value
End Set
End Property
Private _themeTextBoxes As Boolean = True
Public Property themeTextBoxes() As Boolean
Get
Return _themeTextBoxes
End Get
Set(ByVal value As Boolean)
_themeTextBoxes = value
End Set
End Property
Private _themeCheckboxes As Boolean = True
Public Property themeCheckboxes() As Boolean
Get
Return _themeCheckboxes
End Get
Set(ByVal value As Boolean)
_themeCheckboxes = value
End Set
End Property
Private _isIframe As Boolean = False
Public Property isIframe() As Boolean
Get
Return _isIframe
End Get
Set(ByVal value As Boolean)
_isIframe = value
End Set
End Property
Private _theme As themes = themes.smoothness
Public Property theme() As themes
Get
Return _theme
End Get
Set(ByVal value As themes)
_theme = value
End Set
End Property
#End Region
Private Sub AddThemeFilesP()
jQueryInclude.RegisterJQueryUI(Page)
jQueryInclude.addScriptFile(Page, "jQueryLibrary/jquery.formThemes.js")
jQueryInclude.addScriptFile(Page, "jQueryLibrary/Base.css")
If theme <> Nothing Then
If Not Page.Items("currentJQUITheme") Is Nothing Then
jQueryInclude.deleteScriptFile(Page, "ui-theme")
'Dim tName As String = jQueryInclude.getEnumName(page.Items("currentJQUITheme")).Replace("_", "-")
'jQueryInclude.deleteScriptFile(page, "jQueryLibrary/" & tName & "." & tName & ".css")
End If
Page.Items("currentJQUITheme") = theme
Page.Items("currentCustomJQUITheme") = customThemePath
Else
theme = Page.Items("currentJQUITheme")
customThemePath = Page.Items("currentCustomJQUITheme")
If theme = Nothing Then
theme = themes.smoothness
'page.Items("currentJQUITheme") = theme
End If
End If
Dim themeName As String = jQueryInclude.getEnumName(theme).Replace("_", "-")
If Not theme = themes.custom Then
jQueryInclude.addScriptFile(Page, "jQueryLibrary/" & themeName & "." & themeName & ".css", , , , "ui-theme")
Else
jQueryInclude.addScriptFile(Page, customThemePath, , , True, "ui-theme")
End If
jQueryInclude.addStyleBlock(Page, bodyCssFix, "UI-sizeFix")
jQueryInclude.addScriptBlockPageLoad(Page, "$('button, input:submit, input:button, input:reset').button();", False, "ThemeButtons")
jQueryInclude.addScriptBlockPageLoad(Page, "$('input[type=text],input[type=password],textarea,select').textbox();", False, "ThemeTextBoxes")
jQueryInclude.addScriptBlockPageLoad(Page, "$('body').addClass('ui-widget');", False, "ThemeBody")
'jQueryInclude.addScriptBlock(page, "window.onerror=function(){if(document.body){document.body.style.display='block';}else{document.write(""<style type='text/css'>body{ display:block; }</style>"");}}; document.write(""<style type='text/css'>body{ display:none; }</style>""); $(function(){document.body.style.display='block';$('body').hide().fadeIn(500,function(){}); });", False, , "bodyFadein")
jQueryInclude.addScriptBlock(Page, "window.onerror=function(){if(document.body)document.body.style.display='block';}; document.write(""<style type='text/css'>body{ display:none; }</style>""); $(function(){document.body.style.display='block';$('body').hide().fadeIn(500,function(){}); });", False, Nothing, "bodyFadein", Nothing)
jQueryInclude.addScriptBlockPageLoad(Page, "$('input:checkbox').checkbox();", False, "ThemeCheckBoxes")
jQueryInclude.addScriptBlockPageLoad(Page, "$('input:radio').radio();", False, "ThemeRadioButtons")
Dim header As jQueryInclude = jQueryInclude.getInitialInclude(Page)
If Not themeButtons Then
header.replaceIncludeByID("ThemeButtons", "")
End If
If Not themeTextBoxes Then
header.replaceIncludeByID("ThemeTextBoxes", "")
End If
If Not themeBody Then
header.replaceIncludeByID("ThemeBody", "")
End If
If Not fadeEffect Then
header.replaceIncludeByID("bodyFadein", "")
End If
If Not themeCheckboxes Then
header.replaceIncludeByID("ThemeCheckBoxes", "")
End If
End Sub
Private Sub AddThemeToIframeP()
jQueryInclude.RegisterJQueryUI(page)
jQueryInclude.addScriptFile(page, "jQueryLibrary/jquery.formThemes.js")
jQueryInclude.addScriptFile(page, "jQueryLibrary/Base.css")
jQueryInclude.addScriptFile(page, "jQueryLibrary/smoothness.smoothness.css", , , , "ui-theme")
jQueryInclude.addStyleBlock(page, bodyCssFix, "UI-sizeFix")
'jQueryInclude.addScriptBlock(page, "", , , "ThemeButtons")
'jQueryInclude.addScriptBlock(page, "", , , "ThemeTextBoxes")
'jQueryInclude.addScriptBlock(page, "", , , "ThemeCheckBoxes")
'jQueryInclude.addStyleBlock(page, ".ui-widget{ font-size:0.8em; }")
Dim bodyStr As String = ""
If themeBody Then
bodyStr = "$('body').addClass('ui-widget-content ui-widget');"
End If
jQueryInclude.addScriptBlock(Page, "window.onerror=function(){document.body.style.display='block';}; document.write(""<style type='text/css'>body{ display:none; }</style>""); $(function(){document.body.style.display='block';$('body').hide().fadeIn(500,function(){}); });", minify:=False, id:="bodyFadein", jQueryIncludeHeader:=Nothing)
'jQueryInclude.addScriptBlockPageLoad(page, "$('head').append(parent.$('#ui-theme').clone()); $('head').append(parent.$('#UI-sizeFix').clone()); " & bodyStr & " $('head').append(parent.$('#ThemeButtons').clone());$('head').append(parent.$('#ThemeTextBoxes').clone());$('head').append(parent.$('#ThemeCheckBoxes').clone());")
jQueryInclude.addScriptBlockPageLoad(page, "addFromParent('#ui-theme');addFromParent('#UI-sizeFix'); " & bodyStr & _
" addFromParent('#ThemeButtons');addFromParent('#ThemeTextBoxes');addFromParent('#ThemeCheckBoxes'); ")
End Sub
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
End Sub
Private Sub ThemeAdder_PreRender(sender As Object, e As System.EventArgs) Handles Me.PreRender
If Not isIframe Then
AddThemeFilesP()
Else
AddThemeToIframeP()
End If
End Sub
End Class
|
Micmaz/DTIControls
|
jQueryLibrary/jQueryLibrary/ThemeAdder.vb
|
Visual Basic
|
mit
| 17,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.Immutable
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGen
Friend NotInheritable Class CodeGenerator
Private ReadOnly _method As MethodSymbol
Private ReadOnly _block As BoundStatement
Private ReadOnly _builder As ILBuilder
Private ReadOnly _module As PEModuleBuilder
Private ReadOnly _diagnostics As DiagnosticBag
Private ReadOnly _optimizations As OptimizationLevel
Private ReadOnly _emitPdbSequencePoints As Boolean
Private ReadOnly _stackLocals As HashSet(Of LocalSymbol) = Nothing
''' <summary> Keeps track on current nesting level of try statements </summary>
Private _tryNestingLevel As Integer = 0
''' <summary> Current enclosing Catch block if there is any. </summary>
Private _currentCatchBlock As BoundCatchBlock = Nothing
Private ReadOnly _synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser = New SynthesizedLocalOrdinalsDispenser()
Private _uniqueNameId As Integer
' label used when when return is emitted in a form of store/goto
Private Shared ReadOnly s_returnLabel As New Object
Private _unhandledReturn As Boolean
Private _checkCallsForUnsafeJITOptimization As Boolean
Private _asyncCatchHandlerOffset As Integer = -1
Private _asyncYieldPoints As ArrayBuilder(Of Integer) = Nothing
Private _asyncResumePoints As ArrayBuilder(Of Integer) = Nothing
Public Sub New(method As MethodSymbol,
boundBody As BoundStatement,
builder As ILBuilder,
moduleBuilder As PEModuleBuilder,
diagnostics As DiagnosticBag,
optimizations As OptimizationLevel,
emittingPdbs As Boolean)
Debug.Assert(method IsNot Nothing)
Debug.Assert(boundBody IsNot Nothing)
Debug.Assert(builder IsNot Nothing)
Debug.Assert(moduleBuilder IsNot Nothing)
Debug.Assert(diagnostics IsNot Nothing)
Me._method = method
Me._block = boundBody
Me._builder = builder
Me._module = moduleBuilder
Me._diagnostics = diagnostics
' Always optimize synthesized methods that don't contain user code.
Me._optimizations = If(method.GenerateDebugInfo, optimizations, OptimizationLevel.Release)
' Emit sequence points unless
' - the PDBs are not being generated
' - debug information for the method is not generated since the method does not contain
' user code that can be stepped thru, or changed during EnC.
'
' This setting only affects generating PDB sequence points, it shall Not affect generated IL in any way.
Me._emitPdbSequencePoints = emittingPdbs AndAlso method.GenerateDebugInfo
If Me._optimizations = OptimizationLevel.Release Then
Me._block = Optimizer.Optimize(method, boundBody, Me._stackLocals)
End If
Me._checkCallsForUnsafeJITOptimization = (Me._method.ImplementationAttributes And MethodSymbol.DisableJITOptimizationFlags) <> MethodSymbol.DisableJITOptimizationFlags
Debug.Assert(Not Me._module.JITOptimizationIsDisabled(Me._method))
End Sub
Public Sub Generate()
Debug.Assert(_asyncYieldPoints Is Nothing)
Debug.Assert(_asyncResumePoints Is Nothing)
Debug.Assert(_asyncCatchHandlerOffset < 0)
GenerateImpl()
End Sub
Public Sub Generate(<Out> ByRef asyncCatchHandlerOffset As Integer,
<Out> ByRef asyncYieldPoints As ImmutableArray(Of Integer),
<Out> ByRef asyncResumePoints As ImmutableArray(Of Integer))
GenerateImpl()
Debug.Assert(_asyncCatchHandlerOffset >= 0)
asyncCatchHandlerOffset = _builder.GetILOffsetFromMarker(_asyncCatchHandlerOffset)
Dim yieldPoints As ArrayBuilder(Of Integer) = _asyncYieldPoints
Dim resumePoints As ArrayBuilder(Of Integer) = _asyncResumePoints
Debug.Assert((yieldPoints Is Nothing) = (resumePoints Is Nothing))
If yieldPoints Is Nothing Then
asyncYieldPoints = ImmutableArray(Of Integer).Empty
asyncResumePoints = ImmutableArray(Of Integer).Empty
Else
Debug.Assert(yieldPoints.Count > 0, "Why it was allocated?")
Dim yieldPointsBuilder = ArrayBuilder(Of Integer).GetInstance
Dim resumePointsBuilder = ArrayBuilder(Of Integer).GetInstance
For i = 0 To yieldPoints.Count - 1
Dim yieldOffset = _builder.GetILOffsetFromMarker(yieldPoints(i))
Dim resumeOffset = _builder.GetILOffsetFromMarker(resumePoints(i))
Debug.Assert(resumeOffset >= 0) ' resume marker should always be reachable from dispatch
' yield point may not be reachable if the whole
' await is not reachable; we just ignore such awaits
If yieldOffset > 0 Then
yieldPointsBuilder.Add(yieldOffset)
resumePointsBuilder.Add(resumeOffset)
End If
Next
asyncYieldPoints = yieldPointsBuilder.ToImmutableAndFree()
asyncResumePoints = resumePointsBuilder.ToImmutableAndFree()
yieldPoints.Free()
resumePoints.Free()
End If
End Sub
Private Sub GenerateImpl()
SetInitialDebugDocument()
' Synthesized methods should have a sequence point
' at offset 0 to ensure correct stepping behavior.
If _emitPdbSequencePoints AndAlso _method.IsImplicitlyDeclared Then
_builder.DefineInitialHiddenSequencePoint()
End If
EmitStatement(_block)
If _unhandledReturn Then
HandleReturn()
End If
If Not _diagnostics.HasAnyErrors Then
_builder.Realize()
End If
_synthesizedLocalOrdinals.Free()
End Sub
Private Sub HandleReturn()
_builder.MarkLabel(s_returnLabel)
_builder.EmitRet(True)
_unhandledReturn = False
End Sub
Private Sub EmitFieldAccess(fieldAccess As BoundFieldAccess)
' TODO: combination load/store for +=; addresses for ref
Dim field As FieldSymbol = fieldAccess.FieldSymbol
If Not field.IsShared Then
EmitExpression(fieldAccess.ReceiverOpt, True)
End If
If field.IsShared Then
_builder.EmitOpCode(ILOpCode.Ldsfld)
Else
_builder.EmitOpCode(ILOpCode.Ldfld)
End If
EmitSymbolToken(field, fieldAccess.Syntax)
End Sub
Private Function IsStackLocal(local As LocalSymbol) As Boolean
Return _stackLocals IsNot Nothing AndAlso _stackLocals.Contains(local)
End Function
Private Sub EmitLocalStore(local As BoundLocal)
' TODO: combination load/store for +=; addresses for ref
Dim slot = GetLocal(local)
_builder.EmitLocalStore(slot)
End Sub
Private Sub EmitSymbolToken(symbol As FieldSymbol, syntaxNode As VisualBasicSyntaxNode)
_builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics)
End Sub
Private Sub EmitSymbolToken(symbol As MethodSymbol, syntaxNode As VisualBasicSyntaxNode)
_builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics)
End Sub
Private Sub EmitSymbolToken(symbol As TypeSymbol, syntaxNode As VisualBasicSyntaxNode)
_builder.EmitToken(_module.Translate(symbol, syntaxNode, _diagnostics), syntaxNode, _diagnostics)
End Sub
Private Sub EmitSequencePointExpression(node As BoundSequencePointExpression, used As Boolean)
Dim syntax = node.Syntax
If _emitPdbSequencePoints Then
If syntax Is Nothing Then
EmitHiddenSequencePoint()
Else
EmitSequencePoint(syntax)
End If
End If
' used is true to ensure that something is emitted
EmitExpression(node.Expression, used:=True)
EmitPopIfUnused(used)
End Sub
Private Sub EmitSequencePointExpressionAddress(node As BoundSequencePointExpression, addressKind As AddressKind)
Dim syntax = node.Syntax
If _emitPdbSequencePoints Then
If syntax Is Nothing Then
EmitHiddenSequencePoint()
Else
EmitSequencePoint(syntax)
End If
End If
Dim temp = EmitAddress(node.Expression, addressKind)
Debug.Assert(temp Is Nothing, "we should not be taking ref of a sequence if value needs a temp")
End Sub
Private Sub EmitSequencePointStatement(node As BoundSequencePoint)
Dim syntax = node.Syntax
If _emitPdbSequencePoints Then
If syntax Is Nothing Then
EmitHiddenSequencePoint()
Else
EmitSequencePoint(syntax)
End If
End If
Dim statement = node.StatementOpt
Dim instructionsEmitted As Integer = 0
If statement IsNot Nothing Then
instructionsEmitted = EmitStatementAndCountInstructions(statement)
End If
If instructionsEmitted = 0 AndAlso syntax IsNot Nothing AndAlso _optimizations = OptimizationLevel.Debug Then
' if there was no code emitted, then emit nop
' otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop)
End If
End Sub
Private Sub EmitSequencePointStatement(node As BoundSequencePointWithSpan)
Dim span = node.Span
If span <> Nothing AndAlso _emitPdbSequencePoints Then
EmitSequencePoint(node.SyntaxTree, span)
End If
Dim statement = node.StatementOpt
Dim instructionsEmitted As Integer = 0
If statement IsNot Nothing Then
instructionsEmitted = EmitStatementAndCountInstructions(statement)
End If
If instructionsEmitted = 0 AndAlso span <> Nothing AndAlso _optimizations = OptimizationLevel.Debug Then
' if there was no code emitted, then emit nop
' otherwise this point could get associated with some random statement, possibly in a wrong scope
_builder.EmitOpCode(ILOpCode.Nop)
End If
End Sub
Private Sub SetInitialDebugDocument()
Dim methodBlockSyntax = Me._method.Syntax
If _emitPdbSequencePoints AndAlso methodBlockSyntax IsNot Nothing Then
' If methodBlockSyntax is available (i.e. we're in a SourceMethodSymbol), then
' provide the IL builder with our best guess at the appropriate debug document.
' If we don't and this is hidden sequence point precedes all non-hidden sequence
' points, then the IL Builder will drop the sequence point for lack of a document.
' This negatively impacts the scenario where we insert hidden sequence points at
' the beginnings of methods so that step-into (F11) will handle them correctly.
_builder.SetInitialDebugDocument(methodBlockSyntax.SyntaxTree)
End If
End Sub
Private Sub EmitHiddenSequencePoint()
Debug.Assert(_emitPdbSequencePoints)
_builder.DefineHiddenSequencePoint()
End Sub
Private Sub EmitSequencePoint(syntax As VisualBasicSyntaxNode)
EmitSequencePoint(syntax.SyntaxTree, syntax.Span)
End Sub
Private Function EmitSequencePoint(tree As SyntaxTree, span As TextSpan) As TextSpan
Debug.Assert(tree IsNot Nothing)
Debug.Assert(_emitPdbSequencePoints)
_builder.DefineSequencePoint(tree, span)
Return span
End Function
End Class
End Namespace
|
paladique/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/CodeGenerator.vb
|
Visual Basic
|
apache-2.0
| 13,116
|
Public Class ActionButtons
Private _actionButtonCount As Integer = 0
Private _repNode As GitPathNode
Private Sub CreateActionButton(name As String, repPath As String, cmd As String, args As String, useShell As Boolean)
Dim button As New Button()
button.Text = name
button.Width = pActionButtons.Width - 24
button.Height = 25
pActionButtons.Controls.Add(button)
button.Left = 3
button.Top = (button.Height + 3) * _actionButtonCount
_actionButtonCount += 1
Dim color = System.Drawing.Color.LightGray
Select Case IO.Path.GetExtension(cmd.ToLower)
Case ".atsln" : color = Color.Pink
Case ".cmd" : color = Color.LightYellow
Case ".sln" : color = Color.FromArgb(255, 200, 255)
Case ".dch" : color = Color.Orange
Case ".dip" : color = Color.LightGreen
Case ".atsln" : color = Color.Pink
End Select
button.BackColor = color
AddHandler button.Click, Sub()
If useShell Then
Shell(cmd, AppWinStyle.NormalFocus)
Else
Dim prc As New Process()
prc.StartInfo.FileName = cmd
prc.StartInfo.Arguments = args
prc.StartInfo.WorkingDirectory = repPath
prc.Start()
End If
End Sub
End Sub
Private Sub CreateActionButtonCommand(command As String, repPath As String)
Dim parts = command.Split({"|"}, StringSplitOptions.None)
If parts.Length > 2 Then
If parts(0) = "GitterCake" Then
Dim appManagerPath = IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Bwl AppManager", "GitterCake", "output", "Release", "Gitter.exe")
If IO.File.Exists(appManagerPath) Then
parts(1) = appManagerPath
End If
End If
If IO.File.Exists(parts(1)) Then
CreateActionButton(parts(0), repPath, parts(1), parts(2), False)
End If
End If
End Sub
Private Sub CleanActionButtons()
_actionButtonCount = 0
pActionButtons.Controls.Clear()
End Sub
Public Sub SetRepNode(repNode As GitPathNode)
_repNode = repNode
If _repNode IsNot Nothing Then _repNode.UpdateStatus(False, False)
tbFilter.Text = ""
CleanActionButtons()
Dim thr As New Threading.Thread(Sub()
CreateActionButtons("")
End Sub)
thr.Start()
End Sub
Public Sub CreateActionButtons(filter As String)
If _repNode IsNot Nothing Then
If filter = "" Then
'default
If _repNode.Status.IsRepository Then
Dim files As New List(Of String)
files.AddRange(IO.Directory.GetFiles(_repNode.FullPath, "*.cmd", IO.SearchOption.AllDirectories))
files.AddRange(IO.Directory.GetFiles(_repNode.FullPath, "*.sln", IO.SearchOption.AllDirectories))
files.AddRange(IO.Directory.GetFiles(_repNode.FullPath, "*.atsln", IO.SearchOption.AllDirectories))
files.AddRange(IO.Directory.GetFiles(_repNode.FullPath, "*.dch", IO.SearchOption.AllDirectories))
files.AddRange(IO.Directory.GetFiles(_repNode.FullPath, "*.dip", IO.SearchOption.AllDirectories))
'create buttons
Me.Invoke(Sub()
CreateActionButton("Explorer", _repNode.FullPath, "explorer", ".", False)
If GitManager.Settings.ShowCommandsAsButtons.Value Then
If GitManager.Settings.Command1Setting.Value > "" Then CreateActionButtonCommand(GitManager.Settings.Command1Setting.Value, _repNode.FullPath)
If GitManager.Settings.Command2Setting.Value > "" Then CreateActionButtonCommand(GitManager.Settings.Command2Setting.Value, _repNode.FullPath)
If GitManager.Settings.Command3Setting.Value > "" Then CreateActionButtonCommand(GitManager.Settings.Command3Setting.Value, _repNode.FullPath)
If GitManager.Settings.Command4Setting.Value > "" Then CreateActionButtonCommand(GitManager.Settings.Command4Setting.Value, _repNode.FullPath)
If GitManager.Settings.Command5Setting.Value > "" Then CreateActionButtonCommand(GitManager.Settings.Command5Setting.Value, _repNode.FullPath)
End If
For Each file In files
Dim info As New IO.FileInfo(file)
CreateActionButton(info.Name, _repNode.FullPath, file, "", False)
Next
End Sub)
Else
Me.Invoke(Sub()
CreateActionButton("Explorer", _repNode.FullPath, "explorer", ".", False)
End Sub)
End If
Else
'find mode
For Each file In IO.Directory.GetFiles(_repNode.FullPath, "*" + filter + "*.*", IO.SearchOption.AllDirectories)
Dim info As New IO.FileInfo(file)
CreateActionButton(info.Name, _repNode.FullPath, file, "", False)
Next
End If
End If
End Sub
Private Sub tbFilter_KeyDown(sender As Object, e As KeyEventArgs) Handles tbFilter.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
CleanActionButtons()
CreateActionButtons(tbFilter.Text.Trim)
End If
End Sub
End Class
|
Lifemotion/Bwl.GitManager
|
Bwl.GitManager/App/Controls/ActionButtons.vb
|
Visual Basic
|
apache-2.0
| 6,196
|
' 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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertToInterpolatedString
Public Class ConvertConcatenationToInterpolatedStringTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace) As CodeRefactoringProvider
Return New VisualBasicConvertConcatenationToInterpolatedStringRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMissingOnSimpleString() As Task
Await TestMissingAsync(
"
Public Class C
Sub M()
dim v = [||]""string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringOnLeft() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = [||]""string"" & 1
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""string{1}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestRightSideOfString() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = ""string""[||] & 1
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""string{1}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithStringOnRight() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = 1 & [||]""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1}string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithComplexExpressionOnLeft() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithTrivia1() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string"" ' trailing trivia
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string"" ' trailing trivia
End Sub
End Class", compareTokens:=False)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithComplexExpressions() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = 1 + 2 & [||]""string"" & 3 & 4
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""{1 + 2}string{3}{4}""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithEscapes1() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = ""\r"" & 2 & [||]""string"" & 3 & ""\n""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""\r{2}string{3}\n""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithEscapes2() As Task
Await TestAsync(
"
Public Class C
Sub M()
dim v = ""\\r"" & 2 & [||]""string"" & 3 & ""\\n""
End Sub
End Class",
"
Public Class C
Sub M()
dim v = $""\\r{2}string{3}\\n""
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithOverloadedOperator() As Task
Await TestAsync(
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = 1 & [||]""string"" & d
End Sub
End Class",
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = $""{1}string"" & d
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestWithOverloadedOperator2() As Task
Await TestMissingAsync(
"
public class D
public shared operator&(D d, string s) as boolean
end operator
public shared operator&(string s, D d) as boolean
end operator
end class
Public Class C
Sub M()
dim d as D = nothing
dim v = d & [||]""string"" & 1
End Sub
End Class")
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/EditorFeatures/VisualBasicTest/ConvertToInterpolatedString/ConvertConcatenationToInterpolatedStringTests.vb
|
Visual Basic
|
apache-2.0
| 5,616
|
' Copyright (c) .NET Foundation. All rights reserved.
' Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Runtime.CompilerServices
Friend Class BatchUpdateString
Private Const MaxBatch As Integer = 500
Private Shared ReadOnly Queries As String() = New String(499) {}
Public Shared ReadOnly Property Strings As IList(Of BatchUpdateString) = Enumerable.Range(0, MaxBatch).[Select](Function(i) New BatchUpdateString With {
.Id = $"Id_{i}",
.Random = $"Random_{i}",
.BatchSize = i
}).ToArray()
Private Property BatchSize As Integer
Public Property Id As String
Public Property Random As String
Public ReadOnly Property UpdateQuery As String
Get
Return If(Queries(BatchSize), CreateQuery(BatchSize))
End Get
End Property
<MethodImpl(MethodImplOptions.NoInlining)>
Private Function CreateQuery(ByVal batchSize As Integer) As String
Dim sb = StringBuilderCache.Acquire()
For Each q In Enumerable.Range(0, batchSize + 1).[Select](Function(i) $"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};")
sb.Append(q)
Next
Dim query = sb.ToString()
Queries(batchSize) = query
Return query
End Function
Public Shared Sub Initalize()
Observe(Strings(0).UpdateQuery)
Observe(Strings(4).UpdateQuery)
Observe(Strings(9).UpdateQuery)
Observe(Strings(14).UpdateQuery)
Observe(Strings(19).UpdateQuery)
End Sub
<MethodImpl(MethodImplOptions.NoInlining)>
Private Shared Sub Observe(ByVal query As String)
End Sub
End Class
|
zloster/FrameworkBenchmarks
|
frameworks/VB/aspnetcore/Benchmarks/Data/BatchUpdateString.vb
|
Visual Basic
|
bsd-3-clause
| 1,726
|
' 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.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Binding info for attribute syntax and expressions that are part of a attribute.
''' </summary>
Friend NotInheritable Class AttributeSemanticModel
Inherits MemberSemanticModel
Private Sub New(root As VisualBasicSyntaxNode, binder As Binder, Optional parentSemanticModelOpt As SyntaxTreeSemanticModel = Nothing, Optional speculatedPosition As Integer = 0, Optional ignoreAccessibility As Boolean = False)
MyBase.New(root, binder, parentSemanticModelOpt, speculatedPosition, ignoreAccessibility)
End Sub
''' <summary>
''' Creates an AttributeSemanticModel that allows asking semantic questions about an attribute node.
''' </summary>
Friend Shared Function Create(binder As AttributeBinder, Optional ignoreAccessibility As Boolean = False) As AttributeSemanticModel
Return New AttributeSemanticModel(binder.Root, binder, ignoreAccessibility:=ignoreAccessibility)
End Function
''' <summary>
''' Creates a speculative AttributeSemanticModel that allows asking semantic questions about an attribute node that did not appear in the original source code.
''' </summary>
Friend Shared Function CreateSpeculative(parentSemanticModel As SyntaxTreeSemanticModel, root As VisualBasicSyntaxNode, binder As Binder, position As Integer) As AttributeSemanticModel
Debug.Assert(parentSemanticModel IsNot Nothing)
Debug.Assert(root IsNot Nothing)
Debug.Assert(binder IsNot Nothing)
Debug.Assert(binder.IsSemanticModelBinder)
Return New AttributeSemanticModel(root, binder, parentSemanticModel, position)
End Function
Friend Overrides Function Bind(binder As Binder, node As VisualBasicSyntaxNode, diagnostics As DiagnosticBag) As BoundNode
Debug.Assert(binder.IsSemanticModelBinder)
Dim boundNode As boundNode
Select Case node.Kind
Case SyntaxKind.Attribute
boundNode = binder.BindAttribute(DirectCast(node, AttributeSyntax), diagnostics)
Return boundNode
Case SyntaxKind.IdentifierName, SyntaxKind.QualifiedName
' Special binding for attribute type to account for the implicit Attribute suffix.
If SyntaxFacts.IsAttributeName(node) Then
Dim name = DirectCast(node, NameSyntax)
boundNode = binder.BindNamespaceOrTypeExpression(name, diagnostics)
Return boundNode
End If
End Select
boundNode = MyBase.Bind(binder, node, diagnostics)
Return boundNode
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, initializer As EqualsValueSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelCore(parentModel As SyntaxTreeSemanticModel, position As Integer, statement As ExecutableStatementSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
speculativeModel = Nothing
Return False
End Function
Friend Overrides Function TryGetSpeculativeSemanticModelForMethodBodyCore(parentModel As SyntaxTreeSemanticModel, position As Integer, method As MethodBlockBaseSyntax, <Out> ByRef speculativeModel As SemanticModel) As Boolean
speculativeModel = Nothing
Return False
End Function
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/AttributeSemanticModel.vb
|
Visual Basic
|
apache-2.0
| 4,037
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.1433
'
' 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 NEvoWeb.Modules.NB_Store
Partial Public Class ProductSearchSettings
'''<summary>
'''plModuleCombo control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plModuleCombo As Global.System.Web.UI.UserControl
'''<summary>
'''txtModule control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtModule As Global.System.Web.UI.WebControls.Label
'''<summary>
'''cboModule control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents cboModule As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''plGoCheck control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plGoCheck As Global.System.Web.UI.UserControl
'''<summary>
'''chkGo control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkGo As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plImgPath control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plImgPath As Global.System.Web.UI.UserControl
'''<summary>
'''txtImagePath control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtImagePath As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''plSearchCheck control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSearchCheck As Global.System.Web.UI.UserControl
'''<summary>
'''chkSearchImage control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents chkSearchImage As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''plSImgPath control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents plSImgPath As Global.System.Web.UI.UserControl
'''<summary>
'''txtSImagePath control.
'''</summary>
'''<remarks>
'''Auto-generated field.
'''To modify move field declaration from designer file to code-behind file.
'''</remarks>
Protected WithEvents txtSImagePath As Global.System.Web.UI.WebControls.TextBox
End Class
End Namespace
|
skamphuis/NB_Store
|
ProductSearchSettings.ascx.designer.vb
|
Visual Basic
|
mit
| 4,143
|
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim documents As SolidEdgeFramework.Documents = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim refPlanes As SolidEdgePart.RefPlanes = Nothing
Dim profileSets As SolidEdgePart.ProfileSets = Nothing
Dim profileSet As SolidEdgePart.ProfileSet = Nothing
Dim profiles As SolidEdgePart.Profiles = Nothing
Dim profile As SolidEdgePart.Profile = Nothing
Dim arcs2d As SolidEdgeFrameworkSupport.Arcs2d = Nothing
Dim arc2d1 As SolidEdgeFrameworkSupport.Arc2d = Nothing
Dim arc2d2 As SolidEdgeFrameworkSupport.Arc2d = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
documents = application.Documents
partDocument = CType(documents.Add("SolidEdge.PartDocument"), SolidEdgePart.PartDocument)
refPlanes = partDocument.RefPlanes
profileSets = partDocument.ProfileSets
profileSet = profileSets.Add()
profiles = profileSet.Profiles
profile = profiles.Add(refPlanes.Item(1))
arcs2d = profile.Arcs2d
arc2d1 = arcs2d.AddByCenterStartEnd(0.233, 0.149, 0.233, 0.278, 0.338, 0.324)
arc2d2 = arcs2d.AddByCenterStartEnd(0.325, 0.16, 0.269, 0.293, 0.158, 0.34)
Dim zOrder = arc2d1.ZOrder
arc2d1.BringForward()
zOrder = arc2d1.ZOrder
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgeFrameworkSupport.Arc2d.BringForward.vb
|
Visual Basic
|
mit
| 2,268
|
Imports KOTSMSAPI
Imports System.Text.RegularExpressions
Imports EDM.Holmes.Cust
Imports System.Collections.ObjectModel
Imports System.Collections.Generic
Imports System.Text
Imports EDM.Holmes.VO.User
Imports EDM.Holmes.Tools
Imports EDM.Holmes.VO.Work
Imports EDM.Holmes.Mail
Imports EDM.Holmes.Mail.SendType
Imports EDM.Holmes.VO.Sample
Imports System.Configuration
Imports EDM.Holmes.Sms
''' <summary>
''' Goverment SMS
''' </summary>
''' <remarks></remarks>
Public Class SMS
'¿ï¾Üªº½d¥»¦WºÙ
Private selectedSampName As String
'¿ï¾Üªº½d¥»ID
Private selectedSampId As String
'¿ï¾Üªº½d¥»¤º®e
Private selectedSampContent As String
'¿ï¾Üªº±M®×¦WºÙ
Private selectedPrjName As String
'¿ï¾Üªº«È¤á¼Æ¥Ø
Private CustCnt As Integer
'Àx¦s¤â¾÷²M³æ
'Private custMobileLst As Collection(Of String)
Private custMobileLst As Collection
'Àx¦s¾úµ{¬ö¿ý
Public workHistory As New WorkHistory
'Àx¦sSQL SERVERªºSerial record
Private ReturnSerial As Integer
'if lbl_PrjName value changed
Public Event PrjName_Chg(ByVal prjName As String)
Public Event CustCnt_Chg(ByVal cnt As Integer)
'Àx¦sÁ`µ²ªG
Dim sb As StringBuilder
Private Sub SMS_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.lbl_PrjName.Text = Me._SelectedPrjName
Me.lbl_SampName.Text = Me._SelectedSampName
End Sub
Private Sub SMS_CustCnt_Chg(ByVal cnt As Integer) Handles Me.CustCnt_Chg
'Me.lbl_CustCnt.Visible = True
'Me.lbl_CustCnt.Text = String.Format("({0})¦W«È¤á", cnt)
Dim msg As MsgBoxResult = MsgBox(String.Format("µo°e²°T²M³æ¦@¦³{0}¦W«È¤á,½ÐÄ~Äò¿é¤J²°T¤º®e", cnt))
End Sub
''' <summary>
''' ±Ò°Êµo°Ê²°T
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub BackgroundWorker1_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If Me._CustMobileLst.Count > 0 Then
Me.SendSMS()
'Àx¦s¦Ü±H¥ó³Æ¥÷--------------------------------------
Dim bp As New EDM.Holmes.Mail.MailBp(Me.lbl_PrjName.Text.Trim, Me.txt_Content.Text.Trim, "")
bp.SaveToSms()
'----------------------------------------------------
Else
MsgBox("¨S¦³¥ô¦ó³q°T¦W³æ!")
Exit Sub
End If
End Sub
''' <summary>
''' Send
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub btn_Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Send.Click
Dim msg As MsgBoxResult = MsgBox("½T©wn±Hµo²°T¶Ü?", MsgBoxStyle.YesNo)
If msg = MsgBoxResult.Yes Then
'¬O§_¦s¤J±Æµ{©ÎªÌ½d¥»
IsSaveToWorkArrangeOrSamp()
'¤¹³\¦^³ø¶i«×
BackgroundWorker1.WorkerReportsProgress = True
'¤¹³\¨ú®ø
BackgroundWorker1.WorkerSupportsCancellation = True
'±Ò°ÊI´º§@·~
If Me.BackgroundWorker1.IsBusy Then
MsgBox("¤u§@¤w¦b¶i¦æ¤¤.....")
Exit Sub
Else
Dim ret As Collection = Me._CustMobileLst
If ret.Count > 0 Then
Me.progress.Maximum = ret.Count - 1
End If
BackgroundWorker1.RunWorkerAsync()
End If
End If
End Sub
''' <summary>
''' ±H¥X²°T 2011/11/06
''' </summary>
Public Sub SendSMS()
'add evt handler if application happend to close
'AddHandler Application.ApplicationExit, AddressOf AppExit
'¶}©l®É¶¡-----------------------------
workHistory._StartTime = DateTime.Now
workHistory._PrjName = DateTime.Now & "±HµoSMS"
workHistory._BpType = SendTypeFactory.SendSms
'-------------------------------------
'Àx¦sµ²ªG
sb = New StringBuilder
'pºâ±H¥XÁ`¼Æ not use
Dim cnt As Integer
'---------------¨ú±oSMS±b±K-------------------
Dim y As New User
y = y.getUserSMS(User.LoginId, User.LoginPwd)
Dim x As New KOT_SMSAPI
x.username = y._SMSLoginId
x.password = y._SMSLoginPwd
If String.IsNullOrEmpty(x.username) Or String.IsNullOrEmpty(x.password) Then
MsgBox("½Ð³]©w²°T±b¸¹±K½X")
Exit Sub
End If
'---------------¨ú±oSMS±b±K-------------------
'WorkHistory-----------------------------
'¹w©w¶Ç°eµ§¼Æ()
workHistory._PlanTotalCnt = Me._CustMobileLst.count
'---------------¶Ç°e¸ê®Æ¨ìSQL Server-------------------------------------
Dim smsWs As New EDM.SmsWs.SMS
ReturnSerial = smsWs.InsertSMS("sp", _
"Á`³¡", _
workHistory._PrjName, _
workHistory._StartTime, _
workHistory._PlanTotalCnt)
'------------------------------------------------------------------------
' Judge which instance in the collection , govermentsms or shopsms?
Dim ret As Collection = Me._CustMobileLst
Dim sms As MySMS = Nothing
If ret.Count > 0 Then
sms = MySMS.SmsFactory(ret.Item(1))
End If
'Try
sms.Send(ret, Me.txt_Content.Text, sb, x, workHistory, cnt, Me.BackgroundWorker1)
'Catch ex As Exception
'¤£¥i¥H°µÄÀ©ñ¸ê·½°Ê§@,§_«h·|¼vÅT¨ì±µ¤U¨Óªº±Hµo°Ê§@
'sb = Nothing
'x = Nothing
'workHistory = Nothing
'smsWs = Nothing
'End Try
End Sub
''' <summary>
''' µo°e²°T§¹¦¨«á
''' ¬°Á×§K¤¤Â_,¨Ï¥Îtry catch ¨Ó§PÂ_,¨Ã¥B¼g¤J°T®§,¦Ó¤£¥Îmsgbox¥´Â_
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
'Àx¦sµ²§ô®É¶¡
workHistory._EndTime = DateTime.Now
'Àx¦s¤u§@¾úµ{---------------------------------------------------
Try
workHistory.Save()
'workHistory = Nothing ' fuck you
Catch ex As Exception
sb.Append("Error_Code:281_SMS_Error" & vbCrLf & ex.Message)
End Try
'Àx¦s¤u§@¾úµ{---------------------------------------------------
'Send data to Sql server---------------------------------------
Try
Dim smsWs As New EDM.SmsWs.SMS
smsWs.UptSMS(Me.ReturnSerial, workHistory._EndTime, workHistory._SuccessCnt, workHistory._FailCnt)
smsWs = Nothing
Catch ex As Exception
sb.Append("Error_Code:253_SMS_Error" & vbCrLf & ex.Message)
End Try
'Send data to Sql server---------------------------------------
'test
'Dim test As String = sb.ToString
'-------«È»s°T®§-----------------------------------------------------------
'ex:
'0919xxxxxx ¦¨¥\
'0919xxxxxx ¥¢±Ñ
'Á`µ§¼Æ:
'¦¨¥\µ§¼Æ:
'¥¢±Ñµ§¼Æ:
'---------------------------------------------------------------------------
'¹w³] Message Form ªº message and hash field
'My.Forms.Message.txt_Message.Text = sb.ToString & vbCrLf & "Á`µ§¼Æ:" & _
'workHistory._SuccessCnt + workHistory._FailCnt & vbCrLf & _
'"¦¨¥\µ§¼Æ" & workHistory._SuccessCnt & _
'vbCrLf & "¥¢±Ñµ§¼Æ:" & workHistory._FailCnt & _
'vbCrLf
'2011/11/10
'My.Forms.Message.txt_Message.Text = "Á`µ§¼Æ:" & _
'workHistory._SuccessCnt + workHistory._FailCnt & vbCrLf & _
'"¦¨¥\µ§¼Æ" & workHistory._SuccessCnt & _
'vbCrLf & "¥¢±Ñµ§¼Æ:" & workHistory._FailCnt & _
'vbCrLf
'---------------------------------------------------------------------------
'¶Çȵ¹Message Form·Ç³Æ°µ¦ô»ù³æ²Îp
'My.Forms.Message._Hash = CustomMsg(sb.ToString)
'My.Forms.Message._Message = sb.ToString
'My.Forms.Message.txt_Message.Text = sb.ToString
MsgBox("¤u§@¤w§¹¦¨")
Me.progress.Value = 0
My.Forms.Message.Show()
'Me._CustMobileLst = Nothing
'workHistory = Nothing
End Sub
''' <summary>
''' µ²§ô¤u§@«á²£¥Íªº°T®§®æ¦¡
''' </summary>
''' <param name="msg"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function CustomMsg(ByVal msg As String) As Hashtable
'¤T¥Á©±/097056432/¶Ç°e¦¨¥\¡A§Ç¸¹¬°¡G33865190
'¤T¥Á©±/097056432/-5:B Number¹H¤Ï³W«h ±µ¦¬ºÝ ªù¸¹¿ù»~
Dim hash As New Hashtable
Dim shopname As String = ""
Dim key As String = ""
Dim myRegex As New Regex("^\w{3}\/[0-9]*\/¶Ç°e¦¨¥\", RegexOptions.Multiline)
'Dim msg2 As String() = msg.Split(vbCrLf)
Dim msg2 As String() = Split(msg, vbCrLf)
For Each msg3 As String In msg2
Try
If Not String.IsNullOrEmpty(msg3) Then
'§PÂ_¦³µL²Å¦X¦Ûq®æ¦¡,¥H¨¾¤¤¶¡·|¦³Exceptionµ¥¿ù»~°T®§
'¥up¤J¦¨¥\¦¸¼Æ
If myRegex.IsMatch(msg3) Then
msg3 = msg3.Trim
Dim index2 As Integer = msg3.IndexOf("/")
'§ä¥X¦Ûq®æ¦¡ªº¤À©±¦WºÙ
If Not index2 = -1 Then
shopname = msg3.Substring(0, index2)
End If
'find sms id
Dim index As Integer = msg3.IndexOf("¡G")
If Not index = -1 Then
key = msg3.Substring(index + 1)
End If
If hash.ContainsKey(key) Then
Else
hash.Add(key, shopname)
End If
End If
End If
Catch ex As Exception
MsgBox("Error_Code:420_SMS_Error" & vbCrLf & ex.Message)
End Try
Next
'2011/11/7
'Dim hash As New Hashtable
'Dim myRegex As New Regex("^\w{3}\/[0-9]*\/¶Ç°e¦¨¥\", RegexOptions.Multiline)
'Dim msg2 As String() = msg.Split(vbCrLf)
'For Each msg3 As String In msg2
' '§PÂ_¦³µL²Å¦X¶Ç°e¦¨¥\ªº®æ¦¡,¥H¨¾¤¤¶¡·|¦³Exceptionµ¥¿ù»~°T®§
' '¥up¤J¦¨¥\¦¸¼Æ
' If myRegex.IsMatch(msg3) Then
' '¨¾¤î²Ä¤@¦C³£·|²£¥Í¦h¾lªÅ®æ
' msg3 = msg3.Trim
' Dim index As Integer = msg3.IndexOf("/")
' '§ä¥X°T®§¸Ìªº¤À©±¦WºÙ
' Dim shopname As String = msg3.Substring(0, index)
' 'Y¤w¸g¦³³o¤À©±ºÙ¦s¦b,«h¨ú¥XȨå[1,YµL,«h·s¼W¤À©±¦WºÙªº key
' If hash.ContainsKey(shopname) Then
' Dim i As Integer = hash.Item(shopname)
' i = i + 1
' hash.Item(shopname) = i
' Else
' hash.Add(shopname, 1)
' End If
' End If
'Next
Return hash
End Function
''' <summary>
''' when form closed
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub SMS_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
Dim msg As MsgBoxResult = Nothing
'±Ò°ÊI´º§@·~
If Me.BackgroundWorker1.IsBusy Then
msg = MsgBox("¤u§@¶i¦æ¤¤,±z½T©wn¨ú®ø¶Ü?", MsgBoxStyle.YesNoCancel)
If msg = MsgBoxResult.Yes Then
Me.BackgroundWorker1.CancelAsync()
Me.Close()
End If
End If
End Sub
Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
''I´º§@·~¶i«×¦^³øµ{§Ç()
'txt_Message.Text = e.UserState '§e²{¶Ç°e°T®§
'Label9.Text = "¤w¶Ç°e " & e.ProgressPercentage & "µ§" '§e²{¶Ç°eµ§¼Æ
'¨ú±o±H¥XÁ`¼Æ
'workHistory._TotalCnt = e.ProgressPercentage
Me.progress.Increment(e.ProgressPercentage)
End Sub
'¤¤¤î§@·~
Private Sub btn_Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cancel.Click
If Me.BackgroundWorker1.CancellationPending Then
Me.BackgroundWorker1.CancelAsync()
Me.Close()
Else
Me.Close()
End If
End Sub
'pºâ¼Æ¦r¦h¹è
Private Sub txt_Content_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_Content.TextChanged
Me.lbl_Strlength.Text = "¦r¼Æ" & txt_Content.Text.Length.ToString
End Sub
''' <summary>
''' Åã¥Ü¬O§_¤u§@¬O§_¦s¤J±Æµ{©ÎªÌ½d¥»
''' </summary>
''' <remarks></remarks>
Private Sub IsSaveToWorkArrangeOrSamp()
'Dim btn As Button = My.Forms.IsSaveToWorkOrSamp.btn_AddSamp
'Dim btn1 As Button = My.Forms.IsSaveToWorkOrSamp.btn_AddWork
'AddHandler btn.Click, AddressOf AddSample
'AddHandler btn1.Click, AddressOf AddWork
'My.Forms.IsSaveToWorkOrSamp.Show()
End Sub
'·s¼W½d¥»
Private Sub AddSample(ByVal sender As Object, ByVal e As EventArgs)
Dim samp As New Saple
samp._SampName = DateTime.Now.ToString
samp._SampContent = Me.txt_Content.Text.Trim
samp._SampCat = Saple.SmsSamp
Try
samp.AddSamp(samp)
Catch ex As Exception
MsgBox("Error_Code:460_SMS_Error" & vbCrLf & ex.Message)
Exit Sub
End Try
My.Forms.IsSaveToWorkOrSamp.Close()
End Sub
'·s¼W±Æµ{
Private Sub AddWork(ByVal sender As Object, ByVal e As EventArgs)
My.Forms.AddWork.Show()
My.Forms.IsSaveToWorkOrSamp.Close()
End Sub
''' <summary>
'''¿ï¾Ü³q°T¿ý
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ShowPrj.Click
My.Forms.AddProject.TopMost = True
My.Forms.AddProject.Show()
My.Forms.AddProject.StartPosition = FormStartPosition.CenterScreen
'My.Forms.AddProject.btn_ImportCust.Visible = False
'²°T«ö¶s
'My.Forms.AddProject.ToolStripButton1.Visible = False
'remove button named close
My.Forms.AddProject.ToolStrip2.Items.RemoveAt(2)
'add Button named ±H¥X²°T-----------------------------------------------------
Dim control As New ControlTool
Dim btn As ToolStripButton = control.AddToolsBtn("±H¥X²°T", ControlTool.ImgButton, "Images\Email.png")
My.Forms.AddProject.ToolStrip2.Items.Add(btn)
AddHandler btn.Click, AddressOf AddPrj_Click
'-----------------------------------------------------
'add Button named close ------------------------------
Dim btn2 As ToolStripButton = control.AddToolsBtn("Ãö³¬", ControlTool.ImgButton, "Images\Delete.png")
My.Forms.AddProject.ToolStrip2.Items.Add(btn2)
AddHandler btn2.Click, AddressOf CloseAddPrject_Click
'-----------------------------------------------------
End Sub
''' <summary>
''' close AddProject Form
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub CloseAddPrject_Click(ByVal sender As Object, ByVal e As EventArgs)
My.Forms.AddProject.Close()
End Sub
''' <summary>
''' ¥[¤J³q°T¿ý¨ì¥Ø«eªº±Hµo²°T¦W³æ
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub AddPrj_Click(ByVal sender As Object, ByVal e As EventArgs)
'Reset-------------------------
'Me._CustMobileLst = Nothing
'Me._CustCnt = 0
'Reset-------------------------
'¨ú±o¦óºØÃþ«¬«È¤á
Dim cust As OrginCust = CustFactory.getCustTpe(CustFactory.goverment)
'®Ú¾Ú«È¤áÃþ«¬¨ú±o¦óºØÂ²°TÃþ«¬
Dim sms As MySMS = MySMS.SmsFactory(cust)
'Dim ret As Collection(Of GovermentCust) = cust.getCheckedMobileLst(My.Forms.AddProject.DataGridView1)
'Dim sms As MySMS = MySMS.SmsFactory(cust)
Dim ret As Collection = sms.getMobileLst(My.Forms.AddProject.DataGridView1)
Dim receiver As String = sms.mobileLstToString
'²Ö¥[³q°T²M³æ,2012/2/6 §ï¦¨¤£²Ö¥[
Me._SelectedPrjName = receiver
Me._CustMobileLst = ret
Me._CustCnt = ret.Count
'RaiseEvent CustCnt_Chg(ret.Count)
My.Forms.AddProject.Close()
End Sub
''' <summary>
''' «ö¤U¿ï¾Ü±M®×ªí³æ«áªº°Ê§@,³]©wCust Mobile List
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub getCustLst(ByVal sender As Object, ByVal e As EventArgs)
Dim cust As EDM.Holmes.Cust.Cust
Dim ret As Collection(Of String) = Nothing
If Not String.IsNullOrEmpty(Me.lbl_PrjId.Text) Then
cust = New EDM.Holmes.Cust.Cust
ret = cust.getMobilelst(Me.lbl_PrjId.Text)
Me._CustMobileLst = ret
End If
End Sub
''' <summary>
''' ¿ï¾Ü½d¥»
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ChooseSamp.Click
'My.Forms.SampleMaintain.Show()
My.Forms.SMSSamp.Show()
End Sub
''' <summary>
''' ¿ï¾Ü©Ò¦³«È¤á
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub btn_AllCust_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_AllCust.Click
Dim ret As Collection(Of String) = Nothing
Dim sb As New StringBuilder
Dim cust As OrginCust = CustFactory.getCustTpe(CustFactory.goverment)
Try
ret = cust.getCustMobile
Catch ex As Exception
MsgBox("Error_Code:463_SMS_Error")
Exit Sub
End Try
For Each mobile As String In ret
sb.Append(IIf(mobile <> "", mobile & ",", ""))
Next
Me._CustCnt = ret.Count
'RaiseEvent CustCnt_Chg(ret.Count)
'Me.lbl_PrjName.Text = String.Format("({0}):{1}", ret.Count, sb.ToString)
Me.lbl_PrjName.Text = sb.ToString
'Me._SelectedPrjName = sb.ToString
End Sub
''' <summary>
''' when contact list has changed
''' </summary>
''' <param name="prjName"></param>
''' <remarks></remarks>
Private Sub SMS_PrjName_Chg(ByVal prjName As String) Handles Me.PrjName_Chg
'Me.lbl_PrjName.Text = String.Format("({0}):{1}", custCnt, prjName)
Me.lbl_PrjName.Text = prjName
End Sub
''' <summary>
''' clear contact list
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub btn_ClearContact_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_ClearContact.Click
Me.lbl_PrjName.Text = ""
'Me.custMobileLst.Clear()
Me._SelectedPrjName = ""
RaiseEvent CustCnt_Chg(0)
End Sub
Public Property _SelectedSampName()
Get
Return Me.selectedSampName
End Get
Set(ByVal value)
Me.selectedSampName = value
End Set
End Property
Public Property _SelectedSampId()
Get
Return Me.selectedSampId
End Get
Set(ByVal value)
Me.selectedSampId = value
End Set
End Property
Public Property _SelectedSampContent()
Get
Return Me.selectedSampContent
End Get
Set(ByVal value)
Me.selectedSampContent = value
End Set
End Property
Public Property _SelectedPrjName()
Get
Return Me.selectedPrjName
End Get
Set(ByVal value)
Me.selectedPrjName = value
RaiseEvent PrjName_Chg(Me.selectedPrjName)
End Set
End Property
Public Property _CustMobileLst()
Get
Return Me.custMobileLst
End Get
Set(ByVal value)
Me.custMobileLst = value
End Set
End Property
Public Property _CustCnt()
Get
Return Me.CustCnt
End Get
Set(ByVal value)
'Dim oldvalue As Integer = 0
'oldvalue = Me.CustCnt
Me.CustCnt = value
RaiseEvent CustCnt_Chg(value)
End Set
End Property
''' <summary>
''' ¥[¤J«È¤á
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
Try
Me.AddPrj_Click(sender, e)
Catch ex As Exception
'Á×§Kµo¥ÍµLŪ¨ú¨ì«È¤áÀɮתº¿ù»~
MsgBox(ex.Message)
Exit Sub
End Try
End Sub
''' <summary>
''' ¬d¸ß¾ú¥v°O¿ý
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
My.Forms.Message.StartPosition = FormStartPosition.CenterScreen
My.Forms.Message.ShowDialog()
End Sub
End Class
|
holmes2136/SEDM
|
GSEDM/SMS/SMS.vb
|
Visual Basic
|
mit
| 22,131
|
Public Class ParamRepVentas
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Me.Page.IsPostBack = False Then
Me.RadDatePicker1.SelectedDate = Date.Parse("01/" + Session("Mes").ToString + "/" + Session("Anio").ToString)
Me.RadDatePicker2.SelectedDate = Date.Parse(Session("Fecha"))
End If
End Sub
Protected Sub ImageButton1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
Dim cadena_java As String
cadena_java = "<script type='text/javascript'> " & _
" window.open('ReporteVentas.aspx?fechaInicio=" + Me.RadDatePicker1.SelectedDate.ToString + "&fechaFin=" + Me.RadDatePicker2.SelectedDate.ToString + "' ); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "Cerrar", cadena_java.ToString, False)
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Contabilidad/Formularios/ParamRepVentas.aspx.vb
|
Visual Basic
|
mit
| 1,038
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rRDocumentosCompras_Mensuales"
'-------------------------------------------------------------------------------------------'
Partial Class rRDocumentosCompras_Mensuales
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), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
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 = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(9))
Dim lcParametro9Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(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(" SELECT ")
loComandoSeleccionar.AppendLine(" CASE WHEN Requisiciones.Documento <> '' AND Renglones_Requisiciones.renglon <= 1 THEN 1 ELSE 0 END AS Doc_Req, ")
loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Can_Art1 AS Can_Art1_Req, ")
loComandoSeleccionar.AppendLine(" Renglones_Requisiciones.Mon_Net AS Mon_Net_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_DPro, ")
loComandoSeleccionar.AppendLine(" datepart(year, Requisiciones.Fec_Ini) AS Año, ")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Requisiciones.Fec_Ini) AS Mes, ")
loComandoSeleccionar.AppendLine(" Requisiciones.Fec_Ini AS Fecha ")
loComandoSeleccionar.AppendLine(" INTO #tempRequisiciones ")
loComandoSeleccionar.AppendLine(" FROM Requisiciones ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Requisiciones ON Renglones_Requisiciones.Documento = Requisiciones.Documento ")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Requisiciones.Cod_Art ")
loComandoSeleccionar.AppendLine(" --ORDER BY Requisiciones.Fec_Ini ")
loComandoSeleccionar.AppendLine(" WHERE ")
loComandoSeleccionar.AppendLine(" Requisiciones.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art Between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep Between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Requisiciones.Cod_Alm Between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar Between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Requisiciones.Cod_Pro Between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Requisiciones.Cod_Ven Between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Requisiciones.Status IN (" & lcParametro7Desde & ")")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_tip Between " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_cla Between " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Requisiciones.Cod_Suc Between " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Req, ")
loComandoSeleccionar.AppendLine(" CASE WHEN Ordenes_Compras.Documento <> '' AND Renglones_oCompras.renglon <= 1 THEN 1 ELSE 0 END AS Doc_OC, ")
loComandoSeleccionar.AppendLine(" Renglones_oCompras.Can_Art1 AS Can_Art1_OC, ")
loComandoSeleccionar.AppendLine(" Renglones_oCompras.Mon_Net AS Mon_Net_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_DPro, ")
loComandoSeleccionar.AppendLine(" datepart(YEAR, Ordenes_Compras.Fec_Ini) AS Año, ")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Ordenes_Compras.Fec_Ini) AS Mes, ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Fec_Ini AS Fecha ")
loComandoSeleccionar.AppendLine(" INTO #tempOrdenes_Compras ")
loComandoSeleccionar.AppendLine(" FROM Ordenes_Compras ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_oCompras ON Renglones_oCompras.Documento = Ordenes_Compras.Documento ")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_oCompras.Cod_Art ")
loComandoSeleccionar.AppendLine(" --ORDER BY Ordenes_Compras.Fec_Ini ")
loComandoSeleccionar.AppendLine(" WHERE ")
loComandoSeleccionar.AppendLine(" Ordenes_Compras.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art Between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep Between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_oCompras.Cod_Alm Between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar Between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Ordenes_Compras.Cod_Pro Between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Ordenes_Compras.Cod_Ven Between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Ordenes_Compras.Status IN (" & lcParametro7Desde & ")")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_tip Between " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_cla Between " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Ordenes_Compras.Cod_Suc Between " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_OC, ")
loComandoSeleccionar.AppendLine(" CASE WHEN Compras.Documento <> '' AND Renglones_Compras.renglon <= 1 THEN 1 ELSE 0 END AS Doc_Com, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Can_Art1 AS Can_Art1_Com, ")
loComandoSeleccionar.AppendLine(" Renglones_Compras.Mon_Net AS Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_DPro, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_DPro, ")
loComandoSeleccionar.AppendLine(" datepart(year, Compras.Fec_Ini) AS Año, ")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Compras.Fec_Ini) AS Mes, ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini AS Fecha ")
loComandoSeleccionar.AppendLine(" INTO #tempCompras ")
loComandoSeleccionar.AppendLine(" FROM Compras ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_Compras ON Renglones_Compras.Documento = Compras.Documento ")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_Compras.Cod_Art ")
loComandoSeleccionar.AppendLine(" --ORDER BY Compras.Fec_Ini ")
loComandoSeleccionar.AppendLine(" WHERE ")
loComandoSeleccionar.AppendLine(" Compras.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art Between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep Between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_Compras.Cod_Alm Between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar Between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Pro Between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Ven Between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Status IN (" & lcParametro7Desde & ")")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_tip Between " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_cla Between " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Compras.Cod_Suc Between " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Req, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_OC, ")
loComandoSeleccionar.AppendLine(" CAST(0 AS CHAR(10)) AS Doc_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Can_Art1_Com, ")
loComandoSeleccionar.AppendLine(" CAST(0.0 AS DECIMAL) AS Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" CASE WHEN Devoluciones_Proveedores.Documento <> '' AND Renglones_dProveedores.renglon <= 1 THEN 1 ELSE 0 END AS Doc_DPro, ")
loComandoSeleccionar.AppendLine(" Renglones_dProveedores.Can_Art1 AS Can_Art1_DPro, ")
loComandoSeleccionar.AppendLine(" Renglones_dProveedores.Mon_Net AS Mon_Net_DPro, ")
loComandoSeleccionar.AppendLine(" datepart(year, Devoluciones_Proveedores.Fec_Ini) AS Año, ")
loComandoSeleccionar.AppendLine(" DATEPART(MONTH, Devoluciones_Proveedores.Fec_Ini) AS Mes, ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Fec_Ini AS Fecha ")
loComandoSeleccionar.AppendLine(" INTO #tempDevoluciones ")
loComandoSeleccionar.AppendLine(" FROM Devoluciones_Proveedores ")
loComandoSeleccionar.AppendLine(" JOIN Renglones_dProveedores ON Renglones_dProveedores.Documento = Devoluciones_Proveedores.Documento ")
loComandoSeleccionar.AppendLine(" JOIN Articulos ON Articulos.Cod_Art = Renglones_dProveedores.Cod_Art ")
loComandoSeleccionar.AppendLine(" --ORDER BY Devoluciones_Proveedores.Fec_Ini ")
loComandoSeleccionar.AppendLine(" WHERE ")
loComandoSeleccionar.AppendLine(" Devoluciones_Proveedores.Fec_Ini Between " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Art Between " & lcParametro1Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro1Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep Between " & lcParametro2Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro2Hasta)
loComandoSeleccionar.AppendLine(" AND Renglones_dProveedores.Cod_Alm Between " & lcParametro3Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro3Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Mar Between " & lcParametro4Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro4Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Cod_Pro Between " & lcParametro5Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro5Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Cod_Ven Between " & lcParametro6Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro6Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Status IN (" & lcParametro7Desde & ")")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_tip Between " & lcParametro8Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro8Hasta)
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_cla Between " & lcParametro9Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro9Hasta)
loComandoSeleccionar.AppendLine(" AND Devoluciones_Proveedores.Cod_Suc Between " & lcParametro10Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro10Hasta)
loComandoSeleccionar.AppendLine(" SELECT Doc_Req, Can_Art1_Req, Mon_Net_Req, Doc_OC, Can_Art1_OC, Mon_Net_OC, Doc_Com, Can_Art1_Com, Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" Doc_DPro, Can_Art1_DPro, Mon_Net_DPro, Año, Mes ")
loComandoSeleccionar.AppendLine(" FROM #tempRequisiciones ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT Doc_Req, Can_Art1_Req, Mon_Net_Req, Doc_OC, Can_Art1_OC, Mon_Net_OC, Doc_Com, Can_Art1_Com, Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" Doc_DPro, Can_Art1_DPro, Mon_Net_DPro, Año, Mes ")
loComandoSeleccionar.AppendLine(" FROM #tempOrdenes_Compras ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT Doc_Req, Can_Art1_Req, Mon_Net_Req, Doc_OC, Can_Art1_OC, Mon_Net_OC, Doc_Com, Can_Art1_Com, Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" Doc_DPro, Can_Art1_DPro, Mon_Net_DPro, Año, Mes ")
loComandoSeleccionar.AppendLine(" FROM #tempCompras ")
loComandoSeleccionar.AppendLine(" UNION ALL ")
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" Doc_Req, Can_Art1_Req, Mon_Net_Req, Doc_OC, Can_Art1_OC, Mon_Net_OC, Doc_Com, Can_Art1_Com, Mon_Net_Com, ")
loComandoSeleccionar.AppendLine(" Doc_DPro, Can_Art1_DPro, Mon_Net_DPro, Año, Mes ")
loComandoSeleccionar.AppendLine(" FROM #tempDevoluciones ")
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
loComandoSeleccionar.AppendLine(" SELECT ")
loComandoSeleccionar.AppendLine(" ISNULL(")
loComandoSeleccionar.AppendLine(" (")
loComandoSeleccionar.AppendLine(" (DATEDIFF(y,")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(DAY, MIN(Minimo)) >=1 AND DATEPART(DAY, MIN(Minimo)) < 30 THEN CAST(DATEPART(YEAR, MIN(Minimo)) As varchar(4)) + ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, MIN(Minimo)) < 10 THEN '0' + CAST(DATEPART(MONTH, MIN(Minimo)) As varchar(2)) ")
loComandoSeleccionar.AppendLine(" ELSE CAST(DATEPART(MONTH, MIN(Minimo)) As varchar(2)) ")
loComandoSeleccionar.AppendLine(" END + '01'")
loComandoSeleccionar.AppendLine(" END,")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(DAY, MAX(Maximo)) >=1 AND DATEPART(DAY, MAX(Maximo)) < 30 THEN CAST(DATEPART(YEAR, MAX(Maximo)) As varchar(4)) + ")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, MAX(Maximo)) < 10 THEN '0' + CAST(DATEPART(MONTH, MAX(Maximo)) As varchar(2)) ")
loComandoSeleccionar.AppendLine(" ELSE CAST(DATEPART(MONTH, MAX(Maximo)) As varchar(2)) ")
loComandoSeleccionar.AppendLine(" END +")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, MAX(Maximo)) = 2 THEN '28'")
loComandoSeleccionar.AppendLine(" ELSE '30'")
loComandoSeleccionar.AppendLine(" END")
loComandoSeleccionar.AppendLine(" END")
loComandoSeleccionar.AppendLine(" ) +")
loComandoSeleccionar.AppendLine(" CASE ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(YEAR," & lcParametro0Desde & ") = DATEPART(YEAR," & lcParametro0Hasta & ") THEN ")
loComandoSeleccionar.AppendLine(" case ")
loComandoSeleccionar.AppendLine(" WHEN DATEPART(MONTH, " & lcParametro0Desde & ") >= 1 THEN 2")
loComandoSeleccionar.AppendLine(" else 0")
loComandoSeleccionar.AppendLine(" END")
loComandoSeleccionar.AppendLine(" ELSE")
loComandoSeleccionar.AppendLine(" (2 * DATEDIFF(YEAR, "& lcParametro0Desde &", "& lcParametro0Hasta &"))")
loComandoSeleccionar.AppendLine(" END")
loComandoSeleccionar.AppendLine(" ) /30),0) AS Num_Meses, ")
loComandoSeleccionar.AppendLine(" ISNULL(DATEDIFF(y,MIN(Minimo), MAX(Maximo)),0) AS Num_Dias ")
loComandoSeleccionar.AppendLine(" FROM ( ")
loComandoSeleccionar.AppendLine(" SELECT MIN(Fecha) AS Minimo, MAX(Fecha) AS Maximo ")
loComandoSeleccionar.AppendLine(" FROM #tempRequisiciones ")
loComandoSeleccionar.AppendLine(" UNION ")
loComandoSeleccionar.AppendLine(" SELECT MIN(Fecha) AS Minimo, MAX(Fecha) AS Maximo ")
loComandoSeleccionar.AppendLine(" FROM #tempOrdenes_Compras ")
loComandoSeleccionar.AppendLine(" UNION ")
loComandoSeleccionar.AppendLine(" SELECT MIN(Fecha) AS Minimo, MAX(Fecha) AS Maximo ")
loComandoSeleccionar.AppendLine(" FROM #tempCompras ")
loComandoSeleccionar.AppendLine(" UNION ")
loComandoSeleccionar.AppendLine(" SELECT MIN(Fecha) AS Minimo, MAX(Fecha) AS Maximo ")
loComandoSeleccionar.AppendLine(" FROM #tempDevoluciones ")
loComandoSeleccionar.AppendLine(" ) AS Tiempo ")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString, "curReportes")
'-------------------------------------------------------------------------------------------------------
' 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.goReportes.mCargarReporte("rRDocumentosCompras_Mensuales", laDatosReporte)
If laDatosReporte.Tables(1).Rows(0).Item(0) = 0 Then
laDatosReporte.Tables(1).Rows(0).Item(0) = 1
End If
If laDatosReporte.Tables(1).Rows(0).Item(1) = 0 Then
laDatosReporte.Tables(1).Rows(0).Item(1) = 1
End If
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m1").Text = "CDBL (Sum({curReportes.Doc_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(0) & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m2").Text = " CDBL(Sum({curReportes.Can_Art1_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m3").Text = "CDBL (Sum({curReportes.Mon_Net_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m4").Text = "CDBL (Sum({curReportes.Doc_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m5").Text = "CDBL (Sum({curReportes.Can_Art1_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m6").Text = "CDBL (Sum({curReportes.Mon_Net_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m7").Text = "CDBL (Sum({curReportes.Doc_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m8").Text = "CDBL (Sum({curReportes.Can_Art1_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m9").Text = "CDBL (Sum({curReportes.Mon_Net_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m10").Text = "CDBL (Sum({curReportes.Doc_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m11").Text = "CDBL (Sum({curReportes.Can_Art1_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_m12").Text = "CDBL (Sum({curReportes.Mon_Net_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(0).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d1").Text = "ToNumber (Sum({curReportes.Doc_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d2").Text = "ToNumber (Sum({curReportes.Can_Art1_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d3").Text = "ToNumber (Sum({curReportes.Mon_Net_Req})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d4").Text = "ToNumber (Sum({curReportes.Doc_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d5").Text = "ToNumber (Sum({curReportes.Can_Art1_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d6").Text = "ToNumber (Sum({curReportes.Mon_Net_OC})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d7").Text = "ToNumber (Sum({curReportes.Doc_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d8").Text = "ToNumber (Sum({curReportes.Can_Art1_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d9").Text = "ToNumber (Sum({curReportes.Mon_Net_Com})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d10").Text = "ToNumber (Sum({curReportes.Doc_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d11").Text = "ToNumber (Sum({curReportes.Can_Art1_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
loObjetoReporte.DataDefinition.FormulaFields("Promedio_d12").Text = "ToNumber (Sum({curReportes.Mon_Net_DPro})/" & laDatosReporte.Tables(1).Rows(0).Item(1).ToString & " )"
'loObjetoReporte.DataDefinition.FormulaFields("Promedio_d12").ValueType = CrystalDecisions.Shared.FieldValueType.NumberField
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrRDocumentosCompras_Mensuales.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
'-------------------------------------------------------------------------------------------'
' CMS: 03/05/10: Programacion inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rRDocumentosCompras_Mensuales.aspx.vb
|
Visual Basic
|
mit
| 36,073
|
Imports System.Data
Imports System.Data.SqlClient
Partial Class Forums_replytopic
Inherits System.Web.UI.Page
Dim cf As New comonfunctions
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim sql As String = ""
Dim pid As String = ""
Dim regmsg As String = ""
Dim rzlt As String = ""
Dim ipadd As String = ""
Dim doubtfulprofile As String = "Y"
Dim ipcountry As String = ""
Dim updatedby As String = ""
pid = "A" & cf.generateid
sql = "insert into topicsQnAansw(answerid,forumqnaid,anser,updatebyid,updatedby)"
sql = sql & " values(@answerid,@forumqnaid,@anser,@updatebyid,@updatedby)"
'Response.Write(sql)
cn.ConnectionString = cf.friendshipdb
cn.Open()
'TextBox1.Text = Replace(TextBox1.Text, vbCrLf, "<br>")
Try
'Session("pid") = "23434
updatedby = Session("fname")
cmd.Connection = cn
cmd.CommandTimeout = 5000
cmd.CommandText = sql
cmd.Parameters.AddWithValue("@answerid", pid)
cmd.Parameters.AddWithValue("@forumqnaid", Request.QueryString("id"))
cmd.Parameters.AddWithValue("@anser", Mid(cf.ReplaceBadWords(Replace(TextBox1.Text, vbCrLf, "<br>")), 1, 5000))
cmd.Parameters.AddWithValue("@updatebyid", Session("pid"))
cmd.Parameters.AddWithValue("@updatedby", updatedby)
cmd.ExecuteNonQuery()
sql = "update forumqandA set updateddate=getdate(),updatebyid='" & Session("pid") & "',updatedby='" & updatedby & "' where forumqnaid=" & Request.QueryString("id")
cf.Taskjobseeker(sql)
cmd.Dispose()
cn.Close()
pid = Request.QueryString("id")
forumheading(pid)
Response.Redirect("viewtopic.aspx?id=" & Request.QueryString("id") & "&tid=" & Request.QueryString("tid"))
Catch ex As Exception
cn.Close()
Response.Write(ex.ToString)
End Try
End Sub
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If Session("pid") Is Nothing Then
Response.Redirect("../login.aspx" & "?ReturnUrl=" & Request.RawUrl)
End If
End Sub
Sub forumheading(ByVal pid As String)
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim sql As String = ""
Dim regmsg As String = ""
Dim rzlt As String = ""
Dim ipadd As String = ""
Dim doubtfulprofile As String = "Y"
Dim ipcountry As String = ""
Dim startedby As String = ""
sql = "update forumtopics set startedbyid=@postedbyid,updatebyid=@updatebyid,latesttopicid=@topicid"
sql = sql & " where forumtopid=" & Request.QueryString("tid")
'Response.Write(sql)
cn.ConnectionString = cf.friendshipdb
cn.Open()
Try
cmd.Connection = cn
cmd.CommandTimeout = 5000
cmd.CommandText = sql
'cmd.Parameters.AddWithValue("@forumtopic", txttopic.Text)
cmd.Parameters.AddWithValue("@postedbyid", Session("pid"))
cmd.Parameters.AddWithValue("@updatebyid", Session("pid"))
cmd.Parameters.AddWithValue("@topicid", pid)
cmd.ExecuteNonQuery()
cmd.Dispose()
cn.Close()
Catch ex As Exception
cn.Close()
Response.Write(ex.ToString)
End Try
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("pid") Is Nothing Then
Response.Redirect("~/login.aspx" & "?ReturnUrl=" & Request.RawUrl)
End If
If Session("pid") = "" Then
Response.Redirect("~/login.aspx" & "?ReturnUrl=" & Request.RawUrl)
End If
End Sub
End Class
|
aminnagpure/matrimonydatingcommunity1.0
|
lovenmarry - EmptyFreeCode/Forums/replytopic.aspx.vb
|
Visual Basic
|
mit
| 4,088
|
Imports System.Data.SqlClient
Partial Class getpiadNonPaidmem
Inherits System.Web.UI.Page
Public cf As New comonfunctions
Dim queryforentry As String = ""
Function makequery() As String
'Dim country, sqlcountry, state, sqlstate, city, sqlcity As String
Dim sqlcountry As String = ""
Dim sqlstate As String = ""
Dim sqlcity As String = ""
Dim sqlpincode As String = ""
Dim sqlgender As String = ""
Dim sqlrace As String = ""
Dim sqlreligion As String = ""
Dim sqlstarsign As String = ""
Dim sqlmaritalstatus As String = ""
Dim sqlheight As String = ""
Dim sqlage As String = ""
Dim sqlmarital As String = ""
Dim sqlonline As String = ""
Dim sqlchkphoto As String = ""
Dim sqlpaidonon As String = ""
'Dim sqlphoto As String = ""
If dpcountry.Text <> "" Then
sqlcountry = " profile.approved='Y' and profile.countryid=" & dpcountry.SelectedValue & " "
End If
If txtstate.Text <> "" Then
sqlstate = " and profile.state like '%" & txtstate.Text & "%'"
End If
If txtCity.Text <> "" Then
sqlcity = " and profile.cityid like '%" & txtCity.Text & "%'"
End If
If txtpincode.Text <> "" Then
sqlpincode = " and profile.zipcode like '%" & txtpincode.Text & "%'"
End If
If gender.SelectedValue.ToString <> "" Then
sqlgender = " and profile.gender='" & gender.SelectedValue.ToString & "'"
End If
If dpRace.Text <> "" Then
sqlrace = " and profile.ethnic='" & dpRace.SelectedValue.ToString & "'"
End If
If dpreligion.Text <> "" Then
sqlreligion = " and profile.religion='" & dpreligion.Text & "'"
End If
If dpmaritalstatus.SelectedValue <> "" Then
sqlmarital = " and profile.maritalstatus='" & dpmaritalstatus.SelectedValue & "'"
End If
If dpstarsign.Text <> "" Then
sqlstarsign = " and profile.starsign='" & dpstarsign.Text & "'"
End If
If dpheight1.SelectedValue <> "" Then
sqlheight = " and height>=" & dpheight1.SelectedValue & ""
End If
If dpheight2.SelectedValue <> "" Then
sqlheight = sqlheight & " and height<=" & dpheight2.SelectedValue & ""
End If
If dpage1.Text <> "" Then
sqlage = " and DateDiff(yyyy,profile.bdate,getdate())>=" & dpage1.Text
End If
If dpage2.Text <> "" Then
sqlage = sqlage & " and DateDiff(yyyy,profile.bdate,getdate())<=" & dpage2.Text
End If
If chkonlinenow.Checked = True Then
sqlonline = " and isonlinenow='Y'"
End If
If chkphoto.Checked = True Then
txtjointype.Text = " inner join"
sqlchkphoto = " and photo<>'' "
Else
txtjointype.Text = " Left join"
End If
sqlpaidonon = " and premiummem ='" & ddlPaidNone.SelectedItem.Value & "'"
makequery = sqlcountry & sqlstate & sqlpincode & sqlgender & sqlrace & sqlreligion & sqlmarital & sqlstarsign & sqlheight & sqlage & sqlonline & sqlchkphoto & sqlcity & sqlchkphoto & sqlpaidonon & " and mobile<>''"
txtquery.Text = makequery
response.write(makequery)
Return makequery
End Function
Function addalertentry(ByVal query As String, ByVal em As String) As String
Dim cnstring As String = ""
Dim cc As New comonfunctions
Dim rzlt As String = ""
Dim regmsg As String = ""
Dim uid As String = ""
Dim strfield As String = ""
Dim strvalues As String = ""
Dim StrSql As String = ""
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.ConnectionString = cf.friendshipdb
con.Open()
uid = Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & Now.Hour.ToString & Now.Minute.ToString & Now.Millisecond
strfield = " insert into alert(candiid,query,queryname,email,jointype) values("
strvalues = " @candiid,@query,@queryname,@email,@jointype)"
StrSql = strfield & strvalues
If checkingnoofentryies() >= 10 Then
con.Close()
addalertentry = "you can only save 10 enteries "
Else
cmd.Parameters.AddWithValue("@candiid", Session("pid"))
cmd.Parameters.AddWithValue("@query", txtquery.Text & " ")
cmd.Parameters.AddWithValue("@queryname", txtqueryname.Text.ToString)
cmd.Parameters.AddWithValue("@email", txtemail.Text.ToString)
cmd.Parameters.AddWithValue("@jointype", txtjointype.Text)
cmd.Connection = con
cmd.CommandText = StrSql
cmd.ExecuteNonQuery()
regmsg = "Alert Verification Required <br>"
regmsg = regmsg & "http://www." & ConfigurationManager.AppSettings("websitename").ToString & "/members/verifyalert.aspx?alertid=" & uid & "&b=" & Session("pid").ToString
regmsg = regmsg & "<br>You have got this email because you have created Partner alert"
If txtemail.Text.ToString <> "" Then
rzlt = cc.send25("alert", "Alert Query Verification", em.ToString, regmsg)
End If
cmd.Dispose()
con.Close()
addalertentry = "Alert Entry added " & rzlt
End If
End Function
Function checkingnoofentryies() As Integer
Dim cmd As New SqlCommand
Dim myreader As SqlDataReader
Dim cn As New SqlConnection
Dim numbofrows As Integer = 0
cn.ConnectionString = cf.friendshipdb
cn.Open()
cmd.Connection = cn
cmd.CommandText = "[alertcount] " & Session("pid") & ""
myreader = cmd.ExecuteReader
If myreader.HasRows = True Then
While myreader.Read
numbofrows = myreader.GetValue(0).ToString
End While
cn.Close()
Return numbofrows
Else
cn.Close()
Return numbofrows
End If
End Function
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
searchform.Visible = False
' Session("makequery") = makequery()
txtquery.Text = makequery()
searchresults.Visible = True
If txtqueryname.Text <> "" Then
addalertentry(queryforentry, txtemail.Text)
End If
'gridview1.DataSourceID = ObjectDataSource1.ID
'gridview1.DataBind()
' Response.Redirect("findpartnerlist.aspx")
End Sub
Protected Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete
If Page.IsPostBack = True Then
searchresults.Visible = True
Else
loadcountry()
End If
End Sub
Sub loadcountry()
Dim myreader As SqlDataReader
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim strsql As String = ""
strsql = "loadcountry"
cn.ConnectionString = cf.friendshipdb
cn.Open()
cmd.Connection = cn
cmd.CommandText = strsql
myreader = cmd.ExecuteReader
dpcountry.DataSource = myreader
dpcountry.DataValueField = "countryid"
dpcountry.DataTextField = "countryname"
dpcountry.DataBind()
cmd.Dispose()
cn.Close()
End Sub
Protected Sub gridview1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gridview1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim pasw As String = TryCast(DataBinder.Eval(e.Row.DataItem, "photopassw"), String)
Dim url As String = TryCast(DataBinder.Eval(e.Row.DataItem, "photoname"), String)
If (url <> "" Or url IsNot Nothing) And (pasw = "" Or pasw Is Nothing) Then
Dim img As Image = DirectCast(e.Row.FindControl("img"), Image)
If img IsNot Nothing Then
img.ImageUrl = "../App_Themes/Thumbs/" & url
End If
End If
If (url = "" Or url Is Nothing) Then
Dim img As Image = DirectCast(e.Row.FindControl("img"), Image)
If img IsNot Nothing Then
img.ImageUrl = "../App_Themes/no_avatar.gif"
End If
End If
If (url <> "" Or url IsNot Nothing) And (pasw <> "") Then
Dim img As Image = DirectCast(e.Row.FindControl("img"), Image)
If img IsNot Nothing Then
img.ImageUrl = "../App_Themes/request-photo-large-1.gif"
End If
End If
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
searchresults.Visible = False
If Not Session("pid") Is Nothing Then
If Session("hasinvites") = "N" Then
' Response.Redirect("compulsorySteps.aspx")
ElseIf Session("headline") = "" Then
' Response.Redirect("compulsorySteps.aspx")
End If
Else
' Response.Redirect("../login.aspx")
End If
If Not Page.IsPostBack Then
txtquery.Text = "1<>1"
End If
End Sub
End Class
|
aminnagpure/matrimonydatingcommunity1.0
|
lovenmarry - EmptyFreeCode/moderators/getpiadNonPaidmem.aspx.vb
|
Visual Basic
|
mit
| 9,554
|
' Copyright 2018 Google LLC
'
' 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 Google.Api.Ads.AdWords.Lib
Imports Google.Api.Ads.AdWords.v201809
Namespace Google.Api.Ads.AdWords.Examples.VB.v201809
''' <summary>
''' This code example updates an expanded text ad. To get expanded text ads,
''' run GetExpandedTextAds.vb.
''' </summary>
Public Class UpdateExpandedTextAd
Inherits ExampleBase
''' <summary>
''' Main method, to run this code example as a standalone application.
''' </summary>
''' <param name="args">The command line arguments.</param>
Public Shared Sub Main(ByVal args As String())
Dim codeExample As New UpdateExpandedTextAd
Console.WriteLine(codeExample.Description)
Try
Dim adId As Long = Long.Parse("INSERT_AD_ID_HERE")
codeExample.Run(New AdWordsUser, adId)
Catch e As Exception
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e))
End Try
End Sub
''' <summary>
''' Returns a description about the code example.
''' </summary>
Public Overrides ReadOnly Property Description() As String
Get
Return _
"This code example updates an expanded text ad. To get expanded text ads, " +
"run GetExpandedTextAds.cs."
End Get
End Property
''' <summary>
''' Runs the code example.
''' </summary>
''' <param name="user">The AdWords user.</param>
''' <param name="adId">Id of the ad to be updated.</param>
Public Sub Run(ByVal user As AdWordsUser, ByVal adId As Long)
Using service As AdService = CType(
user.GetService(
AdWordsService.v201809.AdGroupAdService),
AdService)
' Create an expanded text ad using the provided ad ID.
Dim expandedTextAd As New ExpandedTextAd()
expandedTextAd.id = adId
' Update some properties of the expanded text ad.
expandedTextAd.headlinePart1 = "Cruise to Pluto #" +
ExampleUtilities.GetShortRandomString()
expandedTextAd.headlinePart2 = "Tickets on sale now"
expandedTextAd.description = "Best space cruise ever."
expandedTextAd.finalUrls = New String() {"http://www.example.com/"}
expandedTextAd.finalMobileUrls = New String() {"http://www.example.com/mobile"}
' Create ad group ad operation And add it to the list.
Dim operation As New AdOperation
operation.operator = [Operator].SET
operation.operand = expandedTextAd
Try
' Update the ad on the server.
Dim result As AdReturnValue = service.mutate(New AdOperation() {operation})
Dim updatedAd As ExpandedTextAd = CType(result.value(0), ExpandedTextAd)
' Print out some information.
Console.WriteLine("Expanded text ad with ID {0} was updated.", updatedAd.id)
Console.WriteLine(
"Headline part 1: {0}\nHeadline part 2: {1}\nDescription: {2}" +
"\nFinal URL: {3}\nFinal mobile URL: {4}",
updatedAd.headlinePart1, updatedAd.headlinePart2, updatedAd.description,
updatedAd.finalUrls(0), updatedAd.finalMobileUrls(0))
Catch e As Exception
Throw New System.ApplicationException("Failed to update expanded text ad.", e)
End Try
End Using
End Sub
End Class
End Namespace
|
googleads/googleads-dotnet-lib
|
examples/AdWords/Vb/v201809/BasicOperations/UpdateExpandedTextAd.vb
|
Visual Basic
|
apache-2.0
| 4,445
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
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.TextBox2 = New System.Windows.Forms.TextBox
Me.Button3 = New System.Windows.Forms.Button
Me.TextBox1 = New System.Windows.Forms.TextBox
Me.RichTextBox1 = New System.Windows.Forms.RichTextBox
Me.Label2 = New System.Windows.Forms.Label
Me.Label3 = New System.Windows.Forms.Label
Me.Label4 = New System.Windows.Forms.Label
Me.Label5 = New System.Windows.Forms.Label
Me.gue1 = New System.Windows.Forms.Label
Me.gue2 = New System.Windows.Forms.Label
Me.gue3 = New System.Windows.Forms.Label
Me.gue4 = New System.Windows.Forms.Label
Me.gue5 = New System.Windows.Forms.Label
Me.Label6 = New System.Windows.Forms.Label
Me.feil = New System.Windows.Forms.Label
Me.gjenstaa = New System.Windows.Forms.Label
Me.Label7 = New System.Windows.Forms.Label
Me.TextBox3 = New System.Windows.Forms.TextBox
Me.foreslaa = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(12, 342)
Me.TextBox2.MaxLength = 7
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New System.Drawing.Size(208, 20)
Me.TextBox2.TabIndex = 17
'
'Button3
'
Me.Button3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None
Me.Button3.Cursor = System.Windows.Forms.Cursors.Default
Me.Button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat
Me.Button3.ForeColor = System.Drawing.SystemColors.ControlText
Me.Button3.Location = New System.Drawing.Point(226, 339)
Me.Button3.Name = "Button3"
Me.Button3.Size = New System.Drawing.Size(75, 24)
Me.Button3.TabIndex = 19
Me.Button3.Text = "Send"
Me.Button3.UseVisualStyleBackColor = True
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(399, 28)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(136, 20)
Me.TextBox1.TabIndex = 21
'
'RichTextBox1
'
Me.RichTextBox1.Location = New System.Drawing.Point(12, 28)
Me.RichTextBox1.Name = "RichTextBox1"
Me.RichTextBox1.ReadOnly = True
Me.RichTextBox1.Size = New System.Drawing.Size(289, 270)
Me.RichTextBox1.TabIndex = 18
Me.RichTextBox1.Text = ""
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.BackColor = System.Drawing.Color.Transparent
Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.Location = New System.Drawing.Point(312, 29)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(88, 16)
Me.Label2.TabIndex = 23
Me.Label2.Text = "IP Address:"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(316, 12)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(121, 13)
Me.Label3.TabIndex = 26
Me.Label3.Text = "Computer to connect to:"
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Location = New System.Drawing.Point(9, 12)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(84, 13)
Me.Label4.TabIndex = 27
Me.Label4.Text = "Network stream:"
'
'Label5
'
Me.Label5.AutoSize = True
Me.Label5.BackColor = System.Drawing.Color.Transparent
Me.Label5.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label5.Location = New System.Drawing.Point(12, 323)
Me.Label5.Name = "Label5"
Me.Label5.Size = New System.Drawing.Size(169, 16)
Me.Label5.TabIndex = 28
Me.Label5.Text = "Ord (maks 5 bokstaver)"
'
'gue1
'
Me.gue1.AutoSize = True
Me.gue1.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gue1.Location = New System.Drawing.Point(587, 201)
Me.gue1.Name = "gue1"
Me.gue1.Size = New System.Drawing.Size(32, 31)
Me.gue1.TabIndex = 29
Me.gue1.Text = "A"
'
'gue2
'
Me.gue2.AutoSize = True
Me.gue2.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gue2.Location = New System.Drawing.Point(625, 201)
Me.gue2.Name = "gue2"
Me.gue2.Size = New System.Drawing.Size(32, 31)
Me.gue2.TabIndex = 30
Me.gue2.Text = "A"
'
'gue3
'
Me.gue3.AutoSize = True
Me.gue3.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gue3.Location = New System.Drawing.Point(663, 201)
Me.gue3.Name = "gue3"
Me.gue3.Size = New System.Drawing.Size(32, 31)
Me.gue3.TabIndex = 31
Me.gue3.Text = "A"
'
'gue4
'
Me.gue4.AutoSize = True
Me.gue4.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gue4.Location = New System.Drawing.Point(701, 201)
Me.gue4.Name = "gue4"
Me.gue4.Size = New System.Drawing.Size(32, 31)
Me.gue4.TabIndex = 32
Me.gue4.Text = "A"
'
'gue5
'
Me.gue5.AutoSize = True
Me.gue5.Font = New System.Drawing.Font("Microsoft Sans Serif", 20.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gue5.Location = New System.Drawing.Point(739, 201)
Me.gue5.Name = "gue5"
Me.gue5.Size = New System.Drawing.Size(32, 31)
Me.gue5.TabIndex = 33
Me.gue5.Text = "A"
'
'Label6
'
Me.Label6.AutoSize = True
Me.Label6.Location = New System.Drawing.Point(566, 127)
Me.Label6.Name = "Label6"
Me.Label6.Size = New System.Drawing.Size(73, 13)
Me.Label6.TabIndex = 34
Me.Label6.Text = "Feil bokstaver"
'
'feil
'
Me.feil.AutoSize = True
Me.feil.Location = New System.Drawing.Point(569, 144)
Me.feil.Name = "feil"
Me.feil.Size = New System.Drawing.Size(0, 13)
Me.feil.TabIndex = 35
'
'gjenstaa
'
Me.gjenstaa.AutoSize = True
Me.gjenstaa.Font = New System.Drawing.Font("Microsoft Sans Serif", 36.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.gjenstaa.Location = New System.Drawing.Point(583, 41)
Me.gjenstaa.Name = "gjenstaa"
Me.gjenstaa.Size = New System.Drawing.Size(51, 55)
Me.gjenstaa.TabIndex = 36
Me.gjenstaa.Text = "8"
'
'Label7
'
Me.Label7.AutoSize = True
Me.Label7.Location = New System.Drawing.Point(569, 28)
Me.Label7.Name = "Label7"
Me.Label7.Size = New System.Drawing.Size(102, 13)
Me.Label7.TabIndex = 37
Me.Label7.Text = "Gjenstående forsøk:"
'
'TextBox3
'
Me.TextBox3.Location = New System.Drawing.Point(669, 291)
Me.TextBox3.MaxLength = 1
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.Size = New System.Drawing.Size(24, 20)
Me.TextBox3.TabIndex = 38
'
'foreslaa
'
Me.foreslaa.Location = New System.Drawing.Point(700, 288)
Me.foreslaa.Name = "foreslaa"
Me.foreslaa.Size = New System.Drawing.Size(75, 23)
Me.foreslaa.TabIndex = 39
Me.foreslaa.Text = "Foreslå"
Me.foreslaa.UseVisualStyleBackColor = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(824, 374)
Me.Controls.Add(Me.foreslaa)
Me.Controls.Add(Me.TextBox3)
Me.Controls.Add(Me.Label7)
Me.Controls.Add(Me.gjenstaa)
Me.Controls.Add(Me.feil)
Me.Controls.Add(Me.Label6)
Me.Controls.Add(Me.gue5)
Me.Controls.Add(Me.gue4)
Me.Controls.Add(Me.gue3)
Me.Controls.Add(Me.gue2)
Me.Controls.Add(Me.gue1)
Me.Controls.Add(Me.Label5)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.TextBox2)
Me.Controls.Add(Me.Button3)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.RichTextBox1)
Me.Controls.Add(Me.Label2)
Me.Name = "Form1"
Me.Text = "LAN HANGMAN 0.1"
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
Friend WithEvents Button3 As System.Windows.Forms.Button
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents Label5 As System.Windows.Forms.Label
Friend WithEvents gue1 As System.Windows.Forms.Label
Friend WithEvents gue2 As System.Windows.Forms.Label
Friend WithEvents gue3 As System.Windows.Forms.Label
Friend WithEvents gue4 As System.Windows.Forms.Label
Friend WithEvents gue5 As System.Windows.Forms.Label
Friend WithEvents Label6 As System.Windows.Forms.Label
Friend WithEvents feil As System.Windows.Forms.Label
Friend WithEvents gjenstaa As System.Windows.Forms.Label
Friend WithEvents Label7 As System.Windows.Forms.Label
Friend WithEvents TextBox3 As System.Windows.Forms.TextBox
Friend WithEvents foreslaa As System.Windows.Forms.Button
End Class
|
niikoo/NProj
|
Windows/Skole/LAN_Hangman/LAN_Hangman/Form1.Designer.vb
|
Visual Basic
|
apache-2.0
| 11,258
|
' 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.ApiDesignGuidelines.Analyzers
''' <summary>
''' CA2211: Non-constant fields should not be visible
''' </summary>
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public NotInheritable Class BasicNonConstantFieldsShouldNotBeVisibleAnalyzer
Inherits NonConstantFieldsShouldNotBeVisibleAnalyzer
End Class
End Namespace
|
mattwar/roslyn-analyzers
|
src/Microsoft.ApiDesignGuidelines.Analyzers/VisualBasic/BasicNonConstantFieldsShouldNotBeVisible.vb
|
Visual Basic
|
apache-2.0
| 699
|
Public Class HTC
Private Sub HTC_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
|
thenameisnigel/OpenRecoveryInstall_Win
|
OpenCannibal/HTC.vb
|
Visual Basic
|
mit
| 122
|
' 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.Diagnostics
Imports Microsoft.CodeAnalysis.Diagnostics.AddImport
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Diagnostics.AddImport
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicAddImportDiagnosticAnalyzer
Inherits AddImportDiagnosticAnalyzerBase(Of SyntaxKind, SimpleNameSyntax, QualifiedNameSyntax, IncompleteMemberSyntax)
Private Const UndefinedType1 As String = "BC30002"
Private Const MessageFormat As String = "Type '{0}' is not defined."
Private Shared ReadOnly _kindsOfInterest As ImmutableArray(Of SyntaxKind) = ImmutableArray.Create(SyntaxKind.IncompleteMember)
Protected Overrides ReadOnly Property SyntaxKindsOfInterest As ImmutableArray(Of SyntaxKind)
Get
Return _kindsOfInterest
End Get
End Property
Protected Overrides ReadOnly Property DiagnosticDescriptor As DiagnosticDescriptor
Get
Return GetDiagnosticDescriptor(UndefinedType1, MessageFormat)
End Get
End Property
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/Features/VisualBasic/Diagnostics/Analyzers/VisualBasicAddImportDiagnosticAnalyzer.vb
|
Visual Basic
|
apache-2.0
| 1,450
|
' *********************************************************
'
' Copyright © Microsoft Corporation
'
' 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
'
' THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES
' OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED,
' INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES
' OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.
'
' See the Apache 2 License for the specific language
' governing permissions and limitations under the License.
'
' *********************************************************
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TreeTransformsVB.Transforms
Public Class TransformVisitor
Inherits VisualBasicSyntaxRewriter
Private ReadOnly tree As SyntaxTree
Private transformKind As transformKind
Public Sub New(tree As SyntaxTree, transformKind As transformKind)
Me.tree = tree
Me.transformKind = transformKind
End Sub
Public Overrides Function VisitLiteralExpression(node As LiteralExpressionSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitLiteralExpression(node), LiteralExpressionSyntax)
Dim token = node.Token
If (transformKind = transformKind.TrueToFalse) AndAlso (node.Kind = SyntaxKind.TrueLiteralExpression) Then
Dim newToken = SyntaxFactory.Token(token.LeadingTrivia, SyntaxKind.FalseKeyword, token.TrailingTrivia)
Return SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression, newToken)
End If
If (transformKind = transformKind.FalseToTrue) AndAlso (node.Kind = SyntaxKind.FalseLiteralExpression) Then
Dim newToken = SyntaxFactory.Token(token.LeadingTrivia, SyntaxKind.TrueKeyword, token.TrailingTrivia)
Return SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression, newToken)
End If
Return node
End Function
Public Overrides Function VisitPredefinedType(node As PredefinedTypeSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitPredefinedType(node), PredefinedTypeSyntax)
Dim token = node.Keyword
If (transformKind = transformKind.IntTypeToLongType) AndAlso (token.Kind = SyntaxKind.IntegerKeyword) Then
Dim longToken = SyntaxFactory.Token(token.LeadingTrivia, SyntaxKind.LongKeyword, token.TrailingTrivia)
Return SyntaxFactory.PredefinedType(longToken)
End If
Return node
End Function
Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode
Return MyBase.VisitModuleBlock(node)
End Function
Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode
Dim classStatement = node.ClassStatement
Dim classKeyword = classStatement.ClassKeyword
Dim endStatement = node.EndClassStatement
Dim endBlockKeyword = endStatement.BlockKeyword
If transformKind = transformKind.ClassToStructure Then
Dim structureKeyword = SyntaxFactory.Token(classKeyword.LeadingTrivia, SyntaxKind.StructureKeyword, classKeyword.TrailingTrivia)
Dim endStructureKeyword = SyntaxFactory.Token(endBlockKeyword.LeadingTrivia, SyntaxKind.StructureKeyword, endBlockKeyword.TrailingTrivia)
Dim newStructureStatement = SyntaxFactory.StructureStatement(classStatement.AttributeLists, classStatement.Modifiers, structureKeyword, classStatement.Identifier, classStatement.TypeParameterList)
Dim newEndStatement = SyntaxFactory.EndStructureStatement(endStatement.EndKeyword, endStructureKeyword)
Return SyntaxFactory.StructureBlock(newStructureStatement, node.Inherits, node.Implements, node.Members, newEndStatement)
End If
Return node
End Function
Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode
Dim structureStatement = node.StructureStatement
Dim structureKeyword = structureStatement.StructureKeyword
Dim endStatement = node.EndStructureStatement
Dim endBlockKeyword = endStatement.BlockKeyword
If transformKind = transformKind.StructureToClass Then
Dim classKeyword = SyntaxFactory.Token(structureKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, structureKeyword.TrailingTrivia)
Dim endClassKeyword = SyntaxFactory.Token(endBlockKeyword.LeadingTrivia, SyntaxKind.ClassKeyword, endBlockKeyword.TrailingTrivia)
Dim newClassStatement = SyntaxFactory.ClassStatement(structureStatement.AttributeLists, structureStatement.Modifiers, classKeyword, structureStatement.Identifier, structureStatement.TypeParameterList)
Dim newEndStatement = SyntaxFactory.EndClassStatement(endStatement.EndKeyword, endClassKeyword)
Return SyntaxFactory.ClassBlock(newClassStatement, node.Inherits, node.Implements, node.Members, newEndStatement)
End If
Return node
End Function
Public Overrides Function VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax) As SyntaxNode
Return MyBase.VisitInterfaceBlock(node)
End Function
Public Overrides Function VisitOrdering(node As OrderingSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitOrdering(node), OrderingSyntax)
Dim orderingKind = node.AscendingOrDescendingKeyword
If (transformKind = transformKind.OrderByAscToOrderByDesc) AndAlso (orderingKind.Kind = SyntaxKind.AscendingKeyword) Then
Dim descToken = SyntaxFactory.Token(orderingKind.LeadingTrivia, SyntaxKind.DescendingKeyword, orderingKind.TrailingTrivia)
Return SyntaxFactory.Ordering(SyntaxKind.DescendingOrdering, node.Expression, descToken)
End If
If (transformKind = transformKind.OrderByDescToOrderByAsc) AndAlso (orderingKind.Kind = SyntaxKind.DescendingKeyword) Then
Dim ascToken = SyntaxFactory.Token(orderingKind.LeadingTrivia, SyntaxKind.AscendingKeyword, orderingKind.TrailingTrivia)
Return SyntaxFactory.Ordering(SyntaxKind.AscendingOrdering, node.Expression, ascToken)
End If
Return node
End Function
Public Overrides Function VisitAssignmentStatement(node As AssignmentStatementSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitAssignmentStatement(node), AssignmentStatementSyntax)
Dim left = node.Left
Dim right = node.Right
Dim operatorToken = node.OperatorToken
If (transformKind = transformKind.AddAssignmentToAssignment) AndAlso (node.Kind = SyntaxKind.AddAssignmentStatement) Then
Dim equalsToken = SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.EqualsToken, operatorToken.TrailingTrivia)
Dim newLeft = left.WithLeadingTrivia(SyntaxTriviaList.Empty)
Dim plusToken = SyntaxFactory.Token(operatorToken.LeadingTrivia, SyntaxKind.PlusToken, operatorToken.TrailingTrivia)
Dim addExpression = SyntaxFactory.BinaryExpression(SyntaxKind.AddExpression, newLeft, plusToken, right)
Return SyntaxFactory.SimpleAssignmentStatement(left, equalsToken, addExpression)
End If
Return node
End Function
Public Overrides Function VisitDirectCastExpression(node As DirectCastExpressionSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitDirectCastExpression(node), DirectCastExpressionSyntax)
Dim keyword = node.Keyword
If (transformKind = transformKind.DirectCastToTryCast) AndAlso (node.Kind = SyntaxKind.DirectCastExpression) Then
Dim tryCastKeyword = SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.TryCastKeyword, keyword.TrailingTrivia)
Return SyntaxFactory.TryCastExpression(tryCastKeyword, node.OpenParenToken, node.Expression, node.CommaToken, node.Type, node.CloseParenToken)
End If
Return node
End Function
Public Overrides Function VisitTryCastExpression(node As TryCastExpressionSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitTryCastExpression(node), TryCastExpressionSyntax)
Dim keyword = node.Keyword
If (transformKind = transformKind.TryCastToDirectCast) AndAlso (node.Kind = SyntaxKind.TryCastExpression) Then
Dim directCastKeyword = SyntaxFactory.Token(keyword.LeadingTrivia, SyntaxKind.DirectCastKeyword, keyword.TrailingTrivia)
Return SyntaxFactory.DirectCastExpression(directCastKeyword, node.OpenParenToken, node.Expression, node.CommaToken, node.Type, node.CloseParenToken)
End If
Return node
End Function
Public Overrides Function VisitVariableDeclarator(node As VariableDeclaratorSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitVariableDeclarator(node), VariableDeclaratorSyntax)
Dim names = node.Names
Dim asClause = node.AsClause
Dim initializer = node.Initializer
If (transformKind = transformKind.InitVariablesToNothing) AndAlso (initializer Is Nothing) AndAlso (names.Count = 1) Then
Dim newEqualsToken = SyntaxFactory.Token(SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")), SyntaxKind.EqualsToken, SyntaxFactory.TriviaList(SyntaxFactory.WhitespaceTrivia(" ")))
Dim newNothingToken = SyntaxFactory.Token(SyntaxKind.NothingKeyword)
Dim newNothingExpression = SyntaxFactory.NothingLiteralExpression(newNothingToken)
Dim newInitializer = SyntaxFactory.EqualsValue(newEqualsToken, newNothingExpression)
Return node.Update(node.Names, node.AsClause, newInitializer)
End If
Return node
End Function
Public Overrides Function VisitParameter(node As ParameterSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitParameter(node), ParameterSyntax)
If (transformKind = transformKind.ByRefParamToByValParam) OrElse (transformKind = transformKind.ByValParamToByRefParam) Then
Dim listOfModifiers = New List(Of SyntaxToken)
For Each modifier In node.Modifiers
Dim modifierToken = modifier
If (modifier.Kind = SyntaxKind.ByValKeyword) AndAlso (transformKind = transformKind.ByValParamToByRefParam) Then
modifierToken = SyntaxFactory.Token(modifierToken.LeadingTrivia, SyntaxKind.ByRefKeyword, modifierToken.TrailingTrivia)
ElseIf (modifier.Kind = SyntaxKind.ByRefKeyword) AndAlso (transformKind = TransformKind.ByRefParamToByValParam) Then
modifierToken = SyntaxFactory.Token(modifierToken.LeadingTrivia, SyntaxKind.ByValKeyword, modifierToken.TrailingTrivia)
End If
listOfModifiers.Add(modifierToken)
Next
Dim newModifiers = SyntaxFactory.TokenList(listOfModifiers)
Return SyntaxFactory.Parameter(node.AttributeLists, newModifiers, node.Identifier, node.AsClause, node.Default)
End If
Return node
End Function
Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitDoLoopBlock(node), DoLoopBlockSyntax)
Dim beginLoop = node.DoStatement
Dim endLoop = node.LoopStatement
If (transformKind = transformKind.DoBottomTestToDoTopTest) AndAlso (node.Kind = SyntaxKind.DoLoopWhileBlock OrElse node.Kind = SyntaxKind.DoLoopUntilBlock) Then
Dim newDoKeyword = SyntaxFactory.Token(beginLoop.DoKeyword.LeadingTrivia, SyntaxKind.DoKeyword, endLoop.LoopKeyword.TrailingTrivia)
Dim newLoopKeyword = SyntaxFactory.Token(endLoop.LoopKeyword.LeadingTrivia, endLoop.LoopKeyword.Kind, beginLoop.DoKeyword.TrailingTrivia)
Dim newBegin = SyntaxFactory.DoStatement(If(endLoop.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoWhileStatement, SyntaxKind.DoUntilStatement), newDoKeyword, endLoop.WhileOrUntilClause)
Dim newEnd = SyntaxFactory.SimpleLoopStatement().WithLoopKeyword(newLoopKeyword)
Return SyntaxFactory.DoLoopBlock(If(endLoop.Kind = SyntaxKind.LoopWhileStatement, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock), newBegin, node.Statements, newEnd)
End If
If (transformKind = transformKind.DoTopTestToDoBottomTest) AndAlso (node.Kind = SyntaxKind.DoWhileLoopBlock OrElse node.Kind = SyntaxKind.DoUntilLoopBlock) Then
Dim newDoKeyword = SyntaxFactory.Token(beginLoop.DoKeyword.LeadingTrivia, SyntaxKind.DoKeyword, endLoop.LoopKeyword.TrailingTrivia)
Dim newLoopKeyword = SyntaxFactory.Token(endLoop.LoopKeyword.LeadingTrivia, endLoop.LoopKeyword.Kind, beginLoop.DoKeyword.TrailingTrivia)
Dim newBegin = SyntaxFactory.SimpleDoStatement().WithDoKeyword(newDoKeyword)
Dim newEnd = SyntaxFactory.LoopStatement(If(beginLoop.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement), newLoopKeyword, beginLoop.WhileOrUntilClause)
Return SyntaxFactory.DoLoopBlock(If(beginLoop.Kind = SyntaxKind.DoWhileStatement, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock), newBegin, node.Statements, newEnd)
End If
If (transformKind = transformKind.DoWhileTopTestToWhile) AndAlso (node.Kind = SyntaxKind.DoWhileLoopBlock OrElse node.Kind = SyntaxKind.DoUntilLoopBlock) Then
Dim endKeyword = SyntaxFactory.Token(endLoop.LoopKeyword.LeadingTrivia, SyntaxKind.EndKeyword)
Dim endWhileKeyword = SyntaxFactory.Token(SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" ")), SyntaxKind.WhileKeyword, endLoop.LoopKeyword.TrailingTrivia)
Dim endWhile = SyntaxFactory.EndWhileStatement(endKeyword, endWhileKeyword)
Dim beginWhileKeyword = SyntaxFactory.Token(beginLoop.DoKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, beginLoop.DoKeyword.TrailingTrivia)
Dim whileStatement = SyntaxFactory.WhileStatement(beginWhileKeyword, beginLoop.WhileOrUntilClause.Condition)
Return SyntaxFactory.WhileBlock(whileStatement, node.Statements, endWhile)
End If
Return node
End Function
Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitWhileBlock(node), WhileBlockSyntax)
Dim beginWhile = node.WhileStatement
Dim endWhile = node.EndWhileStatement
If transformKind = transformKind.WhileToDoWhileTopTest Then
Dim doKeyword = SyntaxFactory.Token(beginWhile.WhileKeyword.LeadingTrivia, SyntaxKind.DoKeyword, beginWhile.WhileKeyword.TrailingTrivia)
Dim whileKeyword = SyntaxFactory.Token(SyntaxKind.WhileKeyword, SyntaxFactory.TriviaList(SyntaxFactory.Whitespace(" ")))
Dim whileClause = SyntaxFactory.WhileOrUntilClause(SyntaxKind.WhileClause, whileKeyword, beginWhile.Condition)
Dim loopKeyword = SyntaxFactory.Token(endWhile.GetLeadingTrivia(), SyntaxKind.LoopKeyword, endWhile.GetTrailingTrivia())
Dim endLoop = SyntaxFactory.SimpleLoopStatement().WithLoopKeyword(loopKeyword)
Dim doStatement = SyntaxFactory.DoWhileStatement(doKeyword, whileClause)
Return SyntaxFactory.DoWhileLoopBlock(doStatement, node.Statements, endLoop)
End If
Return node
End Function
Public Overrides Function VisitExitStatement(node As ExitStatementSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitExitStatement(node), ExitStatementSyntax)
Dim blockKeyword = node.BlockKeyword
Dim exitKeyword = node.ExitKeyword
If (transformKind = transformKind.WhileToDoWhileTopTest) AndAlso (node.Kind = SyntaxKind.ExitWhileStatement) Then
Dim doKeyword = SyntaxFactory.Token(blockKeyword.LeadingTrivia, SyntaxKind.DoKeyword, blockKeyword.TrailingTrivia)
Return SyntaxFactory.ExitDoStatement(exitKeyword, doKeyword)
End If
If (transformKind = transformKind.DoWhileTopTestToWhile) AndAlso (node.Kind = SyntaxKind.ExitDoStatement) Then
Dim parent = node.Parent
'Update Exit Do to Exit While only for Do-While and NOT for Do-Until
While (parent IsNot Nothing) AndAlso (TryCast(parent, DoLoopBlockSyntax) Is Nothing)
parent = parent.Parent
End While
Dim doBlock = TryCast(parent, DoLoopBlockSyntax)
If doBlock IsNot Nothing Then
If (doBlock.DoStatement.WhileOrUntilClause IsNot Nothing) AndAlso (doBlock.DoStatement.WhileOrUntilClause.Kind = SyntaxKind.WhileClause) Then
Dim whileKeyword = SyntaxFactory.Token(blockKeyword.LeadingTrivia, SyntaxKind.WhileKeyword, blockKeyword.TrailingTrivia)
Return SyntaxFactory.ExitWhileStatement(exitKeyword, whileKeyword)
End If
End If
End If
Return node
End Function
Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As SyntaxNode
node = DirectCast(MyBase.VisitSingleLineIfStatement(node), SingleLineIfStatementSyntax)
Dim elseClause = node.ElseClause
If transformKind = transformKind.SingleLineIfToMultiLineIf Then
Dim leadingTriviaList = SyntaxFactory.TriviaList(node.GetLeadingTrivia().LastOrDefault(), SyntaxFactory.WhitespaceTrivia(" "))
Dim newIfStatement = SyntaxFactory.IfStatement(node.IfKeyword, node.Condition, node.ThenKeyword)
Dim newIfStatements = GetSequentialListOfStatements(node.Statements, leadingTriviaList)
Dim newElseBlock As ElseBlockSyntax = Nothing
If elseClause IsNot Nothing Then
Dim newElseKeyword = SyntaxFactory.Token(node.GetLeadingTrivia(), SyntaxKind.ElseKeyword)
Dim newElseStmt = SyntaxFactory.ElseStatement(newElseKeyword)
Dim newStatementsElsePart = GetSequentialListOfStatements(elseClause.Statements, leadingTriviaList)
newElseBlock = SyntaxFactory.ElseBlock(newElseStmt, newStatementsElsePart)
End If
Dim whiteSpaceTrivia = SyntaxFactory.WhitespaceTrivia(" ")
Dim endKeyword = SyntaxFactory.Token(node.GetLeadingTrivia(), SyntaxKind.EndKeyword)
Dim blockKeyword = SyntaxFactory.Token(SyntaxFactory.TriviaList(whiteSpaceTrivia), SyntaxKind.IfKeyword)
Dim newEndIf = SyntaxFactory.EndIfStatement(endKeyword, blockKeyword)
Return SyntaxFactory.MultiLineIfBlock(newIfStatement, newIfStatements, Nothing, newElseBlock, newEndIf)
End If
Return node
End Function
Private Function GetSequentialListOfStatements(statements As SyntaxList(Of StatementSyntax), stmtLeadingTrivia As SyntaxTriviaList) As SyntaxList(Of StatementSyntax)
Dim newStatementList = New List(Of StatementSyntax)
For Each statement In statements
Dim oldFirst = statement.GetFirstToken(includeZeroWidth:=True)
Dim newFirst = oldFirst.WithLeadingTrivia(stmtLeadingTrivia)
newStatementList.Add(statement.ReplaceToken(oldFirst, newFirst))
Next
Dim listOfSeparators = New List(Of SyntaxToken)
For i = 0 To statements.Count - 1
listOfSeparators.Add(SyntaxFactory.Token(SyntaxKind.StatementTerminatorToken))
Next
Return SyntaxFactory.List(newStatementList)
End Function
End Class
|
thomaslevesque/roslyn
|
src/Samples/VisualBasic/TreeTransforms/TransformVisitor.vb
|
Visual Basic
|
apache-2.0
| 19,649
|
Public Class PlaylistCard
Public playlist As Playlist
Public Sub New(ByRef playlist As Playlist)
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
Me.playlist = playlist
If playlist.tracks.Count > 0 Then
If playlist.tracks.Count < 4 Then
If playlist.tracks(0).Album.Cover IsNot Nothing Then
Cover1.Image = playlist.tracks(0).Album.Cover
Else
Cover1.Image = My.Resources.album_cover_default
BackColor = ColorTranslator.FromHtml("#212121")
End If
TableLayout.SetRowSpan(Cover1, 2)
TableLayout.SetColumnSpan(Cover1, 2)
Else
Cover1.Image = playlist.tracks(0).Album.Cover
Cover2.Image = playlist.tracks(1).Album.Cover
Cover3.Image = playlist.tracks(2).Album.Cover
Cover4.Image = playlist.tracks(3).Album.Cover
End If
End If
lblCardType.ForeColor = ColorTranslator.FromHtml("#ffebee")
PlaylistName.ForeColor = ColorTranslator.FromHtml("#ffebee")
PlaylistName.Text = playlist.name
End Sub
Private Sub playPause_Click(sender As Object, e As EventArgs) Handles playPause.Click
If PurePlayer.queue.playing And PurePlayer.queue.data.type = Queue.QueueType.PLAYLIST Then
Dim p As Playlist = PurePlayer.queue.data.args(0)
If p.id = playlist.id Then
PurePlayer.queue.pause()
playPause.Image = My.Resources.play_button_hover
Exit Sub
End If
End If
PurePlayer.queue.stop()
PurePlayer.queue = New Queue(New Queue.QueueData(Queue.QueueType.PLAYLIST, playlist), playlist.tracks)
If PurePlayer.queue.Shuffled Then
PurePlayer.queue.shuffle()
End If
PurePlayer.queue.play(, 0)
playPause.Image = My.Resources.pause_button_hover
End Sub
Private Sub playPause_MouseEnter(sender As Object, e As EventArgs) Handles playPause.MouseEnter
If PurePlayer.queue.playing And PurePlayer.queue.data.type = Queue.QueueType.PLAYLIST Then
Dim p As Playlist = PurePlayer.queue.data.args(0)
If p.id = playlist.id Then
playPause.Image = My.Resources.pause_button_hover
Exit Sub
End If
End If
playPause.Image = My.Resources.play_button_hover
End Sub
Private Sub playPause_MouseLeave(sender As Object, e As EventArgs) Handles playPause.MouseLeave
If PurePlayer.queue.playing And PurePlayer.queue.data.type = Queue.QueueType.PLAYLIST Then
Dim p As Playlist = PurePlayer.queue.data.args(0)
If p.id = playlist.id Then
playPause.Image = My.Resources.pause_button
Exit Sub
End If
End If
playPause.Image = My.Resources.play_button
End Sub
End Class
|
DeveloperRic/PureMusicPlayer
|
PureMusicPlayer/PureMusicPlayer/PlaylistCard.vb
|
Visual Basic
|
mit
| 3,146
|
Imports ExampleSettings.ParamModels
Public Class UC_DataBase
Private _validationOK As Boolean
Public ReadOnly Property ValidationOK As Boolean
Get
Return _validationOK
End Get
End Property
Private _param As SQLServerPrm
Public Property Param As SQLServerPrm
Get
Return _param
End Get
Set(value As SQLServerPrm)
_param = value
If (value.Credentials.Authentication = SQLServerCredentials.AuthenticationType.SQLServer) Then
cboSQLAutenticationTypes.SelectedIndex = cboSQLAutenticationTypes.FindString("SQL Server")
txtSQLAutenticationUserID.Text = value.Credentials.UserId
txtSQLAutenticationPassword.Text = value.Credentials.Password
Else
cboSQLAutenticationTypes.SelectedIndex = cboSQLAutenticationTypes.FindString("Windows")
End If
txtSQLDataSource.Text = value.DataSource
txtSQLCatalog.Text = value.Catalog
End Set
End Property
Private Sub OnValidation()
_validationOK = True
If (Not String.IsNullOrWhiteSpace(txtSQLDataSource.Text)) Then
_param.DataSource = txtSQLDataSource.Text.Trim
Else
_validationOK = False
End If
If (Not String.IsNullOrWhiteSpace(txtSQLCatalog.Text)) Then
_param.Catalog = txtSQLCatalog.Text.Trim
Else
_validationOK = False
End If
If (cboSQLAutenticationTypes.Text = "SQL Server") Then
_param.Credentials.Authentication = SQLServerCredentials.AuthenticationType.SQLServer
If (Not String.IsNullOrWhiteSpace(txtSQLAutenticationUserID.Text)) Then
_param.Credentials.UserId = txtSQLAutenticationUserID.Text.Trim
Else
_validationOK = False
End If
If (Not String.IsNullOrWhiteSpace(txtSQLAutenticationPassword.Text)) Then
_param.Credentials.Password = txtSQLAutenticationPassword.Text.Trim
txtSQLAutenticationPassword.BackColor = SystemColors.Window
Else
_validationOK = False
txtSQLAutenticationPassword.BackColor = txtSQLAutenticationPassword.Z80_BackColorEmptyText
End If
Else
_param.Credentials.Authentication = SQLServerCredentials.AuthenticationType.Windows
End If
btnTestSQLServer.Enabled = SQLcanTest()
End Sub
Private Function SQLcanTest() As Boolean
If String.IsNullOrEmpty(txtSQLDataSource.Text.Trim()) Then
Return False
End If
If String.IsNullOrEmpty(txtSQLCatalog.Text.Trim()) Then
Return False
End If
If cboSQLAutenticationTypes.Text = "SQL Server" Then
If String.IsNullOrEmpty(txtSQLAutenticationUserID.Text.Trim()) Then
Return False
End If
If String.IsNullOrEmpty(txtSQLAutenticationPassword.Text.Trim()) Then
Return False
End If
End If
Return True
End Function
Private Sub cboSQLAutenticationTypes_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSQLAutenticationTypes.SelectedIndexChanged
If cboSQLAutenticationTypes.Text = "SQL Server" Then
txtSQLAutenticationUserID.Enabled = True
txtSQLAutenticationPassword.Enabled = True
txtSQLAutenticationUserID.Text = String.Format("{0}", _param.Credentials.UserId)
txtSQLAutenticationPassword.Text = String.Format("{0}", _param.Credentials.Password)
Else
txtSQLAutenticationUserID.Enabled = False
txtSQLAutenticationPassword.Enabled = False
txtSQLAutenticationUserID.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString()
txtSQLAutenticationPassword.Text = String.Empty
txtSQLAutenticationPassword.BackColor = SystemColors.Window
End If
btnTestSQLServer.Enabled = SQLcanTest()
End Sub
Private Sub btnTestSQLServer_Click(sender As Object, e As EventArgs) Handles btnTestSQLServer.Click
'TODO: implement Database connection test
MessageBox.Show("TODO connection test: Test done", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
Public Sub New()
InitializeComponent()
_param = New SQLServerPrm()
cboSQLAutenticationTypes.Items.Clear()
cboSQLAutenticationTypes.Items.Add("SQL Server")
cboSQLAutenticationTypes.Items.Add("Windows")
AddHandler txtSQLDataSource.TextChanged, AddressOf OnValidation
AddHandler txtSQLCatalog.TextChanged, AddressOf OnValidation
AddHandler txtSQLAutenticationUserID.TextChanged, AddressOf OnValidation
AddHandler txtSQLAutenticationPassword.TextChanged, AddressOf OnValidation
End Sub
End Class
|
kernelENREK/Z80_NavigationBar
|
ExampleSettings/Settings/UserInterface/UC_DataBase.vb
|
Visual Basic
|
mit
| 4,988
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30319.235
'
' 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("BBMS.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
|
gudduarnav/ArnavPrograms
|
Project.ADITA/BBMS/BBMS/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,711
|
'------------------------------------------------------------------------------
' <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.Windows)
Me.IsSingleInstance = false
Me.EnableVisualStyles = true
Me.SaveMySettingsOnExit = true
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
End Sub
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
Protected Overrides Sub OnCreateMainForm()
Me.MainForm = Global.EnglishTeacher.Form1
End Sub
End Class
End Namespace
|
pepm99/School-C-
|
VB/EnglishTeacher/EnglishTeacher/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 1,458
|
Namespace UnsafeRoutines
Public Module _Shared
Public Function GetDWGFileIcon(exists As Boolean, fileName As String, size As Integer, ByRef tooltip As String) As Drawing.Image
Dim DWGVersionCode As String = ""
If exists Then
DWGVersionCode = GetDWGVersionCode(fileName).ToUpper()
End If
Select Case DWGVersionCode
Case "AC1027"
tooltip = "{0}2013{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1027.png"
Case "AC1024"
tooltip = "{0}2010{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1024.bmp"
Case "AC1021"
tooltip = "{0}2007-2009{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1021.bmp"
Case "AC1018"
tooltip = "{0}2004-2006{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1018.gif"
Case "AC1015"
tooltip = "{0}2000-2002{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1015.gif"
Case "AC1014"
tooltip = "{0}R14{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "AC1014.gif"
Case "AC1012", "AC1009", "AC1006", "AC1004"
tooltip = "{0}R9-R13{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "ACPrev.bmp"
Case Else
tooltip = "{0}Unsupported or Unknown Version{0}".FormatWith(Settings.DefaultIndent)
DWGVersionCode = "ACUnknown.bmp"
End Select
Return Images.GetImage(DWGVersionCode, size, Images.Blank)
End Function
Private Function GetDWGVersionCode(fileName As String) As String
Try
Dim Buffer(6) As Char
Using sr As New IO.StreamReader(New IO.FileStream(fileName, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read))
sr.ReadBlock(Buffer, 0, 6)
End Using
Return String.Concat(Buffer).ToString.Substring(0, 6)
Catch ex As Exception
ex.ToLog(True)
End Try
Return ""
End Function
End Module
End Namespace
|
nublet/DMS
|
DMS.Base/UnsafeRoutines/UnsafeRoutines.vb
|
Visual Basic
|
mit
| 2,410
|
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Reflection
Imports System.Collections
Imports Aspose.Words
Imports Aspose.Words.Fields
Imports Aspose.Words.Tables
Imports System.Diagnostics
Public Class ConvertFieldsInParagraph
Public Shared Sub Run()
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir_WorkingWithFields()
Dim fileName As String = "TestFile.doc"
Dim doc As New Document(dataDir & fileName)
' Pass the appropriate parameters to convert all IF fields to static text that are encountered only in the last
' paragraph of the document.
FieldsHelper.ConvertFieldsToStaticText(doc.FirstSection.Body.LastParagraph, FieldType.FieldIf)
dataDir = dataDir & RunExamples.GetOutputFilePath(fileName)
' Save the document with fields transformed to disk.
doc.Save(dataDir)
Console.WriteLine(vbNewLine & "Converted fields to static text in the paragraph successfully." & vbNewLine & "File saved at " + dataDir)
End Sub
End Class
|
assadvirgo/Aspose_Words_NET
|
Examples/VisualBasic/Programming-Documents/Fields/ConvertFieldsInParagraph.vb
|
Visual Basic
|
mit
| 1,099
|
Public Class ProblemWindow
Private Sub ProblemWindow1_Loaded(sender As Object, e As RoutedEventArgs) Handles MyBase.Loaded
WHLClasses.EnableBlur(Me)
End Sub
Public Reason As String = ""
Private Sub ProblemClick(sender As Button, e As RoutedEventArgs) Handles SendToPrepackButton.Click, CantFindButton.Click, NeedsGs1Button.Click, NoStockButon.Click, WrongBarcodeButton.Click, WrongWarehouseButton.Click
Reason = sender.Content.ToString
Me.Hide()
End Sub
Private Sub CancelButton_Click(sender As Object, e As RoutedEventArgs)
Reason = "Cancel"
Me.Hide()
End Sub
End Class
Public Module ProblemWindowMeth
Dim ProblemWindow As New ProblemWindow
Dim SF As New WHLClasses.SpeechFactory
Public Function GetReason() As String
Try
ProblemWindow.WindowTitle.Text = SF.ProblemTitles
Catch ex As Exception
End Try
ProblemWindow.ShowDialog()
Return ProblemWindow.Reason
End Function
End Module
|
WhiteHingeLtd/SurfacePicker
|
SurfacePicker/PickingBits/ProblemWindow.xaml.vb
|
Visual Basic
|
mit
| 1,038
|
#Region "Microsoft.VisualBasic::4fb492bd01d14dca45b52821878e588f, src\mzmath\ms2_math-core\Ms1\PrecursorType\MzCalculator.vb"
' Author:
'
' xieguigang (gg.xie@bionovogene.com, BioNovoGene Co., LTD.)
'
' Copyright (c) 2018 gg.xie@bionovogene.com, BioNovoGene Co., LTD.
'
'
' MIT License
'
'
' 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.
' /********************************************************************************/
' Summaries:
' Class MzCalculator
'
' Properties: adducts, charge, IsEmpty, M, mode
' name
'
' Constructor: (+2 Overloads) Sub New
' Function: AdductMZ, CalcMass, CalcMZ, EvaluateAll, ReverseMass
' (+2 Overloads) ToString
'
' Class PrecursorInfo
'
' Properties: adduct, charge, ionMode, M, mz
' precursor_type
'
' Constructor: (+2 Overloads) Sub New
' Function: ToString
'
'
' /********************************************************************************/
#End Region
#If netcore5 = 0 Then
Imports System.Data.Linq.Mapping
#Else
Imports Microsoft.VisualBasic.ComponentModel.DataSourceModel.SchemaMaps
#End If
Imports System.Runtime.CompilerServices
Imports System.Xml.Serialization
Imports Microsoft.VisualBasic.Language
Imports Microsoft.VisualBasic.Text
Imports stdNum = System.Math
Namespace Ms1.PrecursorType
Public Class MzCalculator
Public Property name As String
''' <summary>
''' 电荷量的符号无所谓,计算出来的m/z结果值总是正数
''' </summary>
''' <returns></returns>
Public Property charge As Integer
Public Property M As Integer
''' <summary>
''' 是可能会出现负数的加和结果,例如[M-H2O]的adducts为-18
''' </summary>
Public Property adducts As Double
''' <summary>
''' +/-
''' </summary>
''' <returns></returns>
Public Property mode As Char
Public ReadOnly Property IsEmpty As Boolean
Get
Return name.StringEmpty AndAlso
charge = 0 AndAlso
M = 0 AndAlso
adducts = 0 AndAlso
mode = ASCII.NUL
End Get
End Property
Sub New()
End Sub
''' <summary>
'''
''' </summary>
''' <param name="type$"></param>
''' <param name="charge%"></param>
''' <param name="M#"></param>
''' <param name="adducts#"></param>
''' <param name="mode">只允许``+/-``这两种符号出现</param>
Sub New(type$, charge%, M#, adducts#, Optional mode As Char = Nothing)
Me.name = type
Me.charge = charge
Me.M = M
Me.adducts = adducts
Me.mode = mode
End Sub
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Function CalcMass(precursorMZ#) As Double
Return (ReverseMass(precursorMZ, M, charge, adducts))
End Function
''' <summary>
''' 通过所给定的精确分子质量计算出``m/z``
''' </summary>
''' <param name="mass#"></param>
''' <returns></returns>
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Function CalcMZ(mass#) As Double
Return (AdductMZ(mass * M, adducts, charge))
End Function
<DebuggerStepThrough>
Public Overrides Function ToString() As String
If InStr(name, "[") < InStr(name, "]") AndAlso InStr(name, "[") > 0 Then
Return name
Else
Return $"[{name}]{If(charge = 1, "", charge)}{mode}"
End If
End Function
Public Overloads Function ToString(ionization_mode As Long) As String
If IsEmpty Then
Return "[M]+" Or "[M]-".When(ionization_mode < 0)
Else
Return Me.ToString
End If
End Function
''' <summary>
''' 返回加和物的m/z数据
''' </summary>
''' <param name="mass#"></param>
''' <param name="adduct#"></param>
''' <param name="charge%"></param>
''' <returns></returns>
'''
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Shared Function AdductMZ(mass#, adduct#, charge%) As Double
Return (mass / stdNum.Abs(charge) + adduct)
End Function
''' <summary>
''' 从质谱的MS/MS的前体的m/z结果反推目标分子的mass结果
''' </summary>
''' <param name="mz#"></param>
''' <param name="M#"></param>
''' <param name="charge%"></param>
''' <param name="adduct#"></param>
''' <returns></returns>
'''
<MethodImpl(MethodImplOptions.AggressiveInlining)>
Public Shared Function ReverseMass(mz#, M#, charge%, adduct#) As Double
Return ((mz - adduct) * stdNum.Abs(charge) / M)
End Function
''' <summary>
'''
''' </summary>
''' <param name="mass">
''' mass value or ``m/z``
''' </param>
''' <param name="mode"><see cref="ParseIonMode"/></param>
''' <returns></returns>
Public Shared Iterator Function EvaluateAll(mass#, mode As String, Optional exact_mass As Boolean = False) As IEnumerable(Of PrecursorInfo)
For Each type In Provider.Calculator(mode).Values
Yield New PrecursorInfo With {
.adduct = type.adducts,
.charge = type.charge,
.M = type.M,
.mz = If(exact_mass, type.CalcMass(mass), type.CalcMZ(mass)),
.precursor_type = type.name
}
Next
End Function
End Class
Public Class PrecursorInfo
<XmlAttribute>
Public Property precursor_type As String
Public Property charge As Double
Public Property M As Double
Public Property adduct As Double
''' <summary>
''' mz or exact mass
''' </summary>
''' <returns></returns>
<Column(Name:="m/z")>
Public Property mz As String
Public Property ionMode As Integer
Sub New()
End Sub
Sub New(mz As MzCalculator)
precursor_type = mz.ToString
charge = mz.charge
M = mz.M
adduct = mz.adducts
ionMode = ParseIonMode(mz.mode)
End Sub
Public Overrides Function ToString() As String
Return $"{precursor_type} m/z={mz}"
End Function
End Class
End Namespace
|
xieguigang/MassSpectrum-toolkits
|
src/mzmath/ms2_math-core/Ms1/PrecursorType/MzCalculator.vb
|
Visual Basic
|
mit
| 7,976
|
'------------------------------------------------------------------------------
' <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
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("DotNet3dsToolkit.Tests.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
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Friend ReadOnly Property FBI_3ds() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("FBI_3ds", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Friend ReadOnly Property FBI_cia() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("FBI_cia", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
'''<summary>
''' Looks up a localized resource of type System.Byte[].
'''</summary>
Friend ReadOnly Property FBI_cxi() As Byte()
Get
Dim obj As Object = ResourceManager.GetObject("FBI_cxi", resourceCulture)
Return CType(obj,Byte())
End Get
End Property
End Module
End Namespace
|
evandixon/DotNet3dsToolkit
|
Old/Tests/DotNet3dsToolkit.Tests/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 3,805
|
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web
Imports System.Web.Security
Imports System.Text
Imports System.Reflection
Imports System.Globalization
Imports Gears.Validation
Imports Gears.DataSource
Imports Gears.Util
Imports Gears.JS
Namespace Gears
''' <summary>
''' Gearsフレームワークを使用する場合の、継承元となるページ
''' </summary>
''' <remarks></remarks>
Public MustInherit Class GearsPage
Inherits Page
''' <summary>
''' ListItemのAttributeがPostBack時に消えてしまうため、これをViewStateに補完するためのキー<br/>
''' http://stackoverflow.com/questions/8157363/is-it-possible-to-maintain-added-attributes-on-a-listitem-while-posting-back
''' </summary>
''' <remarks></remarks>
Public Const V_LIST_ATTRIBUTES As String = "GEARS_LIST_ATTRIBUTES"
''' <summary>画面ロードされた値をViewStateに保持しておくためのキー</summary>
Public Const V_LOADED As String = "GEARS_VALUE_LOADED"
''' <summary>画面ロードされた、楽観ロック用の値をViewStateに保持しておくためのキー</summary>
Public Const V_LOCKCOL As String = "GEARS_VALUE_FOR_LOCK"
''' <summary>リロード防止用のタイムスタンプをViewStateに保持するためのキー</summary>
Public Const V_S_TIME_STAMP As String = "GEARS_TIME_STAMP"
''' <summary>
''' バリデーション情報が保管されたCssClassを保持する。<br/>
''' 初回以降は各属性のスタイルで書き換えられてしまうため、初回の値を保持
''' </summary>
Public Const V_VALIDATORS As String = "GEARS_VALIDATORS"
''' <summary>権限を設定するための属性名</summary>
Public Const A_ROLE_AUTH_ALLOW As String = "AUTHORIZATIONALLOW"
''' <summary>権限の有無によって切り替える属性(VISIBLE/ENABLEなど)</summary>
Public Const A_ROLE_EVAL_ACTION As String = "ROLEEVALACTION"
''' <summary>グローバル化を行う対象を示す属性名</summary>
Public Const A_GLOBALIZE_TARGET As String = "GGLOBALIZE"
''' <summary>
''' ログ出力を行うか否かの引数指定<br/>
''' gs_log_out=trueを設定することでログの出力が可能
''' </summary>
Public Const Q_GEARS_IS_LOG_OUT As String = "gs_log_out"
''' <summary>警告のプロンプトを出すためのスクリプト名</summary>
Const CS_ALERT_PROMPT_SCRIPT_NAME As String = "GearsAlertPromptScript"
''' <summary>警告を無視するか否かを設定したhiddenフィールド</summary>
Const CS_ALERT_IS_IGNORE_FLG As String = "GearsYesAlertIgnore"
''' <summary>JavaScript変数の宣言を行うためのスクリプト名</summary>
Const CS_JS_VARIABLE_BLOCK As String = "GearsJsObjectBlock"
''' <summary>ViewStateに値を設定する際の区切り文字</summary>
Protected Const VIEW_STATE_SEPARATOR As String = "/"
''' <summary>デフォルトで使用するグローバルリソースファイル</summary>
Protected Overridable Property GearsGlobalResource As String = "GearsResource"
Private _isNeedJudgeReload As Boolean = True
''' <summary>リロードを判定するか否かのフラグ</summary>
Public Property IsNeedJudgeReload() As Boolean
Get
Return _isNeedJudgeReload
End Get
Set(ByVal value As Boolean)
_isNeedJudgeReload = value
End Set
End Property
Private _isReload As Boolean = False
''' <summary>リクエストがリロードか否かの判定</summary>
Public ReadOnly Property IsReload() As Boolean
Get
Return _isReload
End Get
End Property
''' <summary>コントロール間の関連を管理するクラス</summary>
Protected GMediator As GearsMediator = Nothing
''' <summary>ログ</summary>GMediator
Protected GLog As New Dictionary(Of String, GearsException)
''' <summary>
''' コントロールの管理を行うGearsMediatorを初期化する
''' </summary>
''' <param name="conName"></param>
''' <param name="dns"></param>
''' <remarks></remarks>
Private Sub initMediator(ByVal conName As String, Optional ByVal dns As String = "")
Dim pageConName As String = conName
Dim pageDsNspace As String = dns
Dim readProperty = Function(p As String) As String
Dim result As String = p
'マスターページプロパティを参照するものは、その値を取得
If Not String.IsNullOrEmpty(p) AndAlso p.StartsWith("Master.") Then
Dim prop As String = MasterProperty(Replace(p, "Master.", ""))
If Not prop Is Nothing Then
result = prop.ToString
End If
End If
Return result
End Function
'Config設定を読み込む
Dim env As GearsSection = GearsSection.Read()
Dim conInfo As String = Trim(env.DefaultConnection)
Dim dnsInfo As String = Trim(env.DefaultNamespace)
'設定
If String.IsNullOrEmpty(pageConName) Then pageConName = conInfo
pageConName = readProperty(pageConName)
If String.IsNullOrEmpty(pageDsNspace) Then pageDsNspace = dnsInfo
pageDsNspace = readProperty(pageDsNspace)
'未作成か、設定値が異なる場合更新
If GMediator Is Nothing OrElse (GMediator.ConnectionName <> pageConName Or GMediator.DsNamespace <> pageDsNspace) Then
GMediator = New GearsMediator(pageConName, pageDsNspace)
End If
End Sub
''' <summary>
''' ページ初期化イベント
''' </summary>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Overrides Sub OnInit(ByVal e As System.EventArgs)
'GearsMediatorのインスタンス化
initMediator(String.Empty, String.Empty)
MyBase.OnInit(e)
GIsAuth(Me) 'コントロールロード後、権限評価を実施する
End Sub
''' <summary>
''' 画面上のコントロールをGearsControl化し、GearsMediatorの管理下に配置する
''' </summary>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Overrides Sub OnPreLoad(ByVal e As System.EventArgs)
MyBase.OnPreLoad(e)
'リロード判定
If IsNeedJudgeReload Then
judgeIsReload()
End If
'コントロールへのデータ/アトリビュートのセット
setUpPageControls()
'ローカライゼーションを行う
globalizeControl(Me)
'ログ出力モードの場合トレースを開始する
If IsLoggingMode() Then
GearsLogStack.traceOn()
End If
End Sub
''' <summary>
''' ロード完了後イベント
''' </summary>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Overrides Sub OnLoadComplete(e As System.EventArgs)
MyBase.OnLoadComplete(e)
'ログの書き出し
If IsLoggingMode() Then
'記録されたログを書き出し
If Me.FindControl(Q_GEARS_IS_LOG_OUT) Is Nothing Then
Dim label As New Label
label.Text = GearsLogStack.makeDisplayString
Me.Controls.Add(label)
Else
CType(Me.FindControl(Q_GEARS_IS_LOG_OUT), Label).Text = GearsLogStack.makeDisplayString
End If
ElseIf Not Me.FindControl(Q_GEARS_IS_LOG_OUT) Is Nothing Then
Me.Controls.Remove(Me.FindControl(Q_GEARS_IS_LOG_OUT))
End If
GearsLogStack.traceEnd()
'JavaScript変数定義スクリプトの書き出し
JsVariableWrite()
End Sub
''' <summary>
''' 発生したPostBackがリロードによるものか否かを判定する
''' </summary>
''' <remarks></remarks>
Private Sub judgeIsReload()
Response.Cache.SetCacheability(HttpCacheability.NoCache)
'IE以外の場合、nostoreも使用しないと駄目な模様 http://d.hatena.ne.jp/manymanytips/20110120/1295500136
Response.Cache.SetNoStore()
Dim dateNow As DateTime = Now
Dim isAsync As Boolean = IsPageAsync()
'ポストバック時、[F5]での二重登録防止判定 ※AsyncによるPostBackは除外する
If Not isAsync Then
If IsPostBack Then
'タイムスタンプが設定されていない場合
If Session(Request.FilePath & V_S_TIME_STAMP) Is Nothing Or ViewState(Request.FilePath & V_S_TIME_STAMP) Is Nothing Then
'ポストバックで遷移してきて、タイムスタンプが空の場合もリロードと判定する
_isReload = True
Else
Dim dateSessionStamp As DateTime = DirectCast(Session(Request.FilePath & V_S_TIME_STAMP), DateTime)
Dim dateViewStateStamp As DateTime = DirectCast(ViewState(Request.FilePath & V_S_TIME_STAMP), DateTime)
'[F5]を押下したとき(リロード)のViewStateのタイムスタンプは、前回送信情報のまま
If dateSessionStamp <> dateViewStateStamp Then
_isReload = True
Else
_isReload = False
End If
End If
End If
'タイムスタンプを記録 ※非同期更新の場合はタイムスタンプの更新を行わない(ViewStateが更新されず、Sessionのみタイムスタンプが更新されてしまうため)
Session(Request.FilePath & V_S_TIME_STAMP) = dateNow
ViewState(Request.FilePath & V_S_TIME_STAMP) = dateNow
End If
End Sub
''' <summary>
''' ページ更新が非同期更新かどうかチェックする
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function IsPageAsync() As Boolean
'TODO ToolkitScriptManagerの考慮が必要->ToolkitScriptManagerが使用されている場合、ScriptManager.GetCurrentでNothingが返る
'これを回避するにはAjaxControlToolkit.ToolkitScriptManager.GetCurrent(Me)を使用する必要があるが、必ず使っているとも限らないのでアセンブリから読み込む必要あり
Dim s As ScriptManager = ScriptManager.GetCurrent(Me)
If s IsNot Nothing Then
Return s.IsInAsyncPostBack()
Else
Return False
End If
End Function
''' <summary>
''' ログ出力モードか否かを判定
''' </summary>
''' <returns></returns>
''' <remarks></remarks>
Public Function IsLoggingMode() As Boolean
Dim isLogging As String = QueryValue(Q_GEARS_IS_LOG_OUT)
Dim isDebug As Boolean = GearsSection.Read.isDebug
If isDebug And (Not String.IsNullOrEmpty(isLogging) AndAlso (isLogging.ToLower = "true")) Then
Return True
Else
Return False
End If
End Function
''' <summary>
''' ページの初期化処理。<br/>
''' * ネーミングルールに沿うコントロールをGearsMediatorに登録する
''' * ViewStateに保持しておいた値から、ロード時の値をGearsControlにセットしておく
''' * CssClassから、GearsControlにバリデーション/スタイル表示のためのAttributeをロードする
''' </summary>
''' <remarks></remarks>
Protected Sub setUpPageControls()
If GMediator Is Nothing Then
Throw New GearsException("ページの初期化が行われていません", "web.configのgears sectionの設定を確認して下さい")
End If
'コントロールを管理するGearsMediatorへコントロールを追加する
'属性情報は、初回ロード以後は初回ロード時のCssClassを使用するため、自動ロードしない
GMediator.addControls(Me, isAutoLoadAttr:=False)
'初回ロード時のCSS
Dim initialCss As Dictionary(Of String, String) = CType(ViewState(V_VALIDATORS), Dictionary(Of String, String))
If initialCss Is Nothing Then
initialCss = New Dictionary(Of String, String)
End If
'登録されたコントロールに対し、属性をセット
For Each item As KeyValuePair(Of String, GearsControl) In GMediator.GControls
'前回ロード時の値がある場合、過去ロード値をセット
If Not reloadLoadedValue(item.Key) Is Nothing Then
item.Value.LoadedValue = reloadLoadedValue(item.Key)
End If
'データロード
If Not IsPostBack Then
'初回、かつ入力用のコントロールについては事前にデータソースから値をロードする。
If GMediator.isInputControl(item.Value.Control) Then
item.Value.dataBind()
End If
'CSSからアトリビュートをロード
If TypeOf item.Value.Control Is WebControl Then
initialCss.Add(item.Key, CType(item.Value.Control, WebControl).CssClass)
item.Value.loadAttribute()
CType(item.Value.Control, WebControl).CssClass = item.Value.GCssClass 'CSSを書き換え
End If
'リストコントロールのAttributeが確保されない対応
saveListItemAttribute(item.Value.Control)
Else
'Postbackの場合、基本はViewStateが担保されているのでロードは行わないが、
'ViewStateEnableがFalseでデータが消える場合、リロードをかける
If item.Value.Control.EnableViewState = False Then
item.Value.dataBind()
End If
'保管しておいた初期CSSからアトリビュートをロード/エラースタイルを消去
If TypeOf item.Value.Control Is WebControl AndAlso initialCss.ContainsKey(item.Key) Then
item.Value.loadAttribute(initialCss(item.Key))
CType(item.Value.Control, WebControl).CssClass = CType(item.Value.Control, WebControl).CssClass.Replace(" " + GearsAttribute.ERR_STYLE, "")
End If
'リストコントロールのAttributeが確保されない対応
loadListItemAttribute(item.Value.Control)
End If
Next
'初期CSSを保管
If ViewState(V_VALIDATORS) Is Nothing Then
ViewState(V_VALIDATORS) = initialCss
End If
End Sub
''' <summary>
''' 指定コントロールについて、ローカライゼーションを行う
''' </summary>
''' <param name="target"></param>
''' <remarks></remarks>
Protected Sub globalizeControl(ByVal target As Control)
ControlSearcher.fetchControls(target, Sub(control As Control, ByRef dto As GearsDTO)
Dim itext As ITextControl = CType(control, ITextControl)
itext.Text = GGlobalize(itext.Text, GearsControl.getControlAttribute(control, A_GLOBALIZE_TARGET))
End Sub,
Function(control As Control) As Boolean
Return TypeOf control Is ITextControl AndAlso Not String.IsNullOrEmpty(GearsControl.getControlAttribute(control, A_GLOBALIZE_TARGET))
End Function)
End Sub
''' <summary>
''' 登録済みのコントロールを取得する(id指定)
''' </summary>
''' <param name="id"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GGet(ByVal id As String) As GearsControl
Return GMediator.GControl(id)
End Function
''' <summary>
''' 登録済みのコントロールを取得する(Controlから)
''' </summary>
''' <param name="con"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GGet(ByVal con As Control) As GearsControl
If Not con Is Nothing Then
Return GMediator.GControl(con)
Else
Return Nothing
End If
End Function
''' <summary>
''' 登録済みのコントロールのデータソースを取得する
''' </summary>
''' <param name="con"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GSource(ByVal con As Control) As GearsDataSource
If Not GGet(con) Is Nothing Then
Return GGet(con).DataSource
Else
Return Nothing
End If
End Function
''' <summary>
''' 自動で登録されないコントロールを手動でGearsMediatorに登録する<br/>
''' ※データソースが推定されるケースは基本的に自動で行われるため、このメソッドにはisRepaceオプションは付与しない
''' </summary>
''' <param name="con"></param>
''' <param name="isAutoLoadAttr"></param>
''' <remarks></remarks>
Public Function GAdd(ByVal con As Control, Optional isAutoLoadAttr As Boolean = True) As gRuleExpression
GMediator.addControl(con, isAutoLoadAttr)
Return New gRuleExpression(con, GMediator)
End Function
''' <summary>
''' 自動で登録されないコントロールを手動でGearsMediatorに登録する(データソース指定)<br/>
''' 先行して登録されているコントロールを明示的に入れ替えたい場合は、isReplaceをTrueに設定する
''' </summary>
''' <param name="con"></param>
''' <param name="ds"></param>
''' <param name="isReplace"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GAdd(ByVal con As Control, ByVal ds As GearsDataSource, Optional ByVal isReplace As Boolean = False) As gRuleExpression
Dim gcon As GearsControl = New GearsControl(con, ds)
If isReplace Then
GMediator.replaceControl(gcon)
Else
GMediator.addControl(gcon)
End If
Return New gRuleExpression(con, GMediator)
End Function
''' <summary>
''' 指定されたIDのコントロールを取得する
''' </summary>
''' <param name="conid"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GFindControl(ByVal conid As String) As Control
Return ControlSearcher.findControl(Me, conid)
End Function
''' <summary>
''' コントロール間のルールを作成する汎用関数
''' </summary>
''' <param name="fromCon"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GRule(ByVal fromCon As Control) As gRuleExpression
Return New gRuleExpression(fromCon, GMediator)
End Function
''' <summary>
''' フォームを保存する(キーが一致すればUpdate/しなければInsertを行う)
''' </summary>
''' <param name="form"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GSave(ByVal form As Control) As Boolean
Dim dto As New GearsDTO(ActionType.SAVE)
Return GSend(form).ToMyself(dto)
End Function
''' <summary>
''' フォームの値でデータベースを更新する
''' </summary>
''' <param name="form"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GUpdate(ByVal form As Control) As Boolean
Dim dto As New GearsDTO(ActionType.UPD)
Return GSend(form).ToMyself(dto)
End Function
''' <summary>
''' フォームの値をデータベースに挿入する
''' </summary>
''' <param name="form"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GInsert(ByVal form As Control) As Boolean
Dim dto As New GearsDTO(ActionType.INS)
Return GSend(form).ToMyself(dto)
End Function
''' <summary>
''' フォーム内のキー項目の値に合致するレコードをデータベースから削除する
''' </summary>
''' <param name="form"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GDelete(ByVal form As Control) As Boolean
Dim dto As New GearsDTO(ActionType.DEL)
Return GSend(form).ToMyself(dto)
End Function
''' <summary>
''' フォーム内のキー項目の値で、データベースからレコードをロードし自身に設定する(フォームのリロード)<br/>
''' DTOを指定した場合、そのDTOでロードが行われる。コントロールにセットされた値は使用されないので注意。
''' </summary>
''' <param name="form"></param>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GLoad(ByVal form As Control, Optional ByVal dto As GearsDTO = Nothing) As Boolean
'Formコントロール内のキーを使用し、自身の値をリロードする
Dim loadDto As New GearsDTO(dto)
If dto Is Nothing Then 'DTOの指定がなかった場合、自身に設定された値を使用する
Dim sqlb As SqlBuilder = GPack(form, ActionType.SEL).toSqlBuilder
For Each f As SqlFilterItem In sqlb.Filter
loadDto.Filter.Add(f)
Next
End If
Return GSend(loadDto).ToThe(form)
End Function
''' <summary>
''' 自身の値で、関連する全てのコントロールに対しフィルタをかける
''' </summary>
''' <param name="fromControl"></param>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GFilterBy(ByVal fromControl As Control, Optional ByVal dto As GearsDTO = Nothing) As Boolean
Dim fDto As GearsDTO = dto
If fDto Is Nothing Then fDto = New GearsDTO(ActionType.SEL)
Return GSend(fromControl).ToAll(fDto)
End Function
''' <summary>
''' 自身の値で、指定したコントロールに対しフィルタをかける
''' </summary>
''' <param name="fromControl"></param>
''' <param name="toControl"></param>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GFilterBy(ByVal fromControl As Control, ByVal toControl As Control, Optional ByVal dto As GearsDTO = Nothing) As Boolean
Dim fDto As GearsDTO = dto
If fDto Is Nothing Then fDto = New GearsDTO(ActionType.SEL)
Return GSend(fromControl).ToThe(toControl, fDto)
End Function
''' <summary>
''' DTOの送信処理を記述する
''' </summary>
''' <param name="fromControl"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GSend(ByVal fromControl As Control) As gSendExpression
Return New gSendExpression(fromControl, AddressOf Me.execute)
End Function
''' <summary>
''' DTOの送信処理を記述する
''' </summary>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function GSend(ByVal dto As GearsDTO) As gSendExpression
Return New gSendExpression(dto, AddressOf Me.execute)
End Function
''' <summary>
''' 自身のコントロール情報を収集しGearsDTOにまとめ、指定したActionをセットする
''' </summary>
''' <param name="fromControl"></param>
''' <param name="atype"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GPack(ByVal fromControl As Control, Optional ByVal atype As ActionType = ActionType.SEL) As GearsDTO
Dim dto As GearsDTO = New GearsDTO(atype)
Return GPack(fromControl, Nothing, dto)
End Function
''' <summary>
''' 与えられたDTOに自身のコントロール情報を追加する形で、GearsDTOを作成する
''' </summary>
''' <param name="fromControl"></param>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GPack(ByVal fromControl As Control, ByVal dto As GearsDTO) As GearsDTO
Return GPack(fromControl, Nothing, dto)
End Function
''' <summary>
''' 指定した相手先に送るためのDTOを作成する
''' </summary>
''' <param name="fromControl"></param>
''' <param name="toControl"></param>
''' <param name="atype"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GPack(ByVal fromControl As Control, ByVal toControl As Control, Optional ByVal atype As ActionType = ActionType.SEL) As GearsDTO
Return GPack(fromControl, toControl, New GearsDTO(atype))
End Function
''' <summary>
''' 与えられたDTOを元に指定した相手先に送るためのDTOを作成する
''' </summary>
''' <param name="fromControl"></param>
''' <param name="toControl"></param>
''' <param name="fromDto"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Overridable Function GPack(ByVal fromControl As Control, ByVal toControl As Control, ByVal fromDto As GearsDTO) As GearsDTO
Return GMediator.makeDTO(fromControl, toControl, fromDto)
End Function
''' <summary>
''' fromコントロールから与えられたDTOを元にDTOを作成し、toコントロールに送信する<br/>
''' </summary>
''' <param name="fromControl"></param>
''' <param name="toControl"></param>
''' <param name="dto"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function execute(ByVal fromControl As Control, ByVal toControl As Control, ByVal dto As GearsDTO) As Boolean
Dim result As Boolean = True
GLog.Clear()
'コントロールの登録チェック
If fromControl IsNot Nothing AndAlso GMediator.GControl(fromControl) Is Nothing Then
GearsLogStack.setLog(fromControl.ID + " はまだ登録されていません。GAddで登録する必要があります。")
Return False
End If
'更新系処理の場合のチェック
If Not dto Is Nothing AndAlso (dto.Action <> ActionType.SEL And dto.Action <> ActionType.NONE) Then
'リロード
If IsReload Then
GLog.Add(If(fromControl IsNot Nothing, fromControl.ID, "(Send Dto)"), New GearsException("画面のリフレッシュのため、更新処理は実行されません"))
dto.Action = ActionType.SEL
End If
'バリデーション
If dto.Action <> ActionType.SEL Then
If Not GIsValid(fromControl) Then
GearsLogStack.setLog(fromControl.ID + " でのバリデーション処理でエラーが発生しました。")
Return False
End If
End If
End If
'メイン処理実行
Dim sender As GearsDTO = New GearsDTO(dto)
If fromControl Is Nothing Then
GMediator.lockDtoWhenSend(sender)
ElseIf sender.Action <> ActionType.SEL Then
reloadLockValue(fromControl).ForEach(Sub(f) sender.addFilter(f)) '楽観的ロックの選択を追加
End If
'警告無視フラグがある場合、その設定を行う処理
If Not Request.Params(CS_ALERT_IS_IGNORE_FLG) Is Nothing AndAlso Request.Params(CS_ALERT_IS_IGNORE_FLG) = "1" Then
sender.IsIgnoreAlert = True
End If
If fromControl IsNot Nothing Then
GearsLogStack.setLog(fromControl.ID + " から送信情報を収集しました(DTO作成)。", sender.toString())
If toControl Is Nothing OrElse fromControl.ID <> toControl.ID Then
result = GMediator.send(fromControl, toControl, sender)
Else
result = GMediator.execute(fromControl, sender)
End If
Else
GearsLogStack.setLog(toControl.ID + " への送信情報を収集しました(DTO作成)。", sender.toString())
result = GMediator.execute(toControl, sender)
End If
'実行結果チェック
If result Then
GearsLogStack.setLog(If(fromControl IsNot Nothing, fromControl.ID, toControl.ID) + " の更新に成功しました。")
'更新対象のロード時の値を保持 ※失敗した場合は、再処理のためロード時の値更新は行わない
saveLoadedValue()
Else
'実行結果がNGであった場合、ログをセット
For Each logitem As KeyValuePair(Of String, GearsException) In GMediator.GLog()
If Not GLog.ContainsKey(logitem.Key) Then
GLog.Add(logitem.Key, logitem.Value)
Else
GLog(logitem.Key) = logitem.Value
End If
Next
'モデルバリデーションの結果を評価する(エラー/警告など)
result = evalModel(GLog)
End If
Return result
End Function
''' <summary>
''' 登録済みコントロールのロード時の値をViewStateに保管する
''' </summary>
''' <remarks></remarks>
Private Sub saveLoadedValue()
For Each gcon As KeyValuePair(Of String, GearsControl) In GMediator.GControls
gcon.Value.LoadedValue = gcon.Value.getValue() '現時点の値をLoadedValueに移す
saveLoadedValue(gcon.Key)
If gcon.Value.IsFormAttribute Then
'ロック用項目がセットされている場合それも格納
saveLockValueIfExist(gcon.Value)
End If
Next
End Sub
''' <summary>
''' ViewStateに指定されたコントロールの値を保存する
''' </summary>
''' <param name="conId"></param>
''' <remarks></remarks>
Private Sub saveLoadedValue(ByVal conId As String)
ViewState(V_LOADED + VIEW_STATE_SEPARATOR + conId) = GMediator.GControl(conId).getValue
End Sub
''' <summary>
''' ロードされた値を取得する
''' </summary>
''' <param name="conId"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function reloadLoadedValue(ByVal conId As String) As String
Return ViewState(V_LOADED + VIEW_STATE_SEPARATOR + conId)
End Function
''' <summary>
''' 楽観ロック用の値を取得し、ViewStateに保存する
''' </summary>
''' <param name="gcon"></param>
''' <remarks></remarks>
Private Sub saveLockValueIfExist(ByVal gcon As GearsControl)
If Not gcon.DataSource Is Nothing Then
Dim lockValue As List(Of SqlFilterItem) = gcon.DataSource.getLockValue
If lockValue.Count > 0 Then
For Each item As SqlFilterItem In lockValue
ViewState(V_LOCKCOL + VIEW_STATE_SEPARATOR + gcon.ControlID + VIEW_STATE_SEPARATOR + item.Column) = item.Value
Next
End If
End If
End Sub
''' <summary>
''' ViewStateに保存しておいた楽観ロック用の値を取得する
''' </summary>
''' <param name="con"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function reloadLockValue(ByVal con As Control) As List(Of SqlFilterItem)
Dim result As New List(Of SqlFilterItem)
For Each key As String In ViewState.Keys
If key.StartsWith(V_LOCKCOL + VIEW_STATE_SEPARATOR + con.ID + VIEW_STATE_SEPARATOR) Then
Dim keySplit() As String = key.Split(VIEW_STATE_SEPARATOR)
If keySplit.Length > 0 Then
If Not keySplit(2) Is Nothing Then '1:LOCKCOL/コントロールID/ロックカラム名
result.Add(New SqlFilterItem(keySplit(2)).eq(ViewState(key)))
End If
End If
End If
Next
Return result
End Function
''' <summary>
''' ListItemのAttributeが消える対策(save)
''' </summary>
''' <param name="con"></param>
''' <remarks></remarks>
Private Sub saveListItemAttribute(ByVal con As Control)
Dim liscon As ListControl
If Not TypeOf con Is ListControl Then
Exit Sub
Else
liscon = CType(con, ListControl)
End If
For Each item As ListItem In liscon.Items
If item.Attributes.Count > 0 Then
For Each key As String In item.Attributes.Keys
'コントロールID/リストアイテムのキー/アトリビュートのキー を結合してキーを作成
ViewState(V_LIST_ATTRIBUTES + VIEW_STATE_SEPARATOR + con.ID + VIEW_STATE_SEPARATOR + item.Value + VIEW_STATE_SEPARATOR + key) = item.Attributes(key)
Next
End If
Next
End Sub
''' <summary>
''' ListItemのAttributeが消える対策(load)
''' </summary>
''' <param name="con"></param>
''' <remarks></remarks>
Private Sub loadListItemAttribute(ByVal con As Control)
Dim liscon As ListControl
If Not TypeOf con Is ListControl Then
Exit Sub
Else
liscon = CType(con, ListControl)
End If
For Each key As String In ViewState.Keys
If key.StartsWith(V_LIST_ATTRIBUTES + VIEW_STATE_SEPARATOR + con.ID + VIEW_STATE_SEPARATOR) Then 'リストアイテムのメンバ
Dim keySplit() As String = key.Split(VIEW_STATE_SEPARATOR)
If keySplit.Length > 0 Then
If Not liscon.Items.FindByValue(keySplit(2)) Is Nothing Then
liscon.Items.FindByValue(keySplit(2)).Attributes.Add(keySplit(3), ViewState(key))
End If
End If
End If
Next
End Sub
''' <summary>
''' 登録されたコントロールのAttributeに基づき、バリデーション処理を実行する
''' </summary>
''' <param name="con"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GIsValid(Optional ByVal con As Control = Nothing) As Boolean
Dim result As Boolean = True
Dim target As Control = con
GLog.Clear()
If con Is Nothing Then
target = Me
End If
'targetが子コントロールを保持している場合、子コントロールについてもバリデーションを行う
If Not target Is Nothing AndAlso target.HasControls Then
ControlSearcher.fetchControls(target, AddressOf Me.fetchEachControlValidate, AddressOf GMediator.isRegisteredControl)
ElseIf GMediator.isRegisteredControl(target) Then
fetchEachControlValidate(target, Nothing)
End If
If GLog.Count > 0 Then
result = False
'エラー項目にスタイル適用
For Each item As KeyValuePair(Of String, GearsException) In GLog
If Not GMediator.GControl(item.Key) Is Nothing AndAlso _
TypeOf GMediator.GControl(item.Key).Control Is WebControl AndAlso _
TypeOf item.Value Is GearsValidationException Then
Dim wcon As WebControl = CType(GMediator.GControl(item.Key).Control, WebControl)
wcon.CssClass += " " + GearsAttribute.ERR_STYLE
Exit For '一件発見したら抜ける(エラーメッセージがそもそもそんなに表示できないので)
End If
Next
End If
Return result
End Function
''' <summary>
''' 登録済みの各コントロールに対しバリデーションを行う
''' </summary>
''' <param name="control"></param>
''' <param name="dto"></param>
''' <remarks></remarks>
Private Sub fetchEachControlValidate(ByVal control As Control, ByRef dto As GearsDTO)
If Not GMediator.GControl(control.ID) Is Nothing Then
Dim gcon As GearsControl = GMediator.GControl(control.ID)
If Not gcon.isValidateOk() Then
GLog.Add(control.ID, New GearsValidationException(gcon.getValidationError))
End If
End If
End Sub
''' <summary>
''' モデルバリデーションの結果を評価する
''' </summary>
''' <param name="logs"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function evalModel(ByVal logs As Dictionary(Of String, GearsException)) As Boolean
Dim result As Boolean = True
'モデルバリデーションの検証
Dim mv As GearsModelValidationException _
= (From ex As KeyValuePair(Of String, GearsException) In logs
Where TypeOf ex.Value Is GearsModelValidationException
Select ex.Value).FirstOrDefault
If Not mv Is Nothing Then 'モデルバリデーションでエラーが出ている場合
If mv.Result.IsValidIgnoreAlert Then '警告のケース
Dim cs As ClientScriptManager = Me.ClientScript
'警告表示
If (Not cs.IsStartupScriptRegistered(Me.GetType, CS_ALERT_PROMPT_SCRIPT_NAME)) Then
Dim isAsync As Boolean = IsPageAsync()
Dim handler As Control = ControlSearcher.GetSubmitCausedControl(Me)
Dim alertMsg As String = "警告\n" + mv.Message.Replace(vbCrLf, "\n")
Dim scriptTag As New StringBuilder()
Dim unlock As String = " if(typeof gears.fn.unlock == 'function' ){ gears.fn.unlock(); } "
Dim releaseHidden As String = " gears.fn.removeElementById('" + CS_ALERT_IS_IGNORE_FLG + "'); "
scriptTag.Append("<script>")
scriptTag.Append("if(typeof gears.fn.lock == 'function' ){ gears.fn.lock(%TGT%); }")
scriptTag.Append("if(window.confirm('" + alertMsg + "')){")
scriptTag.Append(" document.getElementById('" + CS_ALERT_IS_IGNORE_FLG + "').value = '1'; ")
scriptTag.Append(cs.GetPostBackEventReference(handler, "") + ";")
scriptTag.Append(releaseHidden)
scriptTag.Append("}else{")
scriptTag.Append(unlock + releaseHidden)
scriptTag.Append("}")
scriptTag.Append("</script>")
If Not isAsync Then
cs.RegisterHiddenField(CS_ALERT_IS_IGNORE_FLG, "0")
cs.RegisterStartupScript(Me.GetType, CS_ALERT_PROMPT_SCRIPT_NAME, Replace(scriptTag.ToString, "%TGT%", ""), False)
Else
Dim con As Control = ControlSearcher.GetAsynchronousPostBackPanel(Me, handler)
If Not con Is Nothing Then
ScriptManager.RegisterHiddenField(con, CS_ALERT_IS_IGNORE_FLG, "0")
ScriptManager.RegisterStartupScript(con, con.GetType, CS_ALERT_PROMPT_SCRIPT_NAME, Replace(scriptTag.ToString, "%TGT%", "'" + con.ID + "'"), False)
End If
End If
End If
'警告のため、Logにエラーはあるが結果はTrueとする
result = True
Else
result = False
End If
'エラー対象コントロールにスタイルを適用
'TODO エラースタイルの付与/解除を簡単にできるよう関数化。エラースタイルの解除は初期化処理setUpPageControlsに依存しているため、要工夫
Dim eSource As WebControl = (From con As KeyValuePair(Of String, GearsControl) In GMediator.GControls
Where con.Value.DataSourceID = mv.Result.ErrorSource And TypeOf con.Value.Control Is WebControl
Select con.Value.Control).FirstOrDefault
If Not eSource Is Nothing Then
eSource.CssClass += " " + GearsAttribute.ERR_STYLE
End If
Else
result = False 'エラー
End If
Return result
End Function
''' <summary>
''' 与えられたControl領域に対し、権限の評価を行う
''' </summary>
''' <param name="con"></param>
''' <remarks></remarks>
Public Sub GIsAuth(ByVal con As Control)
'ロールベースコントロールについて、指定ロール以外の場合コントロールを非表示/非活性化
ControlSearcher.fetchControls(con, AddressOf Me.fetchRoleBaseControl, AddressOf Me.isRoleBaseControl)
End Sub
''' <summary>
''' 権限による表示/非表示などの切り替えを行う
''' </summary>
''' <param name="control"></param>
''' <param name="dto"></param>
''' <remarks></remarks>
Private Sub fetchRoleBaseControl(ByVal control As Control, ByRef dto As GearsDTO)
'ロールベースコントロールと判定されて来る
Dim result As Boolean = False
Dim evalType As String = "ENABLE"
If TypeOf control Is WebControl Then
Dim wControl = CType(control, WebControl)
'ユーザーが指定ロールを保持しているかどうか判定する
'許可されたロール
Dim allowedRoleString As String = wControl.Attributes(A_ROLE_AUTH_ALLOW)
Dim allowedRole As New List(Of String)(Split(allowedRoleString, ","))
'保持しているロールを取得(User.IsInRoleだと逐一DBアクセスになる気がするのでそれを回避)
Dim havingRole As New List(Of String)(Roles.GetRolesForUser(User.Identity.Name))
'許可されたロールを保持しているか確認
If allowedRole.Count > 0 Then
For Each role As String In allowedRole
If havingRole.IndexOf(role) > -1 Then
result = True
Exit For
End If
Next
Else
result = True '制限無し
End If
'コントロールへの設定反映
Dim evalTypeAttr = GearsControl.getControlAttribute(control, A_ROLE_EVAL_ACTION)
If Not String.IsNullOrEmpty(evalTypeAttr) Then
evalType = evalTypeAttr.ToUpper
End If
Select Case evalType
Case "ENABLE"
wControl.Enabled = result
Case "VISIBLE"
wControl.Visible = result
End Select
End If
End Sub
''' <summary>
''' ロール管理コントロールか否かを判定する
''' </summary>
''' <param name="control"></param>
''' <returns></returns>
''' <remarks></remarks>
Private Function isRoleBaseControl(ByVal control As Control) As Boolean
Return Not String.IsNullOrEmpty(GearsControl.getControlAttribute(control, A_ROLE_AUTH_ALLOW))
End Function
''' <summary>
''' エラーログをラベルに設定する
''' </summary>
''' <param name="result"></param>
''' <param name="label"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function LogToLabel(ByVal result As Boolean, ByRef label As Label) As Boolean
Dim emsg As String = ""
If GLog.Count > 0 Then
emsg = GLog.FirstLog.Message
If IsLoggingMode() Then 'ログモードの場合詳細を出力
If Not GLog.FirstLog.InnerException Is Nothing Then
emsg += " (" + GLog.FirstLog.InnerException.Message + ")"
ElseIf Not String.IsNullOrEmpty(GLog.FirstLog.MessageDetail()) Then
emsg += " (" + GLog.FirstLog.MessageDetail() + ")"
End If
End If
End If
Return LogToLabel(result, "処理は正常に行われました", emsg, label)
End Function
''' <summary>
''' 指定されたラベルに対し、メッセージをセットします<br/>
''' labelのCssClassが、resultに応じ g-msg-success か g-msg-errorに変化します(それ以外のCssClassを指定していた場合はそれが消えることはありません)<br/>
''' result=trueの場合は引数で指定されたsuccessMsgがセットされます。<br/>
''' result=falseの場合は発生したエラーがGLogから取得され、そのメッセージがセットされます。<br/>
''' </summary>
''' <param name="label">メッセージをセットするラベル</param>
''' <param name="successMsg">成功時メッセージ</param>
''' <param name="result">処理結果のBoolean</param>
''' <returns></returns>
''' <remarks></remarks>
Protected Function LogToLabel(ByVal result As Boolean, ByVal successMsg As String, ByVal errorMsg As String, ByRef label As Label) As Boolean
Dim css As String = label.CssClass
'既存スタイルを消去
css = RegularExpressions.Regex.Replace(css, "g-msg-success|g-msg-error|g-msg-warning", "")
label.CssClass = Trim(css)
'resultに応じメッセージをセット
If result Then
If GLog.Count = 0 Then
label.Text = successMsg
label.CssClass += " g-msg-success"
Else
label.Text = errorMsg
label.CssClass += " g-msg-warning"
End If
Else
label.Text = errorMsg
label.CssClass += " g-msg-error"
End If
Return result
End Function
''' <summary>
''' サーバーにインストールされたCultureとCurrentCultureが異なる場合、resourceKeyを使用しリソースファイルから値を取得する。<br/>
''' seeGlobal=Trueの場合、まずグローバルリソースを参照しなければローカルリソースを参照する。
''' </summary>
''' <param name="message"></param>
''' <param name="resourceKey"></param>
''' <param name="seeGlobal"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GGlobalize(ByVal message As String, ByVal resourceKey As String, Optional ByVal seeGlobal As Boolean = True) As Object
Dim serverCulture As Globalization.CultureInfo = CultureInfo.InstalledUICulture
Dim currentCulture As Globalization.CultureInfo = CultureInfo.CurrentCulture
If serverCulture.Equals(currentCulture) Then
Return message
Else
If seeGlobal Then
Return GetResource(resourceKey)
Else
Return GetLocalResourceObject(resourceKey)
End If
End If
End Function
''' <summary>
''' 与えられたリソースキーで、まずローカルリソースを参照しなければグローバルリソースを参照する。
''' </summary>
''' <param name="resourceKey"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function GetResource(ByVal resourceKey As String) As Object
Dim resource As Object = GetLocalResourceObject(resourceKey)
If resource Is Nothing Then
resource = GetGlobalResourceObject(GearsGlobalResource, resourceKey)
End If
Return resource
End Function
''' <summary>
''' クエリ引数を取得する
''' </summary>
''' <param name="keyname"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Function QueryValue(ByVal keyname As String) As String
Dim value As String = HttpUtility.UrlDecode(Page.Request.QueryString.Get(keyname))
If value Is Nothing Then
Return ""
Else
Return value
End If
End Function
''' <summary>
''' クエリ引数の値をDictionary型で取得する
''' </summary>
''' <param name="isIgnoreBlank">空白の値を取得するか否か</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function QueryToDictionary(Optional ByVal isIgnoreBlank As Boolean = True) As Dictionary(Of String, List(Of String))
Dim result As New Dictionary(Of String, List(Of String))
For Each key As String In Page.Request.QueryString.Keys
Dim values As String() = Page.Request.QueryString.GetValues(key)
If Not values Is Nothing Then
Dim list As New List(Of String)
For Each i As String In values
If Not (isIgnoreBlank And String.IsNullOrEmpty(i)) Then
list.Add(HttpUtility.UrlDecode(i))
End If
Next
If list.Count > 0 Then
result.Add(key, list)
End If
End If
Next
Return result
End Function
''' <summary>
''' 親ページのプロパティを取得する
''' </summary>
''' <param name="propName"></param>
''' <returns></returns>
''' <remarks></remarks>
Protected Function MasterProperty(ByVal propName As String) As Object
Dim masterType As Type = Master.GetType
Dim mp As PropertyInfo = masterType.GetProperty(propName)
If Not mp Is Nothing Then
Return mp.GetValue(Master, Nothing)
Else
Return Nothing
End If
End Function
''' <summary>
''' GearsJsAttributeが指定されたプロパティを、ページのscriptブロックに書き込む<br/>
''' </summary>
''' <remarks></remarks>
Protected Sub JsVariableWrite()
Dim jsProps = From p As PropertyInfo In Me.GetType.GetProperties
Let jsAttr As JSVariableAttribute = Attribute.GetCustomAttribute(p, GetType(JSVariableAttribute))
Where jsAttr IsNot Nothing
Select p, jsAttr
Dim cs As ClientScriptManager = Me.ClientScript
If (Not cs.IsClientScriptBlockRegistered(Me.GetType, CS_JS_VARIABLE_BLOCK)) Then
Dim script As New StringBuilder
Dim vars As New Dictionary(Of String, String)
Dim serializer As New Web.Script.Serialization.JavaScriptSerializer
For Each item In jsProps
Dim name As String = If(String.IsNullOrEmpty(item.jsAttr.Name), item.p.Name, item.jsAttr.Name)
Dim value As String = serializer.Serialize(item.p.GetValue(Me, Nothing))
vars.Add(name, value)
Next
If vars.Count > 0 Then
script.Append("var gears; " + vbCrLf)
script.Append("if (typeof gears == ""undefined"") { gears = {}; } " + vbCrLf)
script.Append("if (typeof gears.v == ""undefined"") { gears.v = {}; } " + vbCrLf)
script.Append("(function(){ var GV = gears.v;" + vbCrLf)
For Each item As KeyValuePair(Of String, String) In vars
script.Append(" GV." + item.Key + " = " + item.Value + ";")
Next
script.Append("})() ")
cs.RegisterClientScriptBlock(Me.GetType, CS_JS_VARIABLE_BLOCK, script.ToString, True)
End If
End If
End Sub
End Class
End Namespace
|
icoxfog417/Gears
|
Gears/Code/GearsPage.vb
|
Visual Basic
|
apache-2.0
| 56,279
|
'*******************************************************************************************'
' '
' 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.Drawing
Imports Bytescout.Watermarking
Imports Bytescout.Watermarking.Presets
Module Module1
Sub Main()
' Create Watermarker instance
Dim waterMarker As New Watermarker()
Dim inputFilePath As String
Dim outputFilePath As String
' Initialize library
waterMarker.InitLibrary("demo", "demo")
' Set input file name
inputFilePath = "my_sample_image.jpg"
' Set output file title
outputFilePath = "my_sample_output.jpg"
' Add image to apply watermarks to
waterMarker.AddInputFile(inputFilePath, outputFilePath)
' Create new watermark
Dim preset As New LogoImage()
' Select image file
preset.ImageFile = "mylogo.png"
' Set text transparency
preset.Transparency = 40
' Set watermark placement
preset.Placement = WatermarkPlacement.MiddleCenter
' Set scale
preset.Scale = 2.0F
' Add watermark to watermarker
waterMarker.AddWatermark(preset)
' Set output directory
waterMarker.OutputOptions.OutputDirectory = "."
' Set output format
waterMarker.OutputOptions.ImageFormat = OutputFormats.JPEG
' Apply watermarks
waterMarker.Execute()
' open generated image file in default image viewer installed in Windows
Process.Start(outputFilePath)
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Watermarking SDK/VB.NET/Add Logo to Image/Module1.vb
|
Visual Basic
|
apache-2.0
| 2,444
|
Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common
Imports System.Data.SqlClient
Partial Public Class VALogin
Inherits System.Web.UI.MasterPage
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'If Not Page.IsPostBack Then
' lblPageModDate.Text = clsModifiedDate.LastModifiction
'End If
End Sub
End Class
|
VHAINNOVATIONS/VANS
|
Code/UnCompiled/VALogin.Master.vb
|
Visual Basic
|
apache-2.0
| 418
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class SystemPermissions
'Inherits bv.common.win.BaseXtraListForm
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)
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
MyBase.Dispose(disposing)
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(SystemPermissions))
Me.SimpleButton2 = New DevExpress.XtraEditors.SimpleButton()
Me.GridControl1 = New DevExpress.XtraGrid.GridControl()
Me.GridView1 = New DevExpress.XtraGrid.Views.Grid.GridView()
Me.GridColumn1 = New DevExpress.XtraGrid.Columns.GridColumn()
Me.GridColumn2 = New DevExpress.XtraGrid.Columns.GridColumn()
CType(Me.GridControl1, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'SimpleButton2
'
resources.ApplyResources(Me.SimpleButton2, "SimpleButton2")
Me.SimpleButton2.Image = Global.EIDSS.My.Resources.Resources.Permissions__small__67_
Me.SimpleButton2.Name = "SimpleButton2"
Me.SimpleButton2.Tag = "{alwayseditable}"
'
'GridControl1
'
resources.ApplyResources(Me.GridControl1, "GridControl1")
Me.GridControl1.MainView = Me.GridView1
Me.GridControl1.Name = "GridControl1"
Me.GridControl1.ViewCollection.AddRange(New DevExpress.XtraGrid.Views.Base.BaseView() {Me.GridView1})
'
'GridView1
'
Me.GridView1.Columns.AddRange(New DevExpress.XtraGrid.Columns.GridColumn() {Me.GridColumn1, Me.GridColumn2})
Me.GridView1.GridControl = Me.GridControl1
Me.GridView1.Name = "GridView1"
Me.GridView1.OptionsBehavior.Editable = False
Me.GridView1.OptionsView.ShowGroupPanel = False
Me.GridView1.SortInfo.AddRange(New DevExpress.XtraGrid.Columns.GridColumnSortInfo() {New DevExpress.XtraGrid.Columns.GridColumnSortInfo(Me.GridColumn1, DevExpress.Data.ColumnSortOrder.Ascending)})
'
'GridColumn1
'
resources.ApplyResources(Me.GridColumn1, "GridColumn1")
Me.GridColumn1.FieldName = "SystemFunction"
Me.GridColumn1.Name = "GridColumn1"
'
'GridColumn2
'
resources.ApplyResources(Me.GridColumn2, "GridColumn2")
Me.GridColumn2.FieldName = "Modules"
Me.GridColumn2.Name = "GridColumn2"
'
'SystemPermissions
'
resources.ApplyResources(Me, "$this")
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.GridControl1)
Me.Controls.Add(Me.SimpleButton2)
Me.Editable = False
Me.FormID = "A32"
Me.HelpTopicID = "SystemFunctionsForm"
Me.LeftIcon = Global.EIDSS.My.Resources.Resources.System_Functions__large__28_
Me.Name = "SystemPermissions"
Me.ShowCancelButton = False
Me.ShowDeleteButton = False
Me.ShowSaveButton = False
Me.Controls.SetChildIndex(Me.cmdOk, 0)
Me.Controls.SetChildIndex(Me.SimpleButton2, 0)
Me.Controls.SetChildIndex(Me.GridControl1, 0)
CType(Me.GridControl1, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.GridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents SimpleButton2 As DevExpress.XtraEditors.SimpleButton
Friend WithEvents GridControl1 As DevExpress.XtraGrid.GridControl
Friend WithEvents GridView1 As DevExpress.XtraGrid.Views.Grid.GridView
Friend WithEvents GridColumn1 As DevExpress.XtraGrid.Columns.GridColumn
Friend WithEvents GridColumn2 As DevExpress.XtraGrid.Columns.GridColumn
End Class
|
EIDSS/EIDSS-Legacy
|
EIDSS v5/vb/EIDSS/EIDSS_Admin/SystemPermissions.Designer.vb
|
Visual Basic
|
bsd-2-clause
| 4,565
|
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports OpenCvSharp
Imports OpenCvSharp.CPlusPlus
Imports SampleBase
''' <summary>
''' cv::FAST
''' </summary>
Friend Module FASTSample
Public Sub Start()
Using imgSrc As New Mat(FilePath.Image.Lenna, LoadMode.Color), _
imgGray As New Mat(imgSrc.Size, MatrixType.U8C1), _
imgDst As Mat = imgSrc.Clone()
Cv2.CvtColor(imgSrc, imgGray, ColorConversion.BgrToGray, 0)
Dim keypoints() As KeyPoint
Cv2.FAST(imgGray, keypoints, 50, True)
For Each kp As KeyPoint In keypoints
imgDst.Circle(kp.Pt, 3, CvColor.Red, -1, LineType.AntiAlias, 0)
Next kp
Cv2.ImShow("FAST", imgDst)
Cv2.WaitKey(0)
Cv2.DestroyAllWindows()
End Using
End Sub
End Module
' End Namespace
|
shimat/opencvsharp_2410
|
sample/CppStyleSamplesVB/Samples/FASTSample.vb
|
Visual Basic
|
bsd-3-clause
| 907
|
'*******************************************************************************************'
' '
' 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.Drawing
Imports Bytescout.PDFExtractor
Module Module1
Sub Main()
' Create TextExtractor instance
Dim textExtractor = New TextExtractor("demo", "demo")
textExtractor.WordMatchingMode = WordMatchingMode.ExactMatch ' Set exact search (default is SmartSearch that works like in Adobe Reader)
' Create XMLExtractor instance
Dim xmlExtractor = New XMLExtractor("demo", "demo")
' Load document
textExtractor.LoadDocumentFromFile("Invoice.pdf")
xmlExtractor.LoadDocumentFromFile("Invoice.pdf")
' Results
Dim invoiceNo = String.Empty
Dim invoiceDate = String.Empty
Dim total = String.Empty
Dim tableData = String.Empty
' Iterate pages
For i As Integer = 0 To textExtractor.GetPageCount() - 1
Dim pageRectangle = textExtractor.GetPageRectangle(i)
Dim tableRect = New RectangleF(0, 0, pageRectangle.Width, 0)
' Search for "Invoice No."
If textExtractor.Find(i, "Invoice No.", False) Then
' Get the found text rectangle
Dim textRect = textExtractor.FoundText.Bounds
' Assume the text at right is the invoice number.
' Shift the rectangle to the right:
textRect.X = textRect.Right
textRect.Width = pageRectangle.Right - textRect.Left
' Set the extraction region and extract the text
textExtractor.SetExtractionArea(textRect)
invoiceNo = textExtractor.GetTextFromPage(i).Trim()
End If
' Search for "Invoice Date" and extract text at right
If textExtractor.Find(i, "Invoice Date", False) Then
Dim textRect = textExtractor.FoundText.Bounds
textRect.X = textRect.Right
textRect.Width = pageRectangle.Right - textRect.Left
textExtractor.SetExtractionArea(textRect)
invoiceDate = textExtractor.GetTextFromPage(i).Trim()
End If
' Search for "Quantity" keyword to detect the top of the tabular data rectangle
If textExtractor.Find(i, "Quantity", False) Then
' Keep the top table coordinate
tableRect.Y = textExtractor.FoundText.Bounds.Top ' use textRect.Bottom if you want to skip column headers
End If
' Search and extract "TOTAL" (it will be also the bottom of tabular data rectangle)
If textExtractor.Find(i, "TOTAL", True) Then ' case sensitive!
Dim textRect = textExtractor.FoundText.Bounds
textRect.X = textRect.Right
textRect.Width = pageRectangle.Right - textRect.Left
textExtractor.SetExtractionArea(textRect)
total = textExtractor.GetTextFromPage(i).Trim()
' Calculate the table height
tableRect.Height = textRect.Top - tableRect.Top
End If
' Extract tabular data using XMLExtractor
If tableRect.Height > 0 Then
xmlExtractor.SetExtractionArea(tableRect)
tableData = xmlExtractor.GetXMLFromPage(i)
End If
Next
' Display extracted data
Console.WriteLine("Invoice No.: " + invoiceNo)
Console.WriteLine("Invoice Date: " + invoiceDate)
Console.WriteLine("TOTAL: " + total)
Console.WriteLine("Table Data: ")
Console.WriteLine(tableData)
Console.WriteLine("Press any key...")
Console.ReadKey()
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Solutions/Parse Invoice/VB.NET/Module1.vb
|
Visual Basic
|
apache-2.0
| 4,669
|
' 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.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Methods, Properties, and Events all can override or hide members.
''' This class has helper methods and extensions for sharing by multiple symbol types.
''' </summary>
Friend Class OverrideHidingHelper
''' <summary>
''' Check for overriding and hiding errors in container and report them via diagnostics.
''' </summary>
''' <param name="container">Containing type to check. Should be an original definition.</param>
''' <param name="diagnostics">Place diagnostics here.</param>
Public Shared Sub CheckHidingAndOverridingForType(container As SourceMemberContainerTypeSymbol, diagnostics As DiagnosticBag)
Debug.Assert(container.IsDefinition) ' Don't do this on constructed types
Select Case container.TypeKind
Case TypeKind.Class, TypeKind.Interface, TypeKind.Structure
CheckMembersAgainstBaseType(container, diagnostics)
CheckAllAbstractsAreOverriddenAndNotHidden(container, diagnostics)
Case Else
' Modules, Enums and Delegates have nothing to do.
End Select
End Sub
' Determine if two method or property signatures match, using the rules in 4.1.1, i.e., ByRef mismatches,
' differences in optional parameters, custom modifiers, return type are not considered. An optional parameter
' matches if the corresponding parameter in the other signature is not there, optional of any type,
' or non-optional of matching type.
'
' Note that this sense of matching is not transitive. I.e.
' A) f(x as integer)
' B) f(x as integer, optional y as String = "")
' C) f(x as integer, y As String)
' A matches B, B matches C, but A doesn't match C
'
' Note that (A) and (B) above do match in terms of Dev10 behavior when we look for overridden
' methods/properties. We still keep this behavior in Roslyn to be able to generate the same
' error in the following case:
'
' Class Base
' Public Overridable Sub f(x As Integer)
' End Sub
' End Class
'
' Class Derived
' Inherits Base
' Public Overrides Sub f(x As Integer, Optional y As String = "")
' End Sub
' End Class
'
' >>> error BC30308: 'Public Overrides Sub f(x As Integer, [y As String = ""])' cannot override
' 'Public Overridable Sub f(x As Integer)' because they differ by optional parameters.
'
' In this sense the method returns True if signatures match enough to be
' considered a candidate of overridden member.
'
' But for new overloading rules (overloading based on optional parameters) introduced in Dev11
' we also need more detailed info on the two members being compared, namely do their signatures
' also match taking into account total parameter count and parameter optionality (optional/required)?
' We return this information in 'exactMatch' parameter.
'
' So when searching for overridden members we prefer exactly matched candidates in case we could
' find them. This helps properly find overridden members in the following case:
'
' Class Base
' Public Overridable Sub f(x As Integer)
' End Sub
' Public Overridable Sub f(x As Integer, Optional y As String = "")
' End Sub
' End Class
'
' Class Derived
' Inherits Base
' Public Overrides Sub f(x As Integer)
' End Sub
' Public Overrides Sub f(x As Integer, Optional y As String = "") ' << Dev11 Beta reports BC30308
' End Sub
' End Class
'
' Note that Dev11 Beta wrongly reports BC30308 on the last Sub in this case.
'
Public Shared Function SignaturesMatch(sym1 As Symbol, sym2 As Symbol, <Out()> ByRef exactMatch As Boolean, <Out()> ByRef exactMatchIgnoringCustomModifiers As Boolean) As Boolean
' NOTE: we should NOT ignore extra required parameters as for overloading
Const mismatchesForOverriding As SymbolComparisonResults =
(SymbolComparisonResults.AllMismatches And (Not SymbolComparisonResults.MismatchesForConflictingMethods)) Or
SymbolComparisonResults.CustomModifierMismatch
' 'Exact match' means that the number of parameters and
' parameter 'optionality' match on two symbol candidates.
Const exactMatchIgnoringCustomModifiersMask As SymbolComparisonResults =
SymbolComparisonResults.TotalParameterCountMismatch Or SymbolComparisonResults.OptionalParameterTypeMismatch
' Note that exact match doesn't care about tuple element names.
Const exactMatchMask As SymbolComparisonResults =
exactMatchIgnoringCustomModifiersMask Or SymbolComparisonResults.CustomModifierMismatch
Dim results As SymbolComparisonResults = DetailedSignatureCompare(sym1, sym2, mismatchesForOverriding)
' no match
If (results And Not exactMatchMask) <> 0 Then
exactMatch = False
exactMatchIgnoringCustomModifiers = False
Return False
End If
' match
exactMatch = (results And exactMatchMask) = 0
exactMatchIgnoringCustomModifiers = (results And exactMatchIgnoringCustomModifiersMask) = 0
Debug.Assert(Not exactMatch OrElse exactMatchIgnoringCustomModifiers)
Return True
End Function
Friend Shared Function DetailedSignatureCompare(
sym1 As Symbol,
sym2 As Symbol,
comparisons As SymbolComparisonResults,
Optional stopIfAny As SymbolComparisonResults = 0
) As SymbolComparisonResults
If sym1.Kind = SymbolKind.Property Then
Return PropertySignatureComparer.DetailedCompare(DirectCast(sym1, PropertySymbol), DirectCast(sym2, PropertySymbol), comparisons, stopIfAny)
Else
Return MethodSignatureComparer.DetailedCompare(DirectCast(sym1, MethodSymbol), DirectCast(sym2, MethodSymbol), comparisons, stopIfAny)
End If
End Function
''' <summary>
''' Check each member of container for constraints against the base type. For methods and properties and events,
''' checking overriding and hiding constraints. For other members, just check for hiding issues.
''' </summary>
''' <param name="container">Containing type to check. Should be an original definition.</param>
''' <param name="diagnostics">Place diagnostics here.</param>
''' <remarks></remarks>
Private Shared Sub CheckMembersAgainstBaseType(container As SourceMemberContainerTypeSymbol, diagnostics As DiagnosticBag)
For Each member In container.GetMembers()
If CanOverrideOrHide(member) Then
Select Case member.Kind
Case SymbolKind.Method
Dim methodMember = DirectCast(member, MethodSymbol)
If Not methodMember.IsAccessor Then
If methodMember.IsOverrides Then
OverrideHidingHelper(Of MethodSymbol).CheckOverrideMember(methodMember, methodMember.OverriddenMembers, diagnostics)
ElseIf methodMember.IsNotOverridable Then
'Method is not marked as Overrides but is marked as Not Overridable
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), methodMember.Locations(0)))
End If
End If
Case SymbolKind.Property
Dim propMember = DirectCast(member, PropertySymbol)
If propMember.IsOverrides Then
OverrideHidingHelper(Of PropertySymbol).CheckOverrideMember(propMember, propMember.OverriddenMembers, diagnostics)
ElseIf propMember.IsNotOverridable Then
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_NotOverridableRequiresOverrides), propMember.Locations(0)))
End If
End Select
' TODO: only do this check if CheckOverrideMember didn't find an error?
CheckShadowing(container, member, diagnostics)
End If
Next
End Sub
''' <summary>
''' If the "container" is a non-MustInherit, make sure it has no MustOverride Members
''' If "container" is a non-MustInherit inheriting from a MustInherit, make sure that all MustOverride members
''' have been overridden.
''' If "container" is a MustInherit inheriting from a MustInherit, make sure that no MustOverride members
''' have been shadowed.
''' </summary>
Private Shared Sub CheckAllAbstractsAreOverriddenAndNotHidden(container As NamedTypeSymbol, diagnostics As DiagnosticBag)
' Check that a non-MustInherit class doesn't have any MustOverride members
If Not (container.IsMustInherit OrElse container.IsNotInheritable) Then
For Each member In container.GetMembers()
If member.IsMustOverride Then
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustOverridesInClass1, container.Name), container.Locations(0)))
Exit For
End If
Next
End If
Dim baseType As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics
If baseType IsNot Nothing AndAlso baseType.IsMustInherit Then
' Check that all MustOverride members in baseType or one of its bases are overridden/not shadowed somewhere along the chain.
' Do this by accumulating a set of all the methods that have been overridden, if we encounter a MustOverride
' method that is not in the set, then report it. We can do this in a single pass up the base chain.
Dim overriddenMembers As HashSet(Of Symbol) = New HashSet(Of Symbol)()
Dim unimplementedMembers As ArrayBuilder(Of Symbol) = ArrayBuilder(Of Symbol).GetInstance()
Dim currType = container
While currType IsNot Nothing
For Each member In currType.GetMembers()
If CanOverrideOrHide(member) AndAlso Not member.IsAccessor Then ' accessors handled by their containing properties.
If member.IsOverrides Then
Dim overriddenMember = GetOverriddenMember(member)
If overriddenMember IsNot Nothing Then
overriddenMembers.Add(GetOverriddenMember(member))
End If
End If
If member.IsMustOverride AndAlso currType IsNot container Then
If Not overriddenMembers.Contains(member) Then
unimplementedMembers.Add(member)
End If
End If
End If
Next
currType = currType.BaseTypeNoUseSiteDiagnostics
End While
If unimplementedMembers.Any Then
If container.IsMustInherit Then
' It is OK for a IsMustInherit type to have unimplemented abstract members. But, it is not allowed
' to shadow them. Check each one to see if it is shadowed by a member of "container". Don't report for
' accessor hiding accessor, because we'll report it on the property.
Dim hidingSymbols As New HashSet(Of Symbol) ' don't report more than once per hiding symbols
For Each mustOverrideMember In unimplementedMembers
For Each hidingMember In container.GetMembers(mustOverrideMember.Name)
If DoesHide(hidingMember, mustOverrideMember) AndAlso Not hidingSymbols.Contains(hidingMember) Then
ReportShadowingMustOverrideError(hidingMember, mustOverrideMember, diagnostics)
hidingSymbols.Add(hidingMember)
End If
Next
Next
Else
' This is not a IsMustInherit type. Some members should be been overridden but weren't.
' Create a single error that lists all of the unimplemented members.
Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(unimplementedMembers.Count)
For Each member In unimplementedMembers
If Not member.IsAccessor Then
If member.Kind = SymbolKind.Event Then
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_MustInheritEventNotOverridden,
member,
CustomSymbolDisplayFormatter.QualifiedName(member.ContainingType),
CustomSymbolDisplayFormatter.ShortErrorName(container)),
container.Locations(0)))
Else
diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_UnimplementedMustOverride, member.ContainingType, member))
End If
Else
' accessor is reported on the containing property.
Debug.Assert(unimplementedMembers.Contains(DirectCast(member, MethodSymbol).AssociatedSymbol))
End If
Next
If diagnosticInfos.Count > 0 Then
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_BaseOnlyClassesMustBeExplicit2,
CustomSymbolDisplayFormatter.ShortErrorName(container),
New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())),
container.Locations(0)))
Else
diagnosticInfos.Free()
End If
End If
End If
unimplementedMembers.Free()
End If
End Sub
' Compare two symbols of the same name to see if one actually does hide the other.
Private Shared Function DoesHide(hidingMember As Symbol, hiddenMember As Symbol) As Boolean
Debug.Assert(IdentifierComparison.Equals(hidingMember.Name, hiddenMember.Name))
Select Case hidingMember.Kind
Case SymbolKind.Method
If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Method Then
Dim hidingMethod = DirectCast(hidingMember, MethodSymbol)
If hidingMethod.IsOverrides Then
' For Dev10 compatibility, an override is not considered as hiding (see bug 11728)
Return False
Else
Dim exactMatchIgnoringCustomModifiers As Boolean = False
Return OverrideHidingHelper(Of MethodSymbol).SignaturesMatch(hidingMethod, DirectCast(hiddenMember, MethodSymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers
End If
Else
Return True
End If
Case SymbolKind.Property
If hidingMember.IsOverloads AndAlso hiddenMember.Kind = SymbolKind.Property Then
Dim hidingProperty = DirectCast(hidingMember, PropertySymbol)
If hidingProperty.IsOverrides Then
' For Dev10 compatibility, an override is not considered as hiding (see bug 11728)
Return False
Else
Dim exactMatchIgnoringCustomModifiers As Boolean = False
Return OverrideHidingHelper(Of PropertySymbol).SignaturesMatch(hidingProperty, DirectCast(hiddenMember, PropertySymbol), Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers
End If
Else
Return True
End If
Case Else
Return True
End Select
End Function
''' <summary>
''' Report any diagnostics related to shadowing for a member.
''' </summary>
Protected Shared Sub CheckShadowing(container As SourceMemberContainerTypeSymbol,
member As Symbol,
diagnostics As DiagnosticBag)
Dim memberIsOverloads = member.IsOverloads()
Dim warnForHiddenMember As Boolean = Not member.ShadowsExplicitly
If Not warnForHiddenMember Then
Return ' short circuit unnecessary checks.
End If
If container.IsInterfaceType() Then
For Each currentBaseInterface In container.AllInterfacesNoUseSiteDiagnostics
CheckShadowingInBaseType(container, member, memberIsOverloads, currentBaseInterface, diagnostics, warnForHiddenMember)
Next
Else
Dim currentBase As NamedTypeSymbol = container.BaseTypeNoUseSiteDiagnostics
While currentBase IsNot Nothing
CheckShadowingInBaseType(container, member, memberIsOverloads, currentBase, diagnostics, warnForHiddenMember)
currentBase = currentBase.BaseTypeNoUseSiteDiagnostics
End While
End If
End Sub
' Check shadowing against members in one base type.
Private Shared Sub CheckShadowingInBaseType(container As SourceMemberContainerTypeSymbol,
member As Symbol,
memberIsOverloads As Boolean,
baseType As NamedTypeSymbol,
diagnostics As DiagnosticBag,
ByRef warnForHiddenMember As Boolean)
Debug.Assert(container.IsDefinition)
If warnForHiddenMember Then
For Each hiddenMember In baseType.GetMembers(member.Name)
If AccessCheck.IsSymbolAccessible(hiddenMember, container, Nothing, useSiteDiagnostics:=Nothing) AndAlso
(Not memberIsOverloads OrElse
hiddenMember.Kind <> member.Kind OrElse
hiddenMember.IsWithEventsProperty OrElse
(member.Kind = SymbolKind.Method AndAlso DirectCast(member, MethodSymbol).IsUserDefinedOperator() <> DirectCast(hiddenMember, MethodSymbol).IsUserDefinedOperator()) OrElse
member.IsAccessor() <> hiddenMember.IsAccessor) AndAlso
Not (member.IsAccessor() AndAlso hiddenMember.IsAccessor) Then
'special case for classes of different arity . Do not warn in such case
If member.Kind = SymbolKind.NamedType AndAlso
hiddenMember.Kind = SymbolKind.NamedType AndAlso
member.GetArity <> hiddenMember.GetArity Then
Continue For
End If
' Found an accessible member we are hiding and not overloading.
' We don't warn if accessor hides accessor, because we will warn on the containing properties instead.
' Give warning for shadowing hidden member
ReportShadowingDiagnostic(member, hiddenMember, diagnostics)
warnForHiddenMember = False ' don't warn for more than one hidden member.
Exit For
End If
Next
End If
End Sub
' Report diagnostic for one member shadowing another, but no Shadows modifier was present.
Private Shared Sub ReportShadowingDiagnostic(hidingMember As Symbol,
hiddenMember As Symbol,
diagnostics As DiagnosticBag)
Debug.Assert(Not (hidingMember.IsAccessor() AndAlso hiddenMember.IsAccessor))
Dim associatedhiddenSymbol = hiddenMember.ImplicitlyDefinedBy
If associatedhiddenSymbol Is Nothing AndAlso hiddenMember.IsUserDefinedOperator() AndAlso Not hidingMember.IsUserDefinedOperator() Then
' For the purpose of this check, operator methods are treated as implicitly defined by themselves.
associatedhiddenSymbol = hiddenMember
End If
Dim associatedhidingSymbol = hidingMember.ImplicitlyDefinedBy
If associatedhidingSymbol Is Nothing AndAlso hidingMember.IsUserDefinedOperator() AndAlso Not hiddenMember.IsUserDefinedOperator() Then
' For the purpose of this check, operator methods are treated as implicitly defined by themselves.
associatedhidingSymbol = hidingMember
End If
If associatedhiddenSymbol IsNot Nothing Then
If associatedhidingSymbol IsNot Nothing Then
If Not IdentifierComparison.Equals(associatedhiddenSymbol.Name,
associatedhidingSymbol.Name) Then
' both members are defined implicitly by members of different names
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsSynthMember7,
associatedhidingSymbol.GetKindText(),
AssociatedSymbolName(associatedhidingSymbol),
hidingMember.Name,
associatedhiddenSymbol.GetKindText(),
AssociatedSymbolName(associatedhiddenSymbol),
hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
hidingMember.Locations(0)))
End If
Return
End If
' explicitly defined member hiding implicitly defined member
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_MemberShadowsSynthMember6,
hidingMember.GetKindText(), hidingMember.Name,
associatedhiddenSymbol.GetKindText(), AssociatedSymbolName(associatedhiddenSymbol), hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
hidingMember.Locations(0)))
ElseIf associatedhidingSymbol IsNot Nothing Then
' implicitly defined member hiding explicitly defined member
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_SynthMemberShadowsMember5,
associatedhidingSymbol.GetKindText(), AssociatedSymbolName(associatedhidingSymbol),
hidingMember.Name, hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
associatedhidingSymbol.Locations(0)))
ElseIf hidingMember.Kind = hiddenMember.Kind AndAlso
(hidingMember.Kind = SymbolKind.Property OrElse hidingMember.Kind = SymbolKind.Method) AndAlso
Not (hiddenMember.IsWithEventsProperty OrElse hidingMember.IsWithEventsProperty) Then
' method hiding method or property hiding property; message depends on if hidden symbol is overridable.
Dim id As ERRID
If hiddenMember.IsOverridable OrElse hiddenMember.IsOverrides OrElse (hiddenMember.IsMustOverride AndAlso Not hiddenMember.ContainingType.IsInterface) Then
id = ERRID.WRN_MustOverride2
Else
id = ERRID.WRN_MustOverloadBase4
End If
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id,
hidingMember.GetKindText(), hidingMember.Name, hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
hidingMember.Locations(0)))
Else
' all other hiding scenarios.
Debug.Assert(hidingMember.Locations(0).IsInSource)
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.WRN_OverrideType5,
hidingMember.GetKindText(), hidingMember.Name, hiddenMember.GetKindText(), hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
hidingMember.Locations(0)))
End If
End Sub
Public Shared Function AssociatedSymbolName(associatedSymbol As Symbol) As String
Return If(associatedSymbol.IsUserDefinedOperator(),
SyntaxFacts.GetText(OverloadResolution.GetOperatorTokenKind(associatedSymbol.Name)),
associatedSymbol.Name)
End Function
' Report diagnostic for a member shadowing a MustOverride.
Private Shared Sub ReportShadowingMustOverrideError(hidingMember As Symbol,
hiddenMember As Symbol,
diagnostics As DiagnosticBag)
Debug.Assert(hidingMember.Locations(0).IsInSource)
If hidingMember.IsAccessor() Then
' accessor hiding non-accessorTODO
Dim associatedHidingSymbol = DirectCast(hidingMember, MethodSymbol).AssociatedSymbol
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_SynthMemberShadowsMustOverride5,
hidingMember,
associatedHidingSymbol.GetKindText(), associatedHidingSymbol.Name,
hiddenMember.ContainingType.GetKindText(),
CustomSymbolDisplayFormatter.ShortErrorName(hiddenMember.ContainingType)),
hidingMember.Locations(0)))
Else
' Basic hiding case
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CantShadowAMustOverride1, hidingMember),
hidingMember.Locations(0)))
End If
End Sub
''' <summary>
''' Some symbols do not participate in overriding/hiding (e.g. constructors). Accessors are consider
''' to override or hide.
''' </summary>
Friend Shared Function CanOverrideOrHide(sym As Symbol) As Boolean
If sym.Kind <> SymbolKind.Method Then
Return True
Else
Select Case DirectCast(sym, MethodSymbol).MethodKind
Case MethodKind.LambdaMethod, MethodKind.Constructor, MethodKind.SharedConstructor
Return False
Case MethodKind.Conversion, MethodKind.DelegateInvoke, MethodKind.UserDefinedOperator, MethodKind.Ordinary, MethodKind.DeclareMethod,
MethodKind.EventAdd, MethodKind.EventRaise, MethodKind.EventRemove,
MethodKind.PropertyGet, MethodKind.PropertySet
Return True
Case Else
Debug.Assert(False, String.Format("Unexpected method kind '{0}'", DirectCast(sym, MethodSymbol).MethodKind))
Return False
End Select
End If
End Function
' If this member overrides another member, return that overridden member, else return Nothing.
Protected Shared Function GetOverriddenMember(sym As Symbol) As Symbol
Select Case sym.Kind
Case SymbolKind.Method
Return DirectCast(sym, MethodSymbol).OverriddenMethod
Case SymbolKind.Property
Return DirectCast(sym, PropertySymbol).OverriddenProperty
Case SymbolKind.Event
Return DirectCast(sym, EventSymbol).OverriddenEvent
End Select
Return Nothing
End Function
''' <summary>
''' If a method had a virtual inaccessible override, then an explicit override in metadata is needed
''' to make it really override what it intends to override, and "skip" the inaccessible virtual
''' method.
''' </summary>
Public Shared Function RequiresExplicitOverride(method As MethodSymbol) As Boolean
If method.IsAccessor Then
If TypeOf method.AssociatedSymbol Is EventSymbol Then
' VB does not override events
Return False
End If
Return RequiresExplicitOverride(DirectCast(method.AssociatedSymbol, PropertySymbol))
End If
If method.OverriddenMethod IsNot Nothing Then
For Each inaccessibleOverride In method.OverriddenMembers.InaccessibleMembers
If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then
Return True
End If
Next
End If
Return False
End Function
Private Shared Function RequiresExplicitOverride(prop As PropertySymbol) As Boolean
If prop.OverriddenProperty IsNot Nothing Then
For Each inaccessibleOverride In prop.OverriddenMembers.InaccessibleMembers
If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then
Return True
End If
Next
End If
Return False
End Function
Private Shared Function RequiresExplicitOverride([event] As EventSymbol) As Boolean
If [event].OverriddenEvent IsNot Nothing Then
For Each inaccessibleOverride In [event].OverriddenOrHiddenMembers.InaccessibleMembers
If inaccessibleOverride.IsOverridable OrElse inaccessibleOverride.IsMustOverride OrElse inaccessibleOverride.IsOverrides Then
Return True
End If
Next
End If
Return False
End Function
End Class
''' <summary>
''' Many of the methods want to generically work on properties, methods (and maybe events) as TSymbol. We put all these
''' methods into a generic class for convenience.
''' </summary>
Friend Class OverrideHidingHelper(Of TSymbol As Symbol)
Inherits OverrideHidingHelper
' Comparer for comparing signatures of TSymbols in a runtime-equivalent way.
' It is not ReadOnly because it is initialized by a Shared Sub New of another instance of this class.
Private Shared s_runtimeSignatureComparer As IEqualityComparer(Of TSymbol)
' Initialize the various kinds of comparers.
Shared Sub New()
OverrideHidingHelper(Of MethodSymbol).s_runtimeSignatureComparer = MethodSignatureComparer.RuntimeMethodSignatureComparer
OverrideHidingHelper(Of PropertySymbol).s_runtimeSignatureComparer = PropertySignatureComparer.RuntimePropertySignatureComparer
OverrideHidingHelper(Of EventSymbol).s_runtimeSignatureComparer = EventSignatureComparer.RuntimeEventSignatureComparer
End Sub
''' <summary>
''' Walk up the type hierarchy from ContainingType and list members that this
''' method overrides (accessible methods/properties with the same signature, if this
''' method is declared "override").
'''
''' Methods in the overridden list may not be virtual or may have different
''' accessibilities, types, accessors, etc. They are really candidates to be
''' overridden.
'''
''' All found accessible candidates of overridden members are collected in two
''' builders, those with 'exactly' matching signatures and those with 'generally'
''' or 'inexactly' matching signatures. 'Exact' signature match is a 'general'
''' signature match which also does not have mismatches in total number of parameters
''' and/or types of optional parameters. See also comments on correspondent
''' OverriddenMembersResult(Of TSymbol) properties.
'''
''' 'Inexactly' matching candidates are only collected for reporting Dev10/Dev11
''' errors like BC30697 and others. We collect 'inexact' matching candidates until
''' we find any 'exact' match.
'''
''' Also remembers inaccessible members that are found, but these do not prevent
''' continuing to search for accessible members.
'''
''' </summary>
''' <remarks>
''' In the presence of non-VB types, the meaning of "same signature" is rather
''' complicated. If this method isn't from source, then it refers to the runtime's
''' notion of signature (i.e. including return type, custom modifiers, etc).
''' If this method is from source, use the VB version of signature. Note that
''' Dev10 C# has a rule that prefers members with less custom modifiers. Dev 10 VB has no
''' such rule, so I'm not adding such a rule here.
''' </remarks>
Friend Shared Function MakeOverriddenMembers(overridingSym As TSymbol) As OverriddenMembersResult(Of TSymbol)
If Not overridingSym.IsOverrides OrElse Not CanOverrideOrHide(overridingSym) Then
Return OverriddenMembersResult(Of TSymbol).Empty
End If
' We should not be here for constructed methods, since overriding/hiding doesn't really make sense for them.
Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).ConstructedFrom <> overridingSym))
' We should not be here for property accessors (but ok for event accessors).
' TODO: When we support virtual events, that might change.
Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso
(DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse
DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet)))
' NOTE: If our goal is to make source references and metadata references indistinguishable, then we should really
' distinguish between the "current" compilation and other compilations, rather than between source and metadata.
' However, doing so would require adding a new parameter to the public API (i.e. which compilation to consider
' "current") and that extra complexity does not seem to provide significant benefit. Our fallback goal is:
' if a source assembly builds successfully, then compilations referencing that assembly should build against
' both source and metadata or fail to build against both source and metadata. Our expectation is that an exact
' match (which is required for successful compilation) should roundtrip through metadata, so this requirement
' should be met.
Dim overridingIsFromSomeCompilation As Boolean = overridingSym.Dangerous_IsFromSomeCompilationIncludingRetargeting
Dim containingType As NamedTypeSymbol = overridingSym.ContainingType
Dim overriddenBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
Dim inexactOverriddenMembers As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
Dim inaccessibleBuilder As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
Debug.Assert(Not containingType.IsInterface, "An interface member can't be marked overrides")
Dim currType As NamedTypeSymbol = containingType.BaseTypeNoUseSiteDiagnostics
While currType IsNot Nothing
If FindOverriddenMembersInType(overridingSym, overridingIsFromSomeCompilation, containingType, currType, overriddenBuilder, inexactOverriddenMembers, inaccessibleBuilder) Then
Exit While ' Once we hit an overriding or hiding member, we're done.
End If
currType = currType.BaseTypeNoUseSiteDiagnostics
End While
Return OverriddenMembersResult(Of TSymbol).Create(overriddenBuilder.ToImmutableAndFree(),
inexactOverriddenMembers.ToImmutableAndFree(),
inaccessibleBuilder.ToImmutableAndFree())
End Function
''' <summary>
''' Look for overridden members in a specific type. Return true if we find an overridden member candidate
''' with 'exact' signature match, or we hit a member that hides. See comments on MakeOverriddenMembers(...)
''' for description of 'exact' and 'inexact' signature matches.
'''
''' Also remember any inaccessible members that we see.
''' </summary>
''' <param name="overridingSym">Syntax that overriding or hiding.</param>
''' <param name="overridingIsFromSomeCompilation">True if "overridingSym" is from source (this.IsFromSomeCompilation).</param>
''' <param name="overridingContainingType">The type that contains this method (this.ContainingType).</param>
''' <param name="currType">The type to search.</param>
''' <param name="overriddenBuilder">Builder to place exactly-matched overridden member candidates in. </param>
''' <param name="inexactOverriddenMembers">Builder to place inexactly-matched overridden member candidates in. </param>
''' <param name="inaccessibleBuilder">Builder to place exactly-matched inaccessible overridden member candidates in. </param>
Private Shared Function FindOverriddenMembersInType(overridingSym As TSymbol,
overridingIsFromSomeCompilation As Boolean,
overridingContainingType As NamedTypeSymbol,
currType As NamedTypeSymbol,
overriddenBuilder As ArrayBuilder(Of TSymbol),
inexactOverriddenMembers As ArrayBuilder(Of TSymbol),
inaccessibleBuilder As ArrayBuilder(Of TSymbol)) As Boolean
' Note that overriddenBuilder may contain some non-exact
' matched symbols found in previous iterations
' We should not be here for property accessors (but ok for event accessors).
' TODO: When we support virtual events, that might change.
Debug.Assert(Not (TypeOf overridingSym Is MethodSymbol AndAlso
(DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertyGet OrElse
DirectCast(DirectCast(overridingSym, Symbol), MethodSymbol).MethodKind = MethodKind.PropertySet)))
Dim stopLookup As Boolean = False
Dim haveExactMatch As Boolean = False
Dim overriddenInThisType As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
For Each sym In currType.GetMembers(overridingSym.Name)
ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers,
inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch)
Next
If overridingSym.Kind = SymbolKind.Property Then
Dim prop = DirectCast(DirectCast(overridingSym, Object), PropertySymbol)
If prop.IsImplicitlyDeclared AndAlso prop.IsWithEvents Then
For Each sym In currType.GetSynthesizedWithEventsOverrides()
If sym.Name.Equals(prop.Name) Then
ProcessMemberWithMatchingName(sym, overridingSym, overridingIsFromSomeCompilation, overridingContainingType, inexactOverriddenMembers,
inaccessibleBuilder, overriddenInThisType, stopLookup, haveExactMatch)
End If
Next
End If
End If
If overriddenInThisType.Count > 1 Then
RemoveMembersWithConflictingAccessibility(overriddenInThisType)
End If
If overriddenInThisType.Count > 0 Then
If haveExactMatch Then
Debug.Assert(stopLookup)
overriddenBuilder.Clear()
End If
If overriddenBuilder.Count = 0 Then
overriddenBuilder.AddRange(overriddenInThisType)
End If
End If
overriddenInThisType.Free()
Return stopLookup
End Function
Private Shared Sub ProcessMemberWithMatchingName(
sym As Symbol,
overridingSym As TSymbol,
overridingIsFromSomeCompilation As Boolean,
overridingContainingType As NamedTypeSymbol,
inexactOverriddenMembers As ArrayBuilder(Of TSymbol),
inaccessibleBuilder As ArrayBuilder(Of TSymbol),
overriddenInThisType As ArrayBuilder(Of TSymbol),
ByRef stopLookup As Boolean,
ByRef haveExactMatch As Boolean
)
' Use original definition for accessibility check, because substitutions can cause
' reductions in accessibility that aren't appropriate (see bug #12038 for example).
Dim accessible = AccessCheck.IsSymbolAccessible(sym.OriginalDefinition, overridingContainingType.OriginalDefinition, Nothing, useSiteDiagnostics:=Nothing)
If sym.Kind = overridingSym.Kind AndAlso
CanOverrideOrHide(sym) Then
Dim member As TSymbol = DirectCast(sym, TSymbol)
Dim exactMatch As Boolean = True ' considered to be True for all runtime signature comparisons
Dim exactMatchIgnoringCustomModifiers As Boolean = True ' considered to be True for all runtime signature comparisons
If If(overridingIsFromSomeCompilation,
sym.IsWithEventsProperty = overridingSym.IsWithEventsProperty AndAlso
SignaturesMatch(overridingSym, member, exactMatch, exactMatchIgnoringCustomModifiers),
s_runtimeSignatureComparer.Equals(overridingSym, member)) Then
If accessible Then
If exactMatchIgnoringCustomModifiers Then
If exactMatch Then
If Not haveExactMatch Then
haveExactMatch = True
stopLookup = True
overriddenInThisType.Clear()
End If
overriddenInThisType.Add(member)
ElseIf Not haveExactMatch Then
overriddenInThisType.Add(member)
End If
Else
' Add only if not hidden by signature
AddMemberToABuilder(member, inexactOverriddenMembers)
End If
Else
If exactMatchIgnoringCustomModifiers Then
' only exact matched methods are to be added
inaccessibleBuilder.Add(member)
End If
End If
ElseIf Not member.IsOverloads() AndAlso accessible Then
' hiding symbol by name
stopLookup = True
End If
ElseIf accessible Then
' Any accessible symbol of different kind stops further lookup
stopLookup = True
End If
End Sub
Private Shared Sub AddMemberToABuilder(member As TSymbol,
builder As ArrayBuilder(Of TSymbol))
' We should only add a member to a builder if it does not match any
' symbols from previously processed (derived) classes
' This is supposed to help avoid adding multiple symbols one of
' which overrides another one, in the following case
' C1
' Overridable Sub S(x As Integer, Optional y As Integer = 1)
'
' C2: C1
' Overridable Sub S(x As Integer)
'
' C3: C2
' Overrides Sub S(x As Integer)
'
' C4: C3
' Overrides Sub S(x As Integer, Optional y As Integer = 1)
' In the case above we should not add 'S(x As Integer)' twice
' We don't use 'OverriddenMethod' property on MethodSymbol because
' right now it does not cache the result, so we want to avoid
' unnecessary nested calls to 'MakeOverriddenMembers'
Dim memberContainingType As NamedTypeSymbol = member.ContainingType
For i = 0 To builder.Count - 1
Dim exactMatchIgnoringCustomModifiers As Boolean = False
If Not TypeSymbol.Equals(builder(i).ContainingType, memberContainingType, TypeCompareKind.ConsiderEverything) AndAlso
SignaturesMatch(builder(i), member, Nothing, exactMatchIgnoringCustomModifiers) AndAlso exactMatchIgnoringCustomModifiers Then
' Do NOT add
Exit Sub
End If
Next
builder.Add(member)
End Sub
' Check a member that is marked Override against it's base and report any necessary diagnostics. The already computed
' overridden members are passed in.
Friend Shared Sub CheckOverrideMember(member As TSymbol,
overriddenMembersResult As OverriddenMembersResult(Of TSymbol),
diagnostics As DiagnosticBag)
Debug.Assert(overriddenMembersResult IsNot Nothing)
Dim memberIsShadows As Boolean = member.ShadowsExplicitly
Dim memberIsOverloads As Boolean = member.IsOverloads()
Dim overriddenMembers As ImmutableArray(Of TSymbol) = overriddenMembersResult.OverriddenMembers
' If there are no overridden members (those with 'exactly' matching signature)
' analyze overridden member candidates with 'generally' matching signature
If overriddenMembers.IsEmpty Then
overriddenMembers = overriddenMembersResult.InexactOverriddenMembers
End If
If overriddenMembers.Length = 0 Then
' Did not have member to override. But there might have been an inaccessible one.
If overriddenMembersResult.InaccessibleMembers.Length > 0 Then
ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, member, overriddenMembersResult.InaccessibleMembers(0), diagnostics)
Else
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_OverrideNotNeeded3, member.GetKindText(), member.Name),
member.Locations(0)))
End If
ElseIf overriddenMembers.Length > 1 Then
' Multiple members we could be overriding. Create a single error message that lists them all.
Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(overriddenMembers.Length)
For Each overriddenMemb In overriddenMembers
diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverriddenCandidate1, overriddenMemb.OriginalDefinition))
Next
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_AmbiguousOverrides3,
overriddenMembers(0),
CustomSymbolDisplayFormatter.ShortErrorName(overriddenMembers(0).ContainingType),
New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree())),
member.Locations(0)))
Else
' overriding exactly one member.
Dim overriddenMember As TSymbol = overriddenMembers(0)
Dim comparisonResults As SymbolComparisonResults = DetailedSignatureCompare(member, overriddenMember, SymbolComparisonResults.AllMismatches)
Dim errorId As ERRID
If overriddenMember.IsNotOverridable Then
ReportBadOverriding(ERRID.ERR_CantOverrideNotOverridable2, member, overriddenMember, diagnostics)
ElseIf Not (overriddenMember.IsOverridable Or overriddenMember.IsMustOverride Or overriddenMember.IsOverrides) Then
ReportBadOverriding(ERRID.ERR_CantOverride4, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.ParameterByrefMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithByref2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithOptional2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.ReturnTypeMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_InvalidOverrideDueToReturn2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.PropertyAccessorMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverridingPropertyKind2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.ParamArrayMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithArrayVsParamArray2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterTypeMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithOptionalTypes2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.OptionalParameterValueMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithDefault2, member, overriddenMember, diagnostics)
ElseIf (comparisonResults And SymbolComparisonResults.ConstraintMismatch) <> 0 Then
ReportBadOverriding(ERRID.ERR_OverrideWithConstraintMismatch2, member, overriddenMember, diagnostics)
ElseIf Not ConsistentAccessibility(member, overriddenMember, errorId) Then
ReportBadOverriding(errorId, member, overriddenMember, diagnostics)
ElseIf member.ContainsTupleNames() AndAlso (comparisonResults And SymbolComparisonResults.TupleNamesMismatch) <> 0 Then
' it is ok to override with no tuple names, for compatibility with VB 14, but otherwise names should match
ReportBadOverriding(ERRID.WRN_InvalidOverrideDueToTupleNames2, member, overriddenMember, diagnostics)
Else
For Each inaccessibleMember In overriddenMembersResult.InaccessibleMembers
If inaccessibleMember.DeclaredAccessibility = Accessibility.Friend AndAlso
inaccessibleMember.OverriddenMember = overriddenMember Then
' We have an inaccessible friend member that overrides the member we're trying to override.
' We can't do that, so issue an error.
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_InAccessibleOverridingMethod5,
member, member.ContainingType, overriddenMember, overriddenMember.ContainingType, inaccessibleMember.ContainingType),
member.Locations(0)))
End If
Next
Dim useSiteErrorInfo = overriddenMember.GetUseSiteErrorInfo()
If useSiteErrorInfo IsNot Nothing Then
diagnostics.Add(New VBDiagnostic(useSiteErrorInfo, member.Locations(0)))
ElseIf member.Kind = SymbolKind.Property Then
' No overriding errors found in member. If its a property, its accessors might have issues.
Dim overridingProperty As PropertySymbol = DirectCast(DirectCast(member, Symbol), PropertySymbol)
Dim overriddenProperty As PropertySymbol = DirectCast(DirectCast(overriddenMember, Symbol), PropertySymbol)
CheckOverridePropertyAccessor(overridingProperty.GetMethod, overriddenProperty.GetMethod, diagnostics)
CheckOverridePropertyAccessor(overridingProperty.SetMethod, overriddenProperty.SetMethod, diagnostics)
End If
End If
End If
End Sub
' Imported types can have multiple members with the same signature (case insensitive) and different accessibilities. VB prefers
' members that are "more accessible". This is a very rare code path if members has > 1 element so we don't worry about performance.
Private Shared Sub RemoveMembersWithConflictingAccessibility(members As ArrayBuilder(Of TSymbol))
If members.Count < 2 Then
Return
End If
Const significantDifferences As SymbolComparisonResults = SymbolComparisonResults.AllMismatches And
Not SymbolComparisonResults.MismatchesForConflictingMethods
Dim nonConflicting As ArrayBuilder(Of TSymbol) = ArrayBuilder(Of TSymbol).GetInstance()
For Each sym In members
Dim isWorseThanAnother As Boolean = False
For Each otherSym In members
If sym IsNot otherSym Then
Dim originalSym = sym.OriginalDefinition
Dim originalOther = otherSym.OriginalDefinition
' Two original definitions with identical signatures in same containing types are compared by accessibility, and
' more accessible wins.
If TypeSymbol.Equals(originalSym.ContainingType, originalOther.ContainingType, TypeCompareKind.ConsiderEverything) AndAlso
DetailedSignatureCompare(originalSym, originalOther, significantDifferences) = 0 AndAlso
LookupResult.CompareAccessibilityOfSymbolsConflictingInSameContainer(originalSym, originalOther) < 0 Then
' sym is worse than otherSym
isWorseThanAnother = True
Exit For
End If
End If
Next
If Not isWorseThanAnother Then
nonConflicting.Add(sym)
End If
Next
If nonConflicting.Count <> members.Count Then
members.Clear()
members.AddRange(nonConflicting)
End If
nonConflicting.Free()
End Sub
' Check an accessor with respect to its overridden accessor and report any diagnostics
Friend Shared Sub CheckOverridePropertyAccessor(overridingAccessor As MethodSymbol,
overriddenAccessor As MethodSymbol,
diagnostics As DiagnosticBag)
' CONSIDER: it is possible for an accessor to have a use site error even when the property
' does not but, in general, we have not been handling cases where property and accessor
' signatures are mismatched (e.g. different modopts).
If overridingAccessor IsNot Nothing AndAlso overriddenAccessor IsNot Nothing Then
' Use original definition for accessibility check, because substitutions can cause
' reductions in accessibility that aren't appropriate (see bug #12038 for example).
If Not AccessCheck.IsSymbolAccessible(overriddenAccessor.OriginalDefinition, overridingAccessor.ContainingType, Nothing, useSiteDiagnostics:=Nothing) Then
ReportBadOverriding(ERRID.ERR_CannotOverrideInAccessibleMember, overridingAccessor, overriddenAccessor, diagnostics)
Else
Dim errorId As ERRID
If Not ConsistentAccessibility(overridingAccessor, overriddenAccessor, errorId) Then
ReportBadOverriding(errorId, overridingAccessor, overriddenAccessor, diagnostics)
End If
End If
End If
End Sub
' Report an error with overriding
Private Shared Sub ReportBadOverriding(id As ERRID,
overridingMember As Symbol,
overriddenMember As Symbol,
diagnostics As DiagnosticBag)
diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(id, overridingMember, overriddenMember),
overridingMember.Locations(0)))
End Sub
' Are the declared accessibility of the two symbols consistent? If not, return the error code to use.
Private Shared Function ConsistentAccessibility(overriding As Symbol, overridden As Symbol, ByRef errorId As ERRID) As Boolean
If overridden.DeclaredAccessibility = Accessibility.ProtectedOrFriend And Not overriding.ContainingAssembly = overridden.ContainingAssembly Then
errorId = ERRID.ERR_FriendAssemblyBadAccessOverride2
Return overriding.DeclaredAccessibility = Accessibility.Protected
Else
errorId = ERRID.ERR_BadOverrideAccess2
Return overridden.DeclaredAccessibility = overriding.DeclaredAccessibility
End If
End Function
End Class
End Namespace
|
reaction1989/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Source/OverrideHidingHelper.vb
|
Visual Basic
|
apache-2.0
| 62,420
|
'------------------------------------------------------------------------------
' <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 Off
Option Explicit On
'Generation date: 2/9/2015 3:43:43 PM
Namespace [Namespace].Foo
'''<summary>
'''There are no comments for BaseTypeSingle in the schema.
'''</summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("baseTypeSingle")> _
Partial Public Class BaseTypeSingle
Inherits Global.Microsoft.OData.Client.DataServiceQuerySingle(Of BaseType)
''' <summary>
''' Initialize a new BaseTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String)
MyBase.New(context, path)
End Sub
''' <summary>
''' Initialize a new BaseTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String, ByVal isComposable As Boolean)
MyBase.New(context, path, isComposable)
End Sub
''' <summary>
''' Initialize a new BaseTypeSingle object.
''' </summary>
Public Sub New(ByVal query As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of BaseType))
MyBase.New(query)
End Sub
End Class
'''<summary>
'''There are no comments for BaseType in the schema.
'''</summary>
'''<KeyProperties>
'''KeyProp
'''</KeyProperties>
<Global.Microsoft.OData.Client.Key("keyProp")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("baseType")> _
Partial Public Class BaseType
Inherits Global.Microsoft.OData.Client.BaseEntityType
'''<summary>
'''Create a new BaseType object.
'''</summary>
'''<param name="keyProp">Initial value of KeyProp.</param>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Shared Function CreateBaseType(ByVal keyProp As Integer) As BaseType
Dim baseType As BaseType = New BaseType()
baseType.KeyProp = keyProp
Return baseType
End Function
'''<summary>
'''There are no comments for Property KeyProp in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("keyProp")> _
Public Property KeyProp() As Integer
Get
Return Me._KeyProp
End Get
Set
Me.OnKeyPropChanging(value)
Me._KeyProp = value
Me.OnKeyPropChanged
End Set
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _KeyProp As Integer
Partial Private Sub OnKeyPropChanging(ByVal value As Integer)
End Sub
Partial Private Sub OnKeyPropChanged()
End Sub
End Class
'''<summary>
'''There are no comments for TestTypeSingle in the schema.
'''</summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("testTypeSingle")> _
Partial Public Class TestTypeSingle
Inherits Global.Microsoft.OData.Client.DataServiceQuerySingle(Of TestType)
''' <summary>
''' Initialize a new TestTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String)
MyBase.New(context, path)
End Sub
''' <summary>
''' Initialize a new TestTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String, ByVal isComposable As Boolean)
MyBase.New(context, path, isComposable)
End Sub
''' <summary>
''' Initialize a new TestTypeSingle object.
''' </summary>
Public Sub New(ByVal query As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of TestType))
MyBase.New(query)
End Sub
'''<summary>
'''There are no comments for SingleType in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("singleType")> _
Public ReadOnly Property SingleType() As [Namespace].Foo.SingleTypeSingle
Get
If Not Me.IsComposable Then
Throw New Global.System.NotSupportedException("The previous function is not composable.")
End If
If (Me._SingleType Is Nothing) Then
Me._SingleType = New [Namespace].Foo.SingleTypeSingle(Me.Context, GetPath("singleType"))
End If
Return Me._SingleType
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _SingleType As [Namespace].Foo.SingleTypeSingle
End Class
'''<summary>
'''There are no comments for TestType in the schema.
'''</summary>
'''<KeyProperties>
'''KeyProp
'''</KeyProperties>
<Global.Microsoft.OData.Client.Key("keyProp")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("testType")> _
Partial Public Class TestType
Inherits BaseType
'''<summary>
'''Create a new TestType object.
'''</summary>
'''<param name="keyProp">Initial value of KeyProp.</param>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Shared Function CreateTestType(ByVal keyProp As Integer) As TestType
Dim testType As TestType = New TestType()
testType.KeyProp = keyProp
Return testType
End Function
'''<summary>
'''There are no comments for Property SingleType in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("singleType")> _
Public Property SingleType() As [Namespace].Foo.SingleType
Get
Return Me._SingleType
End Get
Set
Me.OnSingleTypeChanging(value)
Me._SingleType = value
Me.OnSingleTypeChanged
End Set
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _SingleType As [Namespace].Foo.SingleType
Partial Private Sub OnSingleTypeChanging(ByVal value As [Namespace].Foo.SingleType)
End Sub
Partial Private Sub OnSingleTypeChanged()
End Sub
End Class
'''<summary>
'''There are no comments for SingleTypeSingle in the schema.
'''</summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("singleTypeSingle")> _
Partial Public Class SingleTypeSingle
Inherits Global.Microsoft.OData.Client.DataServiceQuerySingle(Of SingleType)
''' <summary>
''' Initialize a new SingleTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String)
MyBase.New(context, path)
End Sub
''' <summary>
''' Initialize a new SingleTypeSingle object.
''' </summary>
Public Sub New(ByVal context As Global.Microsoft.OData.Client.DataServiceContext, ByVal path As String, ByVal isComposable As Boolean)
MyBase.New(context, path, isComposable)
End Sub
''' <summary>
''' Initialize a new SingleTypeSingle object.
''' </summary>
Public Sub New(ByVal query As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of SingleType))
MyBase.New(query)
End Sub
'''<summary>
'''There are no comments for BaseSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("baseSet")> _
Public ReadOnly Property BaseSet() As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType)
Get
If Not Me.IsComposable Then
Throw New Global.System.NotSupportedException("The previous function is not composable.")
End If
If (Me._BaseSet Is Nothing) Then
Me._BaseSet = Context.CreateQuery(Of [Namespace].Foo.TestType)(GetPath("baseSet"))
End If
Return Me._BaseSet
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _BaseSet As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType)
End Class
'''<summary>
'''There are no comments for SingleType in the schema.
'''</summary>
'''<KeyProperties>
'''KeyProp
'''</KeyProperties>
<Global.Microsoft.OData.Client.Key("keyProp")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("singleType")> _
Partial Public Class SingleType
Inherits Global.Microsoft.OData.Client.BaseEntityType
'''<summary>
'''Create a new SingleType object.
'''</summary>
'''<param name="keyProp">Initial value of KeyProp.</param>
'''<param name="colorProp">Initial value of ColorProp.</param>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Shared Function CreateSingleType(ByVal keyProp As Integer, ByVal colorProp As [Namespace].Foo.Color) As SingleType
Dim singleType As SingleType = New SingleType()
singleType.KeyProp = keyProp
singleType.ColorProp = colorProp
Return singleType
End Function
'''<summary>
'''There are no comments for Property KeyProp in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("keyProp")> _
Public Property KeyProp() As Integer
Get
Return Me._KeyProp
End Get
Set
Me.OnKeyPropChanging(value)
Me._KeyProp = value
Me.OnKeyPropChanged
End Set
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _KeyProp As Integer
Partial Private Sub OnKeyPropChanging(ByVal value As Integer)
End Sub
Partial Private Sub OnKeyPropChanged()
End Sub
'''<summary>
'''There are no comments for Property ColorProp in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("colorProp")> _
Public Property ColorProp() As [Namespace].Foo.Color
Get
Return Me._ColorProp
End Get
Set
Me.OnColorPropChanging(value)
Me._ColorProp = value
Me.OnColorPropChanged
End Set
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _ColorProp As [Namespace].Foo.Color
Partial Private Sub OnColorPropChanging(ByVal value As [Namespace].Foo.Color)
End Sub
Partial Private Sub OnColorPropChanged()
End Sub
'''<summary>
'''There are no comments for Property BaseSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("baseSet")> _
Public Property BaseSet() As Global.System.Collections.ObjectModel.Collection(Of [Namespace].Foo.TestType)
Get
Return Me._BaseSet
End Get
Set
Me.OnBaseSetChanging(value)
Me._BaseSet = value
Me.OnBaseSetChanged
End Set
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _BaseSet As Global.System.Collections.ObjectModel.Collection(Of [Namespace].Foo.TestType) = New Global.System.Collections.ObjectModel.Collection(Of [Namespace].Foo.TestType)()
Partial Private Sub OnBaseSetChanging(ByVal value As Global.System.Collections.ObjectModel.Collection(Of [Namespace].Foo.TestType))
End Sub
Partial Private Sub OnBaseSetChanged()
End Sub
''' <summary>
''' There are no comments for Foo7 in the schema.
''' </summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("foo7")> _
Public Function Foo7() As Global.Microsoft.OData.Client.DataServiceActionQuerySingle(Of Global.System.Nullable(Of Integer))
Dim resource As Global.Microsoft.OData.Client.EntityDescriptor = Context.EntityTracker.TryGetEntityDescriptor(Me)
If resource Is Nothing Then
Throw New Global.System.Exception("cannot find entity")
End If
Return New Global.Microsoft.OData.Client.DataServiceActionQuerySingle(Of Global.System.Nullable(Of Integer))(Me.Context, resource.EditLink.OriginalString.Trim("/"C) + "/namespace.foo.foo7")
End Function
End Class
'''<summary>
'''There are no comments for Color in the schema.
'''</summary>
<Global.System.Flags()>
<Global.Microsoft.OData.Client.OriginalNameAttribute("color")> _
Public Enum Color
<Global.Microsoft.OData.Client.OriginalNameAttribute("red")> _
Red = 0
<Global.Microsoft.OData.Client.OriginalNameAttribute("white")> _
White = 1
<Global.Microsoft.OData.Client.OriginalNameAttribute("blue")> _
Blue = 2
End Enum
''' <summary>
''' Class containing all extension methods
''' </summary>
Public Module ExtensionMethods
''' <summary>
''' Get an entity of type [Namespace].Foo.BaseType as [Namespace].Foo.BaseTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keys">dictionary with the names and values of keys</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.BaseType), ByVal keys As Global.System.Collections.Generic.Dictionary(Of String, Object)) As [Namespace].Foo.BaseTypeSingle
Return New [Namespace].Foo.BaseTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' Get an entity of type [Namespace].Foo.BaseType as [Namespace].Foo.BaseTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keyProp">The value of keyProp</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.BaseType),
keyProp As Integer) As [Namespace].Foo.BaseTypeSingle
Dim keys As Global.System.Collections.Generic.Dictionary(Of String, Object) = New Global.System.Collections.Generic.Dictionary(Of String, Object)() From
{
{ "keyProp", keyProp }
}
Return New [Namespace].Foo.BaseTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' Get an entity of type [Namespace].Foo.TestType as [Namespace].Foo.TestTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keys">dictionary with the names and values of keys</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType), ByVal keys As Global.System.Collections.Generic.Dictionary(Of String, Object)) As [Namespace].Foo.TestTypeSingle
Return New [Namespace].Foo.TestTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' Get an entity of type [Namespace].Foo.TestType as [Namespace].Foo.TestTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keyProp">The value of keyProp</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType),
keyProp As Integer) As [Namespace].Foo.TestTypeSingle
Dim keys As Global.System.Collections.Generic.Dictionary(Of String, Object) = New Global.System.Collections.Generic.Dictionary(Of String, Object)() From
{
{ "keyProp", keyProp }
}
Return New [Namespace].Foo.TestTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' Cast an entity of type [Namespace].Foo.BaseType to its derived type [Namespace].Foo.TestType
''' </summary>
''' <param name="source">source entity</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function CastToTestType(ByVal source As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of [Namespace].Foo.BaseType)) As [Namespace].Foo.TestTypeSingle
Dim query As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of [Namespace].Foo.TestType) = source.CastTo(Of [Namespace].Foo.TestType)()
Return New [Namespace].Foo.TestTypeSingle(source.Context, query.GetPath(Nothing))
End Function
''' <summary>
''' Get an entity of type [Namespace].Foo.SingleType as [Namespace].Foo.SingleTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keys">dictionary with the names and values of keys</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.SingleType), ByVal keys As Global.System.Collections.Generic.Dictionary(Of String, Object)) As [Namespace].Foo.SingleTypeSingle
Return New [Namespace].Foo.SingleTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' Get an entity of type [Namespace].Foo.SingleType as [Namespace].Foo.SingleTypeSingle specified by key from an entity set
''' </summary>
''' <param name="source">source entity set</param>
''' <param name="keyProp">The value of keyProp</param>
<Global.System.Runtime.CompilerServices.Extension()>
Public Function ByKey(ByVal source As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.SingleType),
keyProp As Integer) As [Namespace].Foo.SingleTypeSingle
Dim keys As Global.System.Collections.Generic.Dictionary(Of String, Object) = New Global.System.Collections.Generic.Dictionary(Of String, Object)() From
{
{ "keyProp", keyProp }
}
Return New [Namespace].Foo.SingleTypeSingle(source.Context, source.GetKeyPath(Global.Microsoft.OData.Client.Serializer.GetKeyString(source.Context, keys)))
End Function
''' <summary>
''' There are no comments for Foo7 in the schema.
''' </summary>
<Global.System.Runtime.CompilerServices.Extension()>
<Global.Microsoft.OData.Client.OriginalNameAttribute("foo7")> _
Public Function Foo7(ByVal source As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of [Namespace].Foo.SingleType)) As Global.Microsoft.OData.Client.DataServiceActionQuerySingle(Of Global.System.Nullable(Of Integer))
If Not source.IsComposable Then
Throw New Global.System.NotSupportedException("The previous function is not composable.")
End If
Return New Global.Microsoft.OData.Client.DataServiceActionQuerySingle(Of Global.System.Nullable(Of Integer))(source.Context, source.AppendRequestUri("namespace.foo.foo7"))
End Function
End Module
End Namespace
Namespace [Namespace].Bar
'''<summary>
'''There are no comments for SingletonContainer in the schema.
'''</summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("singletonContainer")> _
Partial Public Class SingletonContainer
Inherits Global.Microsoft.OData.Client.DataServiceContext
'''<summary>
'''Initialize a new SingletonContainer object.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Sub New(ByVal serviceRoot As Global.System.Uri)
MyBase.New(serviceRoot, Global.Microsoft.OData.Client.ODataProtocolVersion.V4)
Me.ResolveName = AddressOf Me.ResolveNameFromType
Me.ResolveType = AddressOf Me.ResolveTypeFromName
Me.OnContextCreated
Me.Format.LoadServiceModel = AddressOf GeneratedEdmModel.GetInstance
Me.Format.UseJson()
End Sub
Partial Private Sub OnContextCreated()
End Sub
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private Shared ROOTNAMESPACE As String = GetType(SingletonContainer).Namespace.Remove(GetType(SingletonContainer).Namespace.LastIndexOf("Namespace.Bar"))
'''<summary>
'''Since the namespace configured for this service reference
'''in Visual Studio is different from the one indicated in the
'''server schema, use type-mappers to map between the two.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Protected Function ResolveTypeFromName(ByVal typeName As String) As Global.System.Type
Dim resolvedType As Global.System.Type = Me.DefaultResolveType(typeName, "namespace.bar", String.Concat(ROOTNAMESPACE, "Namespace.Bar"))
If (Not (resolvedType) Is Nothing) Then
Return resolvedType
End If
resolvedType = Me.DefaultResolveType(typeName, "namespace.foo", String.Concat(ROOTNAMESPACE, "Namespace.Foo"))
If (Not (resolvedType) Is Nothing) Then
Return resolvedType
End If
Return Nothing
End Function
'''<summary>
'''Since the namespace configured for this service reference
'''in Visual Studio is different from the one indicated in the
'''server schema, use type-mappers to map between the two.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Protected Function ResolveNameFromType(ByVal clientType As Global.System.Type) As String
Dim originalNameAttribute As Global.Microsoft.OData.Client.OriginalNameAttribute =
CType(Global.System.Linq.Enumerable.SingleOrDefault(Global.Microsoft.OData.Client.Utility.GetCustomAttributes(clientType, GetType(Global.Microsoft.OData.Client.OriginalNameAttribute), true)), Global.Microsoft.OData.Client.OriginalNameAttribute)
If clientType.Namespace.Equals(String.Concat(ROOTNAMESPACE, "Namespace.Bar"), Global.System.StringComparison.OrdinalIgnoreCase) Then
If (Not (originalNameAttribute) Is Nothing) Then
Return String.Concat("namespace.bar.", originalNameAttribute.OriginalName)
End If
Return String.Concat("namespace.bar.", clientType.Name)
End If
If clientType.Namespace.Equals(String.Concat(ROOTNAMESPACE, "Namespace.Foo"), Global.System.StringComparison.OrdinalIgnoreCase) Then
If (Not (originalNameAttribute) Is Nothing) Then
Return String.Concat("namespace.foo.", originalNameAttribute.OriginalName)
End If
Return String.Concat("namespace.foo.", clientType.Name)
End If
If (Not (originalNameAttribute) Is Nothing) Then
Dim fullName As String = clientType.FullName.Substring(ROOTNAMESPACE.Length)
Return fullName.Remove(fullName.LastIndexOf(clientType.Name)) + originalNameAttribute.OriginalName
End If
Return clientType.FullName.Substring(ROOTNAMESPACE.Length)
End Function
'''<summary>
'''There are no comments for TestTypeSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("testTypeSet")> _
Public ReadOnly Property TestTypeSet() As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType)
Get
If (Me._TestTypeSet Is Nothing) Then
Me._TestTypeSet = MyBase.CreateQuery(Of [Namespace].Foo.TestType)("testTypeSet")
End If
Return Me._TestTypeSet
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _TestTypeSet As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.TestType)
'''<summary>
'''There are no comments for BaseTypeSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("baseTypeSet")> _
Public ReadOnly Property BaseTypeSet() As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.BaseType)
Get
If (Me._BaseTypeSet Is Nothing) Then
Me._BaseTypeSet = MyBase.CreateQuery(Of [Namespace].Foo.BaseType)("baseTypeSet")
End If
Return Me._BaseTypeSet
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _BaseTypeSet As Global.Microsoft.OData.Client.DataServiceQuery(Of [Namespace].Foo.BaseType)
'''<summary>
'''There are no comments for TestTypeSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Sub AddToTestTypeSet(ByVal testType As [Namespace].Foo.TestType)
MyBase.AddObject("testTypeSet", testType)
End Sub
'''<summary>
'''There are no comments for BaseTypeSet in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Sub AddToBaseTypeSet(ByVal baseType As [Namespace].Foo.BaseType)
MyBase.AddObject("baseTypeSet", baseType)
End Sub
'''<summary>
'''There are no comments for SuperType in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("superType")> _
Public ReadOnly Property SuperType() As [Namespace].Foo.TestTypeSingle
Get
If (Me._SuperType Is Nothing) Then
Me._SuperType = New [Namespace].Foo.TestTypeSingle(Me, "superType")
End If
Return Me._SuperType
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _SuperType As [Namespace].Foo.TestTypeSingle
'''<summary>
'''There are no comments for Single in the schema.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
<Global.Microsoft.OData.Client.OriginalNameAttribute("single")> _
Public ReadOnly Property [Single]() As [Namespace].Foo.SingleTypeSingle
Get
If (Me._Single Is Nothing) Then
Me._Single = New [Namespace].Foo.SingleTypeSingle(Me, "single")
End If
Return Me._Single
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private _Single As [Namespace].Foo.SingleTypeSingle
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private MustInherit Class GeneratedEdmModel
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private Shared ParsedModel As Global.Microsoft.OData.Edm.IEdmModel = LoadModelFromString
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private Const Edmx As String = "<edmx:Edmx Version=""4.0"" xmlns:edmx=""http://docs.oasis-open.org/odata/ns/edmx"">" & _
" <edmx:DataServices>" & _
" <Schema Namespace=""namespace.foo"" xmlns:d=""http://docs.oasis-open.org/odata/ns/data"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">" & _
" <EntityType Name=""baseType"">" & _
" <Key>" & _
" <PropertyRef Name=""keyProp"" />" & _
" </Key>" & _
" <Property Name=""keyProp"" Type=""Edm.Int32"" Nullable=""false"" />" & _
" </EntityType>" & _
" <EntityType Name=""testType"" BaseType=""namespace.foo.baseType"">" & _
" <NavigationProperty Name=""singleType"" Type=""namespace.foo.singleType"" />" & _
" </EntityType>" & _
" <EntityType Name=""singleType"">" & _
" <Key>" & _
" <PropertyRef Name=""keyProp"" />" & _
" </Key>" & _
" <Property Name=""keyProp"" Type=""Edm.Int32"" Nullable=""false"" />" & _
" <Property Name=""colorProp"" Type=""namespace.foo.color"" Nullable=""false"" />" & _
" <NavigationProperty Name=""baseSet"" Type=""Collection(namespace.foo.testType)"" />" & _
" </EntityType>" & _
" <EnumType Name=""color"" UnderlyingType=""Edm.Int32"" IsFlags=""true"">" & _
" <Member Name=""red"" />" & _
" <Member Name=""white"" />" & _
" <Member Name=""blue"" />" & _
" </EnumType>" & _
" <Function Name=""foo6"">" & _
" <Parameter Name=""p1"" Type=""Collection(namespace.foo.testType)"" />" & _
" <ReturnType Type=""Edm.String"" />" & _
" </Function>" & _
" <Action Name=""foo7"" IsBound=""True"">" & _
" <Parameter Name=""p1"" Type=""namespace.foo.singleType"" />" & _
" <ReturnType Type=""Edm.Int32"" />" & _
" </Action>" & _
" </Schema>" & _
" <Schema Namespace=""namespace.bar"" xmlns:d=""http://docs.oasis-open.org/odata/ns/data"" xmlns=""http://docs.oasis-open.org/odata/ns/edm"">" & _
" <EntityContainer Name=""singletonContainer"">" & _
" <EntitySet Name=""testTypeSet"" EntityType=""namespace.foo.testType"" />" & _
" <EntitySet Name=""baseTypeSet"" EntityType=""namespace.foo.baseType"" />" & _
" <Singleton Name=""superType"" Type=""namespace.foo.testType"" />" & _
" <Singleton Name=""single"" Type=""namespace.foo.singleType"" />" & _
" <FunctionImport Name=""foo6"" Function=""namespace.foo.foo6"" />" & _
" </EntityContainer>" & _
" </Schema>" & _
" </edmx:DataServices>" & _
"</edmx:Edmx>"
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Public Shared Function GetInstance() As Global.Microsoft.OData.Edm.IEdmModel
Return ParsedModel
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private Shared Function LoadModelFromString() As Global.Microsoft.OData.Edm.IEdmModel
Dim reader As Global.System.Xml.XmlReader = CreateXmlReader(Edmx)
Try
Return Global.Microsoft.OData.Edm.Csdl.EdmxReader.Parse(reader)
Finally
CType(reader,Global.System.IDisposable).Dispose
End Try
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.2.0")> _
Private Shared Function CreateXmlReader(ByVal edmxToParse As String) As Global.System.Xml.XmlReader
Return Global.System.Xml.XmlReader.Create(New Global.System.IO.StringReader(edmxToParse))
End Function
End Class
''' <summary>
''' There are no comments for Foo6 in the schema.
''' </summary>
<Global.Microsoft.OData.Client.OriginalNameAttribute("foo6")> _
Public Function Foo6(p1 As Global.System.Collections.Generic.ICollection(Of [Namespace].Foo.TestType), Optional ByVal useEntityReference As Boolean = False) As Global.Microsoft.OData.Client.DataServiceQuerySingle(Of String)
Return Me.CreateFunctionQuerySingle(Of String)("", "/foo6", False, New Global.Microsoft.OData.Client.UriEntityOperationParameter("p1", p1, useEntityReference))
End Function
End Class
End Namespace
|
hotchandanisagar/odata.net
|
test/FunctionalTests/Tests/DataServices/UnitTests/DesignT4UnitTests/CodeGen/UpperCamelCaseWithoutNamespacePrefix.vb
|
Visual Basic
|
mit
| 35,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.Collections.Immutable
Imports System.Diagnostics
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitTryStatement(node As BoundTryStatement) As BoundNode
Debug.Assert(_unstructuredExceptionHandling.Context Is Nothing)
Dim rewrittenTryBlock = RewriteTryBlock(node)
Dim rewrittenCatchBlocks = VisitList(node.CatchBlocks)
Dim rewrittenFinally = RewriteFinallyBlock(node)
Dim rewritten As BoundStatement = RewriteTryStatement(node.Syntax, rewrittenTryBlock, rewrittenCatchBlocks, rewrittenFinally, node.ExitLabelOpt)
If Me.Instrument(node) Then
Dim syntax = TryCast(node.Syntax, TryBlockSyntax)
If syntax IsNot Nothing Then
rewritten = _instrumenter.InstrumentTryStatement(node, rewritten)
End If
End If
Return rewritten
End Function
''' <summary>
''' Is there any code to execute in the given statement that could have side-effects,
''' such as throwing an exception? This implementation is conservative, in the sense
''' that it may return true when the statement actually may have no side effects.
''' </summary>
Private Shared Function HasSideEffects(statement As BoundStatement) As Boolean
If statement Is Nothing Then
Return False
End If
Select Case statement.Kind
Case BoundKind.NoOpStatement
Return False
Case BoundKind.Block
Dim block = DirectCast(statement, BoundBlock)
For Each s In block.Statements
If HasSideEffects(s) Then
Return True
End If
Next
Return False
Case BoundKind.SequencePoint
Dim sequence = DirectCast(statement, BoundSequencePoint)
Return HasSideEffects(sequence.StatementOpt)
Case BoundKind.SequencePointWithSpan
Dim sequence = DirectCast(statement, BoundSequencePointWithSpan)
Return HasSideEffects(sequence.StatementOpt)
Case Else
Return True
End Select
End Function
Public Function RewriteTryStatement(
syntaxNode As SyntaxNode,
tryBlock As BoundBlock,
catchBlocks As ImmutableArray(Of BoundCatchBlock),
finallyBlockOpt As BoundBlock,
exitLabelOpt As LabelSymbol
) As BoundStatement
If Not Me.OptimizationLevelIsDebug Then
' When optimizing and the try block has no side effects, we can discard the catch blocks.
If Not HasSideEffects(tryBlock) Then
catchBlocks = ImmutableArray(Of BoundCatchBlock).Empty
End If
' A finally block with no side effects can be omitted.
If Not HasSideEffects(finallyBlockOpt) Then
finallyBlockOpt = Nothing
End If
If catchBlocks.IsDefaultOrEmpty AndAlso finallyBlockOpt Is Nothing Then
If exitLabelOpt Is Nothing Then
Return tryBlock
Else
' Ensure implicit label statement is materialized
Return New BoundStatementList(syntaxNode,
ImmutableArray.Create(Of BoundStatement)(tryBlock,
New BoundLabelStatement(syntaxNode, exitLabelOpt)))
End If
End If
End If
Dim newTry As BoundStatement = New BoundTryStatement(syntaxNode, tryBlock, catchBlocks, finallyBlockOpt, exitLabelOpt)
For Each [catch] In catchBlocks
ReportErrorsOnCatchBlockHelpers([catch])
Next
Return newTry
End Function
Private Function RewriteFinallyBlock(tryStatement As BoundTryStatement) As BoundBlock
Dim node As BoundBlock = tryStatement.FinallyBlockOpt
If node Is Nothing Then
Return node
End If
Dim newFinally = DirectCast(Visit(node), BoundBlock)
If Instrument(tryStatement) Then
Dim syntax = TryCast(node.Syntax, FinallyBlockSyntax)
If syntax IsNot Nothing Then
newFinally = PrependWithPrologue(newFinally, _instrumenter.CreateFinallyBlockPrologue(tryStatement))
End If
End If
Return newFinally
End Function
Private Function RewriteTryBlock(tryStatement As BoundTryStatement) As BoundBlock
Dim node As BoundBlock = tryStatement.TryBlock
Dim newTry = DirectCast(Visit(node), BoundBlock)
If Instrument(tryStatement) Then
Dim syntax = TryCast(node.Syntax, TryBlockSyntax)
If syntax IsNot Nothing Then
newTry = PrependWithPrologue(newTry, _instrumenter.CreateTryBlockPrologue(tryStatement))
End If
End If
Return newTry
End Function
Public Overrides Function VisitCatchBlock(node As BoundCatchBlock) As BoundNode
Dim newExceptionSource = VisitExpressionNode(node.ExceptionSourceOpt)
Dim newFilter = VisitExpressionNode(node.ExceptionFilterOpt)
Dim newCatchBody As BoundBlock = DirectCast(Visit(node.Body), BoundBlock)
If Instrument(node) Then
Dim syntax = TryCast(node.Syntax, CatchBlockSyntax)
If syntax IsNot Nothing Then
If newFilter IsNot Nothing Then
' if we have a filter, we want to stop before the filter expression
' and associate the sequence point with whole Catch statement
' EnC: We need to insert a hidden sequence point to handle function remapping in case
' the containing method is edited while methods invoked in the condition are being executed.
newFilter = _instrumenter.InstrumentCatchBlockFilter(node, newFilter, _currentMethodOrLambda)
Else
newCatchBody = PrependWithPrologue(newCatchBody, _instrumenter.CreateCatchBlockPrologue(node))
End If
End If
End If
Dim errorLineNumber As BoundExpression = Nothing
If node.ErrorLineNumberOpt IsNot Nothing Then
Debug.Assert(_currentLineTemporary Is Nothing)
Debug.Assert((Me._flags And RewritingFlags.AllowCatchWithErrorLineNumberReference) <> 0)
errorLineNumber = VisitExpressionNode(node.ErrorLineNumberOpt)
ElseIf _currentLineTemporary IsNot Nothing AndAlso _currentMethodOrLambda Is _topMethod Then
errorLineNumber = New BoundLocal(node.Syntax, _currentLineTemporary, isLValue:=False, type:=_currentLineTemporary.Type)
End If
Return node.Update(node.LocalOpt,
newExceptionSource,
errorLineNumber,
newFilter,
newCatchBody,
node.IsSynthesizedAsyncCatchAll)
End Function
Private Sub ReportErrorsOnCatchBlockHelpers(node As BoundCatchBlock)
' when starting/finishing any code associated with an exception handler (including exception filters)
' we need to call SetProjectError/ClearProjectError
' NOTE: we do not inject the helper calls via a rewrite.
' SetProjectError is called with implicit argument on the stack and cannot be expressed in the tree.
' ClearProjectError could be added as a rewrite, but for similarity with SetProjectError we will do it in IL gen too.
' we will however check for the presence of the helpers and complain here if we cannot find them.
' TODO: when building VB runtime, this check is unnecessary as we should not emit the helpers.
Dim setProjectError As WellKnownMember = If(node.ErrorLineNumberOpt Is Nothing,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError,
WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__SetProjectError_Int32)
Dim setProjectErrorMethod As MethodSymbol = DirectCast(Compilation.GetWellKnownTypeMember(setProjectError), MethodSymbol)
ReportMissingOrBadRuntimeHelper(node, setProjectError, setProjectErrorMethod)
If node.ExceptionFilterOpt Is Nothing OrElse node.ExceptionFilterOpt.Kind <> BoundKind.UnstructuredExceptionHandlingCatchFilter Then
Const clearProjectError As WellKnownMember = WellKnownMember.Microsoft_VisualBasic_CompilerServices_ProjectData__ClearProjectError
Dim clearProjectErrorMethod = DirectCast(Compilation.GetWellKnownTypeMember(clearProjectError), MethodSymbol)
ReportMissingOrBadRuntimeHelper(node, clearProjectError, clearProjectErrorMethod)
End If
End Sub
End Class
End Namespace
|
bbarry/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_Try.vb
|
Visual Basic
|
apache-2.0
| 10,021
|
Partial Class proxima_Overview
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session.Item("LoggedIn") = False Then
Session.Item("LogInRedirect") = Request.RawUrl
Response.Redirect("LogIn.aspx", True)
End If
If Common.SessionID(Session.Item("UserID"), Application.Item("SqlConnectionStr")) <> Session.Item("SessionID") Then
Response.Redirect("LogOut.aspx", True)
End If
End Sub
End Class
|
jamend/BeyondProxima.vb
|
BeyondProxima/proxima/Overview.aspx.vb
|
Visual Basic
|
mit
| 547
|
'------------------------------------------------------------------------------
' <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", "11.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.Rodriguez_MathMultForms.My.MySettings
Get
Return Global.Rodriguez_MathMultForms.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
miguel2192/CSC-162
|
Rodriguez_MathMultForms/Rodriguez_MathMultForms/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 2,952
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2017 Richard L King (TradeWright Software Systems)
'
' 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.
#End Region
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Partial Class MultiChart
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()>
Protected Overrides Sub Dispose(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(MultiChart))
Me.MultiChartControlToolStrip = New System.Windows.Forms.ToolStrip()
Me.ToolStripTimePeriodSelector1 = New TradeWright.Trading.UI.Trading.ToolStripTimePeriodSelector()
Me.ChangeTimeframeToolStripButton = New System.Windows.Forms.ToolStripButton()
Me.AddTimeframeToolStripButton = New System.Windows.Forms.ToolStripButton()
Me.RemoveTimeframeToolStripButton = New System.Windows.Forms.ToolStripButton()
Me.MultiChartChartSelectorToolStrip = New System.Windows.Forms.ToolStrip()
Me.MultiChartToolStripPanel1 = New System.Windows.Forms.ToolStripPanel()
Me.MultiChartControlToolStrip.SuspendLayout()
Me.MultiChartToolStripPanel1.SuspendLayout()
Me.SuspendLayout()
'
'MultiChartControlToolStrip
'
Me.MultiChartControlToolStrip.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.MultiChartControlToolStrip.Dock = System.Windows.Forms.DockStyle.None
Me.MultiChartControlToolStrip.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripTimePeriodSelector1, Me.ChangeTimeframeToolStripButton, Me.AddTimeframeToolStripButton, Me.RemoveTimeframeToolStripButton})
Me.MultiChartControlToolStrip.Location = New System.Drawing.Point(156, 0)
Me.MultiChartControlToolStrip.Name = "MultiChartControlToolStrip"
Me.MultiChartControlToolStrip.Size = New System.Drawing.Size(81, 25)
Me.MultiChartControlToolStrip.TabIndex = 5
Me.MultiChartControlToolStrip.Text = "ToolStrip1"
'
'ToolStripTimePeriodSelector1
'
Me.ToolStripTimePeriodSelector1.Name = "ToolStripTimePeriodSelector1"
Me.ToolStripTimePeriodSelector1.Size = New System.Drawing.Size(121, 23)
Me.ToolStripTimePeriodSelector1.Text = "ToolStripTimePeriodSelector1"
Me.ToolStripTimePeriodSelector1.TimePeriod = Nothing
Me.ToolStripTimePeriodSelector1.UseShortTimePeriodStrings = True
Me.ToolStripTimePeriodSelector1.Visible = False
'
'ChangeTimeframeToolStripButton
'
Me.ChangeTimeframeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.ChangeTimeframeToolStripButton.Image = CType(resources.GetObject("ChangeTimeframeToolStripButton.Image"), System.Drawing.Image)
Me.ChangeTimeframeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta
Me.ChangeTimeframeToolStripButton.Name = "ChangeTimeframeToolStripButton"
Me.ChangeTimeframeToolStripButton.Size = New System.Drawing.Size(23, 22)
Me.ChangeTimeframeToolStripButton.Text = "Change"
Me.ChangeTimeframeToolStripButton.ToolTipText = "Change the timeframe for this chart"
'
'AddTimeframeToolStripButton
'
Me.AddTimeframeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.AddTimeframeToolStripButton.Image = CType(resources.GetObject("AddTimeframeToolStripButton.Image"), System.Drawing.Image)
Me.AddTimeframeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta
Me.AddTimeframeToolStripButton.Name = "AddTimeframeToolStripButton"
Me.AddTimeframeToolStripButton.Size = New System.Drawing.Size(23, 23)
Me.AddTimeframeToolStripButton.Text = "ToolStripButton1"
Me.AddTimeframeToolStripButton.ToolTipText = "Add a chart with a different timeframe"
'
'RemoveTimeframeToolStripButton
'
Me.RemoveTimeframeToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image
Me.RemoveTimeframeToolStripButton.Image = CType(resources.GetObject("RemoveTimeframeToolStripButton.Image"), System.Drawing.Image)
Me.RemoveTimeframeToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta
Me.RemoveTimeframeToolStripButton.Name = "RemoveTimeframeToolStripButton"
Me.RemoveTimeframeToolStripButton.Size = New System.Drawing.Size(23, 23)
Me.RemoveTimeframeToolStripButton.Text = "ToolStripButton1"
Me.RemoveTimeframeToolStripButton.ToolTipText = "Remove the current chart"
'
'MultiChartChartSelectorToolStrip
'
Me.MultiChartChartSelectorToolStrip.AllowItemReorder = True
Me.MultiChartChartSelectorToolStrip.Dock = System.Windows.Forms.DockStyle.None
Me.MultiChartChartSelectorToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden
Me.MultiChartChartSelectorToolStrip.Location = New System.Drawing.Point(6, 0)
Me.MultiChartChartSelectorToolStrip.MinimumSize = New System.Drawing.Size(150, 0)
Me.MultiChartChartSelectorToolStrip.Name = "MultiChartChartSelectorToolStrip"
Me.MultiChartChartSelectorToolStrip.Size = New System.Drawing.Size(150, 25)
Me.MultiChartChartSelectorToolStrip.TabIndex = 4
Me.MultiChartChartSelectorToolStrip.Text = "ToolStrip1"
'
'MultiChartToolStripPanel1
'
Me.MultiChartToolStripPanel1.Controls.Add(Me.MultiChartChartSelectorToolStrip)
Me.MultiChartToolStripPanel1.Controls.Add(Me.MultiChartControlToolStrip)
Me.MultiChartToolStripPanel1.Dock = System.Windows.Forms.DockStyle.Bottom
Me.MultiChartToolStripPanel1.Location = New System.Drawing.Point(0, 482)
Me.MultiChartToolStripPanel1.Name = "MultiChartToolStripPanel1"
Me.MultiChartToolStripPanel1.Orientation = System.Windows.Forms.Orientation.Horizontal
Me.MultiChartToolStripPanel1.RowMargin = New System.Windows.Forms.Padding(3, 0, 0, 0)
Me.MultiChartToolStripPanel1.Size = New System.Drawing.Size(485, 25)
'
'MultiChart
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.MultiChartToolStripPanel1)
Me.Name = "MultiChart"
Me.Size = New System.Drawing.Size(485, 507)
Me.MultiChartControlToolStrip.ResumeLayout(False)
Me.MultiChartControlToolStrip.PerformLayout()
Me.MultiChartToolStripPanel1.ResumeLayout(False)
Me.MultiChartToolStripPanel1.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
' Friend WithEvents MktChart As TradeWright.Trading.UI.Trading.MarketChart
Friend WithEvents MultiChartControlToolStrip As System.Windows.Forms.ToolStrip
Friend WithEvents AddTimeframeToolStripButton As System.Windows.Forms.ToolStripButton
Friend WithEvents RemoveTimeframeToolStripButton As System.Windows.Forms.ToolStripButton
Friend WithEvents MultiChartChartSelectorToolStrip As System.Windows.Forms.ToolStrip
Friend WithEvents ChangeTimeframeToolStripButton As System.Windows.Forms.ToolStripButton
Friend WithEvents MultiChartToolStripPanel1 As System.Windows.Forms.ToolStripPanel
Friend WithEvents ToolStripTimePeriodSelector1 As TradeWright.Trading.UI.Trading.ToolStripTimePeriodSelector
End Class
|
tradewright/tradebuild-platform.net
|
src/TradingUI/MultiChart.Designer.vb
|
Visual Basic
|
mit
| 9,338
|
'------------------------------------------------------------------------------
' <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", "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
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property TwitchUser() As String
Get
Return CType(Me("TwitchUser"),String)
End Get
Set
Me("TwitchUser") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property TwitchOAuth() As String
Get
Return CType(Me("TwitchOAuth"),String)
End Get
Set
Me("TwitchOAuth") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("")> _
Public Property TwitchChannel() As String
Get
Return CType(Me("TwitchChannel"),String)
End Get
Set
Me("TwitchChannel") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("False")> _
Public Property TwitchRemember() As Boolean
Get
Return CType(Me("TwitchRemember"),Boolean)
End Get
Set
Me("TwitchRemember") = value
End Set
End Property
<Global.System.Configuration.UserScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("TwitchBot")> _
Public Property BotName() As String
Get
Return CType(Me("BotName"),String)
End Get
Set
Me("BotName") = value
End Set
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.TwitchBot.My.MySettings
Get
Return Global.TwitchBot.My.MySettings.Default
End Get
End Property
End Module
End Namespace
|
MechaGS/TwitchBot
|
TwitchBot/My Project/Settings.Designer.vb
|
Visual Basic
|
mit
| 5,229
|
Option Strict On
Option Explicit On
Option Infer Off
Public Class CreateHTTPGameClass
Public Sub Create()
Dim ResultString As String = HTTPClient.DownloadString(ServerBaseURI & "/creategame.php")
Select Case ResultString
Case "Error 1"
Case "Error 2"
Case Else
If IsNumeric(ResultString) Then
HTTPGameCode = CInt(ResultString)
CreateGameSuccess = True
Else
Debug.Print(ResultString)
End If
End Select
End Sub
End Class
|
helliio/Mind-Wars
|
Mind-Wars/CreateHTTPGameClass.vb
|
Visual Basic
|
mit
| 598
|
Imports System.ComponentModel
'side for å besttille time
Public Class TimeBestilling
'laster inn comboboks og formaterer dato
Private Sub TimeBestilling_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd.MM.yyyy"
ComboBox1.Text = "08"
ComboBox1.Items.Add("08")
ComboBox1.Items.Add("09")
ComboBox1.Items.Add("10")
ComboBox1.Items.Add("11")
ComboBox1.Items.Add("12")
ComboBox1.Items.Add("13")
ComboBox1.Items.Add("14")
ComboBox1.Items.Add("15")
ComboBox1.Items.Add("16")
ComboBox2.Text = "00"
ComboBox2.Items.Add("00")
ComboBox2.Items.Add("10")
ComboBox2.Items.Add("20")
ComboBox2.Items.Add("30")
ComboBox2.Items.Add("40")
ComboBox2.Items.Add("50")
DateTimePicker1.MinDate = DateTime.Now.AddDays(1)
End Sub
'skjekker om du har en time innen 90 dager
Public Function check_date(date_pick As String)
Dim siste_time As Date = CDate(date_pick)
Dim valgt_time As Date = CDate(DateTimePicker1.Text)
Dim ny_time_lovlig As Date = siste_time.AddDays(90)
If ny_time_lovlig >= valgt_time Then
Return 0
Else
Return 1
End If
End Function
'knapp for å bestille time
Private Sub btnBestillTime_Click(sender As Object, e As EventArgs) Handles btnBestillTime.Click
Dim list As ArrayList = get_appointment_date(bruker.getPersonnr)
Dim time As String = ComboBox1.Text & "." & ComboBox2.Text
If list.Count > 0 Then
If check_date(list(0)) = 1 Then
If get_appointment_user(time, DateTimePicker1.Text) = 0 Then
Dim result As Integer = MessageBox.Show("Er du sikker på at du vil ha time " & DateTimePicker1.Text & " klokka " & ComboBox1.Text & ":" & ComboBox2.Text, "Timebestilling", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
create_appointment(bruker.getPersonnr, time, DateTimePicker1.Text)
BrukerHovedside.Show()
Me.Close()
End If
ElseIf get_appointment_user(time, DateTimePicker1.Text) = bruker.getPersonnr Then
MsgBox("Du har allerede bestillt denne timen")
Else
MsgBox("Denne timen er allerede tatt")
End If
Else
MsgBox("Denne timen er ikke 90 dager etter din siste time")
End If
Else
If get_appointment_user(time, DateTimePicker1.Text) = 0 Then
Dim result As Integer = MessageBox.Show("Er du sikker på at du vil ha time " & DateTimePicker1.Text & " klokka " & ComboBox1.Text & ":" & ComboBox2.Text, "Timebestilling", MessageBoxButtons.YesNo)
If result = DialogResult.Yes Then
create_appointment(bruker.getPersonnr, time, DateTimePicker1.Text)
BrukerHovedside.Show()
Me.Close()
End If
ElseIf get_appointment_user(time, DateTimePicker1.Text) = bruker.getPersonnr Then
MsgBox("Du har allerede bestillt denne timen")
Else
MsgBox("Denne timen er allerede tatt")
End If
End If
End Sub
Private Sub TimeBestilling_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
Me.Hide()
End Sub
'leter etter tilengelige timer
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
ListBox1.Items.Clear()
Dim Timer As ArrayList
Timer = get_appointments_user(DateTimePicker1.Text)
For Each item In Timer
ListBox1.Items.Add(item(0))
Next
Label3.Text = "Disse timene er tatt " & DateTimePicker1.Text
End Sub
'navigerings knapper
Private Sub btnLoggUt_Click_1(sender As Object, e As EventArgs) Handles btnLoggUt.Click
Main.Show()
Me.Close()
End Sub
Private Sub btnMinSide_Click(sender As Object, e As EventArgs) Handles btnMinSide.Click
BrukerHovedside.Show()
Me.Close()
End Sub
Private Sub btnEgenerklaring_Click(sender As Object, e As EventArgs) Handles btnEgenerklaring.Click
MsgBox("Du må bestille en time før du kan gjøre egenerklæringen")
End Sub
Private Sub btnTimeinfo_Click(sender As Object, e As EventArgs) Handles btnTimeinfo.Click
InfoBruker.Show()
Me.Close()
End Sub
End Class
|
helliio/Aorta-DB
|
Aorta-DB/Aorta-DB/TimeBestilling.vb
|
Visual Basic
|
mit
| 4,683
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class About
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
Friend WithEvents TableLayoutPanel As System.Windows.Forms.TableLayoutPanel
Friend WithEvents LogoPictureBox As System.Windows.Forms.PictureBox
Friend WithEvents LabelProductName As System.Windows.Forms.Label
Friend WithEvents LabelVersion As System.Windows.Forms.Label
Friend WithEvents LabelCompanyName As System.Windows.Forms.Label
Friend WithEvents TextBoxDescription As System.Windows.Forms.TextBox
Friend WithEvents OKButton As System.Windows.Forms.Button
Friend WithEvents LabelCopyright As System.Windows.Forms.Label
'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(About))
Me.TableLayoutPanel = New System.Windows.Forms.TableLayoutPanel
Me.LogoPictureBox = New System.Windows.Forms.PictureBox
Me.LabelProductName = New System.Windows.Forms.Label
Me.LabelVersion = New System.Windows.Forms.Label
Me.LabelCopyright = New System.Windows.Forms.Label
Me.LabelCompanyName = New System.Windows.Forms.Label
Me.TextBoxDescription = New System.Windows.Forms.TextBox
Me.OKButton = New System.Windows.Forms.Button
Me.TableLayoutPanel.SuspendLayout()
CType(Me.LogoPictureBox, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'TableLayoutPanel
'
Me.TableLayoutPanel.ColumnCount = 2
Me.TableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.0!))
Me.TableLayoutPanel.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 67.0!))
Me.TableLayoutPanel.Controls.Add(Me.LogoPictureBox, 0, 0)
Me.TableLayoutPanel.Controls.Add(Me.LabelProductName, 1, 0)
Me.TableLayoutPanel.Controls.Add(Me.LabelVersion, 1, 1)
Me.TableLayoutPanel.Controls.Add(Me.LabelCopyright, 1, 2)
Me.TableLayoutPanel.Controls.Add(Me.LabelCompanyName, 1, 3)
Me.TableLayoutPanel.Controls.Add(Me.TextBoxDescription, 1, 4)
Me.TableLayoutPanel.Controls.Add(Me.OKButton, 1, 5)
Me.TableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill
Me.TableLayoutPanel.Location = New System.Drawing.Point(9, 9)
Me.TableLayoutPanel.Name = "TableLayoutPanel"
Me.TableLayoutPanel.RowCount = 6
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.0!))
Me.TableLayoutPanel.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10.0!))
Me.TableLayoutPanel.Size = New System.Drawing.Size(396, 258)
Me.TableLayoutPanel.TabIndex = 0
'
'LogoPictureBox
'
Me.LogoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill
Me.LogoPictureBox.Image = CType(resources.GetObject("LogoPictureBox.Image"), System.Drawing.Image)
Me.LogoPictureBox.Location = New System.Drawing.Point(3, 3)
Me.LogoPictureBox.Name = "LogoPictureBox"
Me.TableLayoutPanel.SetRowSpan(Me.LogoPictureBox, 6)
Me.LogoPictureBox.Size = New System.Drawing.Size(124, 252)
Me.LogoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage
Me.LogoPictureBox.TabIndex = 0
Me.LogoPictureBox.TabStop = False
'
'LabelProductName
'
Me.LabelProductName.Dock = System.Windows.Forms.DockStyle.Fill
Me.LabelProductName.Location = New System.Drawing.Point(136, 0)
Me.LabelProductName.Margin = New System.Windows.Forms.Padding(6, 0, 3, 0)
Me.LabelProductName.MaximumSize = New System.Drawing.Size(0, 17)
Me.LabelProductName.Name = "LabelProductName"
Me.LabelProductName.Size = New System.Drawing.Size(257, 17)
Me.LabelProductName.TabIndex = 0
Me.LabelProductName.Text = "Jeopardized!"
Me.LabelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'LabelVersion
'
Me.LabelVersion.Dock = System.Windows.Forms.DockStyle.Fill
Me.LabelVersion.Location = New System.Drawing.Point(136, 25)
Me.LabelVersion.Margin = New System.Windows.Forms.Padding(6, 0, 3, 0)
Me.LabelVersion.MaximumSize = New System.Drawing.Size(0, 17)
Me.LabelVersion.Name = "LabelVersion"
Me.LabelVersion.Size = New System.Drawing.Size(257, 17)
Me.LabelVersion.TabIndex = 0
Me.LabelVersion.Text = "Version 1.0.0.2"
Me.LabelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'LabelCopyright
'
Me.LabelCopyright.Dock = System.Windows.Forms.DockStyle.Fill
Me.LabelCopyright.Location = New System.Drawing.Point(136, 50)
Me.LabelCopyright.Margin = New System.Windows.Forms.Padding(6, 0, 3, 0)
Me.LabelCopyright.MaximumSize = New System.Drawing.Size(0, 17)
Me.LabelCopyright.Name = "LabelCopyright"
Me.LabelCopyright.Size = New System.Drawing.Size(257, 17)
Me.LabelCopyright.TabIndex = 0
Me.LabelCopyright.Text = "Copyright ©2007"
Me.LabelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'LabelCompanyName
'
Me.LabelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill
Me.LabelCompanyName.Location = New System.Drawing.Point(136, 75)
Me.LabelCompanyName.Margin = New System.Windows.Forms.Padding(6, 0, 3, 0)
Me.LabelCompanyName.MaximumSize = New System.Drawing.Size(0, 17)
Me.LabelCompanyName.Name = "LabelCompanyName"
Me.LabelCompanyName.Size = New System.Drawing.Size(257, 17)
Me.LabelCompanyName.TabIndex = 0
Me.LabelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'TextBoxDescription
'
Me.TextBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill
Me.TextBoxDescription.Location = New System.Drawing.Point(136, 103)
Me.TextBoxDescription.Margin = New System.Windows.Forms.Padding(6, 3, 3, 3)
Me.TextBoxDescription.Multiline = True
Me.TextBoxDescription.Name = "TextBoxDescription"
Me.TextBoxDescription.ReadOnly = True
Me.TextBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both
Me.TextBoxDescription.Size = New System.Drawing.Size(257, 123)
Me.TextBoxDescription.TabIndex = 0
Me.TextBoxDescription.TabStop = False
Me.TextBoxDescription.Text = resources.GetString("TextBoxDescription.Text")
'
'OKButton
'
Me.OKButton.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.OKButton.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.OKButton.Location = New System.Drawing.Point(318, 232)
Me.OKButton.Name = "OKButton"
Me.OKButton.Size = New System.Drawing.Size(75, 23)
Me.OKButton.TabIndex = 0
Me.OKButton.Text = "&OK"
'
'About
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.CancelButton = Me.OKButton
Me.ClientSize = New System.Drawing.Size(414, 276)
Me.Controls.Add(Me.TableLayoutPanel)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "About"
Me.Padding = New System.Windows.Forms.Padding(9)
Me.ShowInTaskbar = False
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
Me.Text = "About"
Me.TableLayoutPanel.ResumeLayout(False)
Me.TableLayoutPanel.PerformLayout()
CType(Me.LogoPictureBox, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
End Class
|
hgrimberg01/Jeopardized
|
Jeopardy!/About.Designer.vb
|
Visual Basic
|
apache-2.0
| 9,565
|
Namespace YahooManaged.Finance.Screener.StockCriterias
''' <summary>
''' Criteria base class
''' </summary>
''' <remarks></remarks>
Public MustInherit Class CriteriaDefinition
Public MustOverride ReadOnly Property DisplayName As String
Public MustOverride ReadOnly Property CriteriaName As String
Friend MustOverride Function CriteriaParameter() As String
Friend MustOverride ReadOnly Property IsValid As Boolean
End Class
''' <summary>
''' Criteria base class for Stock Screener
''' </summary>
''' <remarks></remarks>
Public MustInherit Class StockCriteriaDefinition
Inherits CriteriaDefinition
''' <summary>
''' The Stock Screener criteria group
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public MustOverride ReadOnly Property CriteriaGroup As StockScreenerCriteriaGroup
''' <summary>
''' The quote properties that the specific criteria class represents/provides
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public MustOverride ReadOnly Property ProvidedQuoteProperties As QuoteProperty()
''' <summary>
''' The Stock Screener properties that the specific criteria class represents/provides
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public MustOverride ReadOnly Property ProvidedScreenerProperties As StockScreenerProperty()
Friend Property CriteriaTag As String
Friend Overrides ReadOnly Property IsValid As Boolean
Get
Return Me.CriteriaTag <> String.Empty
End Get
End Property
Protected Sub New(ByVal paramType As String)
Me.CriteriaTag = paramType
End Sub
End Class
Public Interface IPercentageAvailability
''' <summary>
''' Indicates if the compared values are in percent or absolute
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Property PercentValues As Boolean
End Interface
Public Interface IGainLoss
Property GainOrLoss As StockPriceChangeDirection
End Interface
Public Interface IExtremeParameter
Property ExtremeParameter As StockExtremeParameter
End Interface
Public Interface ILessGreater
Property LessGreater As LessGreater
End Interface
Public Interface IUpDown
Property UpDown As UpDown
End Interface
Public Interface IMovingAverage
Property MovingAverage As MovingAverageType
End Interface
Public Interface IRelativeTimeSpan
Property RelativeTimeSpanInMinutes As StockTradingTimeSpan
End Interface
Public Interface IRelativeTimePoint
Property TimeSpanRelativeTo As StockTradingRelativeTimePoint
End Interface
Public Interface IAbsoluteTimePoint
Property ValueRelativeTo As StockTradingAbsoluteTimePoint
End Interface
''' <summary>
''' Criteria base class for Stock Screener and digit values
''' </summary>
''' <remarks></remarks>
Public MustInherit Class StockDigitCriteriaDefinition
Inherits StockCriteriaDefinition
Private mConverterCulture As New Globalization.CultureInfo("en-US")
''' <summary>
''' The maximum value of the value range.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property MinimumValue As Nullable(Of Double) = Nothing
''' <summary>
''' The minimum value of the value range
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property MaximumValue As Nullable(Of Double) = Nothing
Friend Property OptionalParamValue As Integer = -1
Friend Overrides ReadOnly Property IsValid As Boolean
Get
Return MyBase.IsValid AndAlso (Me.MaximumValue.HasValue Or Me.MinimumValue.HasValue)
End Get
End Property
Protected Sub New(ByVal paramType As String)
MyBase.New(paramType)
Me.MinimumValue = 0
End Sub
Friend Overrides Function CriteriaParameter() As String
If Me.IsValid Then
Return "&" & MyBase.CriteriaTag & "=" & IIf(Me.OptionalParamValue <> -1, Me.OptionalParamValue.ToString & "_", "").ToString & Me.GetParamDigitValue(Me.MinimumValue) & "_" & Me.GetParamDigitValue(Me.MaximumValue) & "_e_3"
Else
Throw New NotSupportedException("The parameters are invalid.")
End If
End Function
Private Function GetParamDigitValue(ByVal paramValue As Nullable(Of Double)) As String
If paramValue.HasValue Then
Return paramValue.Value.ToString(mConverterCulture)
Else
Return "u"
End If
End Function
End Class
''' <summary>
''' Criteria base class for Stock Screener and string values
''' </summary>
''' <remarks></remarks>
Public MustInherit Class StockStringCriteriaDefinition
Inherits StockCriteriaDefinition
Friend Property Value As String = String.Empty
Friend Overrides ReadOnly Property IsValid As Boolean
Get
Return MyBase.IsValid AndAlso Me.Value <> String.Empty
End Get
End Property
Protected Sub New(ByVal paramType As String)
MyBase.New(paramType)
End Sub
Friend Overrides Function CriteriaParameter() As String
If Me.IsValid Then
Return "&" & MyBase.CriteriaTag & "=" & Me.Value & "_e_3"
Else
Throw New NotSupportedException("The parameters are invalid.")
End If
End Function
End Class
End Namespace
|
agassan/YahooManaged
|
MaasOne.YahooManaged/YahooManaged/Finance/Screener/StockScreenerCriterias/BaseCriterias.vb
|
Visual Basic
|
apache-2.0
| 6,079
|
Imports System.IO
Imports jp.co.systembase.json
Imports jp.co.systembase.report
Imports jp.co.systembase.report.data
Imports jp.co.systembase.report.renderer.pdf2
Public Class Test_4_23_Rect
Public Overrides Function ToString() As String
Return "4.23 四角形の枠線"
End Function
Public Sub Run()
Dim name As String = "test_4_23_rect"
Dim report As New Report(Json.Read("rrpt\" & name & ".rrpt"))
report.GlobalScope.Add("time", Now)
report.GlobalScope.Add("lang", "vb")
report.Fill(DummyDataSource.GetInstance)
Dim pages As ReportPages = report.GetPages()
Using fs As New FileStream("out\" & name & ".pdf", IO.FileMode.Create)
Dim renderer As New PdfRenderer(fs)
pages.Render(renderer)
End Using
End Sub
End Class
|
rapidreport/dotnet-pdf2
|
test/Test_4_23_Rect.vb
|
Visual Basic
|
bsd-2-clause
| 842
|
Imports System.Windows.Forms
Imports System.Data.SqlClient
Public Class frmAddExpense
Public myGuid As String
Public Mode As String
Public WithEvents cms As New ContextMenuStrip
Private drHistory As DataTable
Public sHandle As String = ""
Private sHistoryGuid As String
Private Sub frmTicketAdd_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
mGRCData = New GRCSec.GridcoinData
Catch ex As Exception
MsgBox("Unable to load page " + ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
sHandle = KeyValue("TicketHandle")
Try
If Mode <> "View" Then
If sHandle = "" Then
MsgBox("Click <OK> to populate your GridCoin Username.", MsgBoxStyle.Critical)
Dim frmU As New frmUserName
frmU.Show()
Me.Dispose()
Exit Sub
End If
End If
txtSubmittedBy.Text = sHandle
If myGuid <> "" Then
txtTicketId.Text = myGuid
If Mode = "View" Then
'Depersist from GFS
Dim oExpense As SqlDataReader = mGRCData.GetBusinessObject("Expense", txtTicketId.Text, "ExpenseID")
If oExpense.HasRows = False Then
MsgBox("Sorry, this expense does not exist.", MsgBoxStyle.Critical)
Exit Sub
End If
txtDescription.Text = oExpense("Descript")
txtAmount.Text = Trim(oExpense("Amount"))
txtAttachment.Text = Trim("" & oExpense("AttachmentName"))
txtSubmittedBy.Text = Trim("" & oExpense("SubmittedBy"))
rtbNotes.Text = Trim("" & oExpense("Comments"))
Dim sType As String = Trim("" & oExpense("Type"))
If sType = "Expense" Then rbExpense.Checked = True Else rbCampaign.Checked = True
btnSubmit.ForeColor = Drawing.Color.White
GroupBox1.Enabled = False
btnAddAttachment.Enabled = False
btnSubmit.Enabled = False
lblMode.Text = Mode + " Mode"
End If
Else
txtTicketId.Text = Guid.NewGuid.ToString()
btnAddAttachment.Enabled = True
btnSubmit.ForeColor = Drawing.Color.Lime
GroupBox1.Enabled = True
btnSubmit.Enabled = True
lblMode.Text = Mode + " Mode"
End If
Catch ex As Exception
Me.Dispose()
End Try
End Sub
Public Function NormalizeNote(sData As String)
Dim sOut As String
sOut = Replace(sData, "<LF>", vbCrLf)
Return sOut
End Function
Public Function NormalizeNoteRow(sData As String)
Dim sOut As String
sOut = Replace(sData, "<LF>", "; ")
Return sOut
End Function
Public Sub ShowTicket(sId As String)
txtTicketId.Text = sId
Call frmTicketAdd_Load(Me, Nothing)
PopulateHistory()
Me.Show()
Dim dr As DataTable = mGetTicket(txtTicketId.Text)
If dr Is Nothing Then Exit Sub
txtSubmittedBy.Text = dr.Rows(0)("SubmittedBy")
txtTicketId.Text = sId
txtDescription.Text = dr.Rows(0)("Descript")
Call PopulateHistory()
SetViewMode()
Me.TopMost = True
Me.Refresh()
Me.TopMost = False
End Sub
Private Sub SetViewMode()
Mode = "Add"
txtDescription.ReadOnly = True
End Sub
Public Sub AddTicket()
Mode = "Add"
If Mode = "Add" Then
If Val(txtTicketId.Text) = 0 Then
Dim maxTick As Double = mGRCData.P2PMax("TicketId", "Ticket", "", "")
txtTicketId.Text = Trim(maxTick + 1)
End If
End If
End Sub
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
' Add the new campaign or expense
If Len(txtSubmittedBy.Text) = 0 Then
MsgBox("Submitted By must be populated.", MsgBoxStyle.Critical)
Exit Sub
End If
If Len(txtAttachment.Text) = 0 Then
MsgBox("Attachment must be provided.", MsgBoxStyle.Critical)
Exit Sub
End If
If Len(txtDescription.Text) = 0 Or Len(rtbNotes.Text) = 0 Then
MsgBox("Description And Notes must be populated with data.", MsgBoxStyle.Critical)
Exit Sub
End If
If IsDate(dtStart.Text) = False Or IsDate(dtEnd.Text) = False Then
MsgBox("Start and End Date must be populated", MsgBoxStyle.Critical)
Exit Sub
End If
If IsNumeric(txtAmount.Text) = False Then
MsgBox("Amount must be populated", MsgBoxStyle.Critical)
Exit Sub
End If
If Val(txtAmount.Text) = 0 Then
MsgBox("Amount must be greater than zero", MsgBoxStyle.Critical)
Exit Sub
End If
If Not rbExpense.Checked And Not rbCampaign.Checked Then
MsgBox("Please choose a type of submission: campaign or expense", MsgBoxStyle.Critical)
Exit Sub
End If
Dim sType As String = IIf(rbExpense.Checked, "Expense", "Campaign")
'Add the poll first, ensure it does not fail...
'execute addpoll Expense_Authorization_[Foundation_blah] 21 Campaign_1 Approve;Deny 3
Dim sTitle As String = IIf(sType = "Expense", "Expense_Submission" + txtDescription.Text, "New_Campaign_" + txtDescription.Text)
sTitle = Replace(sTitle, " ", "_")
sTitle += "[Foundation_" + txtTicketId.Text + "]"
Dim sQuestion As String = IIf(sType = "Expense", "Approve_Expense?", "Approve_Campaign?")
'if they are not logged on... throw an error ... 4-22-2016
If sHandle = "" Then
MsgBox("Please create a user name first. After logging in you may re-submit the form.", MsgBoxStyle.Critical, "Not Logged In")
Dim frmU1 As New frmUserName
frmU1.Show()
Exit Sub
End If
Dim sAnswers As String = "Approve;Deny"
Try
mGRCData.mInsertExpense(Mode, txtSubmittedBy.Text, txtTicketId.Text, "All", _
sType, txtDescription.Text, sType, rtbNotes.Text, MerkleRoot, _
Trim(dtStart.Text), Trim(dtEnd.Text), Trim(txtAmount.Text), rtbNotes.Text, txtAttachment.Text)
Catch ex As Exception
MsgBox("An error occurred while inserting the new expense [" + ex.Message + "]", MsgBoxStyle.Critical, "Gridcoin Foundation - Expense System")
Exit Sub
End Try
Dim sResult As String = ExecuteRPCCommand("addpoll", sTitle, "21", sQuestion, sAnswers, "3", "http://www.gridcoin.us")
If Not LCase(sResult).Contains("success") Then
MsgBox(sResult, MsgBoxStyle.Information, "Gridcoin Foundation - Expense System")
Exit Sub
End If
SetViewMode()
btnSubmit.Enabled = True
System.Windows.Forms.Cursor.Current = Cursors.Default
MsgBox("Success: Your " + sType + " has been added. ", MsgBoxStyle.Information)
Me.Hide()
End Sub
Public Sub PopulateHistory()
drHistory = mGetTicketHistory(txtTicketId.Text)
If drHistory Is Nothing Then Exit Sub
Dim sAttach As String = ""
For i As Integer = 0 To drHistory.Rows.Count - 1
Dim sRow As String = drHistory.Rows(i)("Disposition") + " - " _
+ Mid(NormalizeNoteRow(drHistory.Rows(i)("notes")), 1, 80) _
+ " - " + drHistory.Rows(i)("AssignedTo") + " - " + drHistory.Rows(i)("updated")
sAttach = drHistory.Rows(i)("BlobName")
txtAttachment.Text = sAttach
If Len(sAttach) > 1 Then sAttach = " - [" + sAttach + "]"
sRow += sAttach
Dim node As TreeNode = New TreeNode(sRow)
node.Tag = i
rtbNotes.Text = NormalizeNote(drHistory.Rows(i)("Notes"))
'Verify security hash:
Dim lAuthentic As Long = 0
lAuthentic = mGRCSecurity.IsHashAuthentic("" & drHistory.Rows(i)("SecurityGuid"), _
"" & drHistory.Rows(i)("SecurityHash"), "" _
& drHistory.Rows(i)("PasswordHash"))
'If lAuthentic <> 0 Then node.ForeColor = Drawing.Color.Red
Next i
End Sub
Private Sub btnAddAttachment_Click(sender As System.Object, e As System.EventArgs) Handles btnAddAttachment.Click
Dim sBlobGuid As String
sBlobGuid = txtTicketId.Text
If Len(sBlobGuid) < 5 Then MsgBox("You must select a historical ticket history item before attaching.", MsgBoxStyle.Critical) : Exit Sub
Dim OFD As New OpenFileDialog()
OFD.InitialDirectory = GetGridFolder()
OFD.Filter = "CSV Files (*.csv)|*.csv|Adobe PDF Files (*.pdf)|*.pdf|Excel Files (*.xls)|*.xls|Excel Files (*.xlsx)|*.xlsx"
OFD.FilterIndex = 2
OFD.RestoreDirectory = True
Me.TopMost = False
If OFD.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
Dim b As Byte()
b = FileToBytes(OFD.FileName)
'Encrypt
b = AES512EncryptData(b, MerkleRoot)
Dim sSuccess As String = mGRCData.mInsertAttachment(sBlobGuid, OFD.SafeFileName, _
b, "", mGRCData.GetHandle(GetSessionGuid()))
txtAttachment.Text = OFD.SafeFileName
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
End Try
End If
End Sub
Private Function DownloadAttachment() As String
Try
If Len(txtAttachment.Text) > 1 Then
'First does it exist already?
Dim sDir As String = ""
sDir = GetGridFolder() + "Attachments\"
Dim sFullPath As String
sFullPath = sDir + txtAttachment.Text
If System.IO.Directory.Exists(sDir) = False Then MkDir(sDir)
If Not System.IO.File.Exists(sFullPath) Then
'Download from GFS
Dim sID As String = txtTicketId.Text
If Len(sID) < 5 Then MsgBox("Attachment has been removed from the P2P server", MsgBoxStyle.Critical) : Exit Function
sFullPath = mRetrieveAttachment(sID, txtAttachment.Text, MerkleRoot)
End If
Return sFullPath
End If
Catch ex As Exception
MsgBox("Failed to download from GFS: " + ex.Message)
End Try
End Function
Private Function AttachmentSecurityScan(bSecurityEnabled As Boolean) As Boolean
If Len(txtAttachment.Text) = 0 Then Exit Function
Try
Dim sBlobGuid As String = ""
Dim sID As String = txtTicketId.Text
Dim bSuccess = mAttachmentSecurityScan(sID)
If Not bSuccess And bSecurityEnabled Then
MsgBox("! WARNING ! Attachment came from an unverifiable source. Virus scan the file and use extreme caution before opening it.", MsgBoxStyle.Critical, "Authenticity Scan Failed")
End If
Return bSuccess
Catch ex As Exception
MsgBox("Document has failed security scanning and has been removed from the P2P server", MsgBoxStyle.Critical)
End Try
End Function
Private Sub btnOpen_Click(sender As System.Object, e As System.EventArgs) Handles btnOpen.Click
Try
Dim sFullpath As String = DownloadAttachment()
Dim bAuthScan As Boolean = AttachmentSecurityScan(False)
'If Not bAuthScan Then Exit Sub 'dont let the user open it
If System.IO.File.Exists(sFullpath) Then
'Launch
Process.Start(sFullpath)
End If
Catch ex As Exception
MsgBox("Document has been removed from the P2P server " + ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub btnOpenFolder_Click(sender As System.Object, e As System.EventArgs)
Call AttachmentSecurityScan(False)
Dim sFullpath As String = DownloadAttachment()
If System.IO.File.Exists(sFullpath) Then
Process.Start(GetGridFolder() + "Attachments\")
Else
MsgBox("File has been removed from the P2P Server", MsgBoxStyle.Critical)
End If
End Sub
Private Sub btnVirusScan_Click(sender As System.Object, e As System.EventArgs) Handles btnVirusScan.Click
'8-3-2015
Dim sFullpath As String = DownloadAttachment()
Dim sMd5 As String = GetMd5OfFile(sFullpath)
Dim webAddress As String = "https://www.virustotal.com/latest-scan/" + sMd5
Process.Start(webAddress)
End Sub
End Class
|
Lederstrumpf/Gridcoin-Research
|
contrib/Installer/boinc/boinc/frmAddExpense.vb
|
Visual Basic
|
mit
| 13,265
|
Option Strict On
Namespace Xeora.Web.Handler
Public Class RemoteInvoke
Private Shared _XeoraSettings As Configuration.XeoraSection
Private Shared _VariablePoolService As Site.Service.VariablePool
Public Shared Sub ReloadApplication(ByVal RequestID As String)
Dim Context As [Shared].IHttpContext =
Web.Context.ContextManager.Current.Context(RequestID)
RequestModule.DisposeAll()
If Not Context Is Nothing Then _
Context.Response.Redirect(Context.Request.URL.Raw)
End Sub
Public Shared ReadOnly Property Context(ByVal RequestID As String) As [Shared].IHttpContext
Get
Return Web.Context.ContextManager.Current.Context(RequestID)
End Get
End Property
Public Shared ReadOnly Property VariablePool() As Site.Service.VariablePool
Get
If RemoteInvoke._VariablePoolService Is Nothing Then _
RemoteInvoke._VariablePoolService = New Site.Service.VariablePool()
Return RemoteInvoke._VariablePoolService
End Get
End Property
Public Shared Property XeoraSettings() As Configuration.XeoraSection
Get
Return RemoteInvoke._XeoraSettings
End Get
Friend Set(ByVal value As Configuration.XeoraSection)
RemoteInvoke._XeoraSettings = value
End Set
End Property
End Class
End Namespace
|
xeora/XeoraCube
|
Framework/Xeora.Web.Handler/RemoteInvoke.vb
|
Visual Basic
|
mit
| 1,524
|
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library
Public Module Extensions_258
''' <summary>
''' Returns the specified 16-bit signed integer value as an array of bytes.
''' </summary>
''' <param name="value">The number to convert.</param>
''' <returns>An array of bytes with length 2.</returns>
<System.Runtime.CompilerServices.Extension> _
Public Function GetBytes(value As Int16) As [Byte]()
Return BitConverter.GetBytes(value)
End Function
End Module
|
huoxudong125/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Int16/System.BitConverter/Int16.GetBytes.vb
|
Visual Basic
|
mit
| 802
|
' 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.Threading
Imports Microsoft.CodeAnalysis.AddImports
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports
<ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicAddImportsService
Inherits AbstractAddImportsService(Of
CompilationUnitSyntax,
NamespaceBlockSyntax,
ImportsStatementSyntax,
ImportsStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer())
Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean
Dim importsA = TryCast(a, ImportsStatementSyntax)
Dim importsB = TryCast(b, ImportsStatementSyntax)
If importsA Is Nothing OrElse importsB Is Nothing Then
Return False
End If
Return ImportsStatementComparer.Compare(importsA, importsB) = 0
End Function
Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode)
Dim result = ArrayBuilder(Of SyntaxNode).GetInstance()
For Each import In compilation.MemberImports()
If TypeOf import Is INamespaceSymbol Then
result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString()))
End If
Next
Return result.ToImmutableAndFree()
End Function
Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode
Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax).
Where(Function(c) c.Alias IsNot Nothing).
FirstOrDefault()?.Alias
End Function
Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean
' Visual Basic doesn't support static imports
Return False
End Function
Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
If node.Kind() = SyntaxKind.CompilationUnit Then
Return DirectCast(node, CompilationUnitSyntax).Imports
End If
Return Nothing
End Function
Protected Overrides Function Rewrite(
externAliases() As ImportsStatementSyntax,
usingDirectives() As ImportsStatementSyntax,
staticUsingDirectives() As ImportsStatementSyntax,
aliasDirectives() As ImportsStatementSyntax,
externContainer As SyntaxNode,
usingContainer As SyntaxNode,
staticUsingContainer As SyntaxNode,
aliasContainer As SyntaxNode,
placeSystemNamespaceFirst As Boolean,
root As SyntaxNode,
cancellationToken As CancellationToken) As SyntaxNode
Dim compilationUnit = DirectCast(root, CompilationUnitSyntax)
If Not compilationUnit.CanAddImportsStatements(cancellationToken) Then
Return compilationUnit
End If
Return compilationUnit.AddImportsStatements(
usingDirectives.Concat(aliasDirectives).ToList(),
placeSystemNamespaceFirst,
Array.Empty(Of SyntaxAnnotation))
End Function
Private Class CaseInsensitiveTokenComparer
Implements IComparer(Of SyntaxToken)
Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare
' By using 'ValueText' we get the value that is normalized. i.e.
' [class] will be 'class', and unicode escapes will be converted
' to actual unicode. This allows sorting to work properly across
' tokens that have different source representations, but which
' mean the same thing.
' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens.
Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText())
End Function
End Class
End Class
End Namespace
|
jmarolf/roslyn
|
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb
|
Visual Basic
|
mit
| 5,255
|
' 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.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenLateBound
Inherits BasicTestBase
<Fact()>
Public Sub LateAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
obj.P1 = 42 ' assignment (Set)
obj.P1() ' side-effect (Call)
Console.WriteLine(obj.P1) ' value (Get)
End Sub
Class cls1
Private _p1 As Integer
Public Property p1 As Integer
Get
Console.Write("Get")
Return _p1
End Get
Set(value As Integer)
Console.Write("Set")
_p1 = value
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[SetGetGet42]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 91 (0x5b)
.maxstack 8
.locals init (Object V_0) //obj
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: ldstr "P1"
IL_000d: ldc.i4.1
IL_000e: newarr "Object"
IL_0013: dup
IL_0014: ldc.i4.0
IL_0015: ldc.i4.s 42
IL_0017: box "Integer"
IL_001c: stelem.ref
IL_001d: ldnull
IL_001e: ldnull
IL_001f: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object, System.Type, String, Object(), String(), System.Type())"
IL_0024: ldloc.0
IL_0025: ldnull
IL_0026: ldstr "P1"
IL_002b: ldc.i4.0
IL_002c: newarr "Object"
IL_0031: ldnull
IL_0032: ldnull
IL_0033: ldnull
IL_0034: ldc.i4.1
IL_0035: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_003a: pop
IL_003b: ldloc.0
IL_003c: ldnull
IL_003d: ldstr "P1"
IL_0042: ldc.i4.0
IL_0043: newarr "Object"
IL_0048: ldnull
IL_0049: ldnull
IL_004a: ldnull
IL_004b: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0050: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0055: call "Sub System.Console.WriteLine(Object)"
IL_005a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateAccessByref()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
goo(obj.p1) 'LateSetComplex
Console.WriteLine(obj.P1)
End Sub
Sub goo(ByRef x As Object)
x = 42
End Sub
Class cls1
Private _p1 As Integer
Public Property p1 As Integer
Get
Console.Write("Get")
Return _p1
End Get
Set(value As Integer)
Console.Write("Set")
_p1 = value
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[GetSetGet42]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 98 (0x62)
.maxstack 8
.locals init (Object V_0, //obj
Object V_1)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: dup
IL_0008: ldnull
IL_0009: ldstr "p1"
IL_000e: ldc.i4.0
IL_000f: newarr "Object"
IL_0014: ldnull
IL_0015: ldnull
IL_0016: ldnull
IL_0017: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_001c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0021: stloc.1
IL_0022: ldloca.s V_1
IL_0024: call "Sub Program.goo(ByRef Object)"
IL_0029: ldnull
IL_002a: ldstr "p1"
IL_002f: ldc.i4.1
IL_0030: newarr "Object"
IL_0035: dup
IL_0036: ldc.i4.0
IL_0037: ldloc.1
IL_0038: stelem.ref
IL_0039: ldnull
IL_003a: ldnull
IL_003b: ldc.i4.1
IL_003c: ldc.i4.0
IL_003d: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(Object, System.Type, String, Object(), String(), System.Type(), Boolean, Boolean)"
IL_0042: ldloc.0
IL_0043: ldnull
IL_0044: ldstr "P1"
IL_0049: ldc.i4.0
IL_004a: newarr "Object"
IL_004f: ldnull
IL_0050: ldnull
IL_0051: ldnull
IL_0052: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0057: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_005c: call "Sub System.Console.WriteLine(Object)"
IL_0061: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateCall()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Module Program
Sub Main()
Dim obj As Object = "hi"
cls1.goo$(obj)
End Sub
Class cls1
Shared Function goo$(x As Integer)
System.Console.WriteLine("int")
Return Nothing
End Function
Shared Function goo$(x As String)
System.Console.WriteLine("str")
Return Nothing
End Function
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[str]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 70 (0x46)
.maxstack 10
.locals init (Object V_0, //obj
Object() V_1,
Boolean() V_2)
IL_0000: ldstr "hi"
IL_0005: stloc.0
IL_0006: ldnull
IL_0007: ldtoken "Program.cls1"
IL_000c: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0011: ldstr "goo"
IL_0016: ldc.i4.1
IL_0017: newarr "Object"
IL_001c: dup
IL_001d: ldc.i4.0
IL_001e: ldloc.0
IL_001f: stelem.ref
IL_0020: dup
IL_0021: stloc.1
IL_0022: ldnull
IL_0023: ldnull
IL_0024: ldc.i4.1
IL_0025: newarr "Boolean"
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldc.i4.1
IL_002d: stelem.i1
IL_002e: dup
IL_002f: stloc.2
IL_0030: ldc.i4.1
IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0036: pop
IL_0037: ldloc.2
IL_0038: ldc.i4.0
IL_0039: ldelem.u1
IL_003a: brfalse.s IL_0045
IL_003c: ldloc.1
IL_003d: ldc.i4.0
IL_003e: ldelem.ref
IL_003f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0044: stloc.0
IL_0045: ret
}
]]>)
End Sub
<Fact()>
Public Sub GenericCall()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
obj.Goo(Of String)()
Console.WriteLine(obj.Goo(Of Integer)())
End Sub
Class cls1
Public Function goo(Of T)()
Console.WriteLine(GetType(T))
Return 42
End Function
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[System.String
System.Int32
42]]>)
End Sub
<Fact()>
Public Sub LateIndex()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
obj(1) = 41 ' assignment (IndexSet)
Console.WriteLine(obj(1)) ' value (IndexGet)
End Sub
Class cls1
Private _p1 As Integer
Default Public Property p1(x As Integer) As Integer
Get
Console.Write("Get")
Return _p1
End Get
Set(value As Integer)
Console.Write("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[SetGet42]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 71 (0x47)
.maxstack 5
.locals init (Object V_0) //obj
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.2
IL_0008: newarr "Object"
IL_000d: dup
IL_000e: ldc.i4.0
IL_000f: ldc.i4.1
IL_0010: box "Integer"
IL_0015: stelem.ref
IL_0016: dup
IL_0017: ldc.i4.1
IL_0018: ldc.i4.s 41
IL_001a: box "Integer"
IL_001f: stelem.ref
IL_0020: ldnull
IL_0021: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object, Object(), String())"
IL_0026: ldloc.0
IL_0027: ldc.i4.1
IL_0028: newarr "Object"
IL_002d: dup
IL_002e: ldc.i4.0
IL_002f: ldc.i4.1
IL_0030: box "Integer"
IL_0035: stelem.ref
IL_0036: ldnull
IL_0037: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_003c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0041: call "Sub System.Console.WriteLine(Object)"
IL_0046: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateIndexRValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
Dim c As New cls1
obj(c(1)) = c(40) ' assignment (IndexSet)
Console.WriteLine(obj(c(1))) ' value (IndexGet)
Dim saveCulture = System.Threading.Thread.CurrentThread.CurrentCulture
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
obj(Sub()
End Sub) = 7 ' InvalidCast
Catch ex As InvalidCastException
Console.WriteLine(ex.Message)
Finally
System.Threading.Thread.CurrentThread.CurrentCulture = saveCulture
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Class cls1
Private _p1 As Integer
Default Public Property p1(x As Integer) As Integer
Get
Console.Write("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.Write("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[GetGetSetGetGet42
Method invocation failed because 'Public Property p1(x As Integer) As Integer' cannot be called with these arguments:
Argument matching parameter 'x' cannot convert from 'VB$AnonymousDelegate_0' to 'Integer'.]]>)
End Sub
<Fact()>
Public Sub LateIndexByref()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Dim obj As Object = New cls1
Sub Main()
goo(EvalObj(x:=EvalArg)) 'LateIndexSetComplex
Console.WriteLine(obj(1))
End Sub
Private Function EvalArg() As Integer
Console.Write("EvalArg")
Return 1
End Function
Private Function EvalObj() As Object
Console.Write("EvalObj")
Return obj
End Function
Sub goo(ByRef x As Object)
x = 40
End Sub
Class cls1
Private _p1 As Integer
Default Public Property p1(x As Integer) As Integer
Get
Console.Write("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.Write("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[EvalObjEvalArgGetSetGet42]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 133 (0x85)
.maxstack 6
.locals init (Object V_0,
Object V_1,
Object V_2)
IL_0000: call "Function Program.EvalObj() As Object"
IL_0005: dup
IL_0006: stloc.0
IL_0007: ldc.i4.1
IL_0008: newarr "Object"
IL_000d: dup
IL_000e: ldc.i4.0
IL_000f: call "Function Program.EvalArg() As Integer"
IL_0014: box "Integer"
IL_0019: dup
IL_001a: stloc.1
IL_001b: stelem.ref
IL_001c: ldc.i4.1
IL_001d: newarr "String"
IL_0022: dup
IL_0023: ldc.i4.0
IL_0024: ldstr "x"
IL_0029: stelem.ref
IL_002a: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_002f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0034: stloc.2
IL_0035: ldloca.s V_2
IL_0037: call "Sub Program.goo(ByRef Object)"
IL_003c: ldloc.0
IL_003d: ldc.i4.2
IL_003e: newarr "Object"
IL_0043: dup
IL_0044: ldc.i4.0
IL_0045: ldloc.1
IL_0046: stelem.ref
IL_0047: dup
IL_0048: ldc.i4.1
IL_0049: ldloc.2
IL_004a: stelem.ref
IL_004b: ldc.i4.1
IL_004c: newarr "String"
IL_0051: dup
IL_0052: ldc.i4.0
IL_0053: ldstr "x"
IL_0058: stelem.ref
IL_0059: ldc.i4.1
IL_005a: ldc.i4.1
IL_005b: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSetComplex(Object, Object(), String(), Boolean, Boolean)"
IL_0060: ldsfld "Program.obj As Object"
IL_0065: ldc.i4.1
IL_0066: newarr "Object"
IL_006b: dup
IL_006c: ldc.i4.0
IL_006d: ldc.i4.1
IL_006e: box "Integer"
IL_0073: stelem.ref
IL_0074: ldnull
IL_0075: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_007a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_007f: call "Sub System.Console.WriteLine(Object)"
IL_0084: ret
}
]]>)
End Sub
<WorkItem(543749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543749")>
<Fact()>
Public Sub MethodCallWithoutArgParensEnclosedInParens()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Try
Dim a = ("a".Clone)()
Catch ex As MissingMemberException
End Try
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (System.MissingMemberException V_0) //ex
.try
{
IL_0000: ldstr "a"
IL_0005: call "Function String.Clone() As Object"
IL_000a: ldc.i4.0
IL_000b: newarr "Object"
IL_0010: ldnull
IL_0011: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_001b: pop
IL_001c: leave.s IL_002c
}
catch System.MissingMemberException
{
IL_001e: dup
IL_001f: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0024: stloc.0
IL_0025: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_002a: leave.s IL_002c
}
IL_002c: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateAccessCompound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
x.p += 1
Console.WriteLine(x.p)
End Sub
Class cls1
Private _p1 As Integer
Public Property p() As Integer
Get
Console.WriteLine("Get")
Return _p1
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Set
Get
1]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 95 (0x5f)
.maxstack 13
.locals init (Object V_0, //x
Object V_1)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldnull
IL_000a: ldstr "p"
IL_000f: ldc.i4.1
IL_0010: newarr "Object"
IL_0015: dup
IL_0016: ldc.i4.0
IL_0017: ldloc.1
IL_0018: ldnull
IL_0019: ldstr "p"
IL_001e: ldc.i4.0
IL_001f: newarr "Object"
IL_0024: ldnull
IL_0025: ldnull
IL_0026: ldnull
IL_0027: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_002c: ldc.i4.1
IL_002d: box "Integer"
IL_0032: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_0037: stelem.ref
IL_0038: ldnull
IL_0039: ldnull
IL_003a: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object, System.Type, String, Object(), String(), System.Type())"
IL_003f: ldloc.0
IL_0040: ldnull
IL_0041: ldstr "p"
IL_0046: ldc.i4.0
IL_0047: newarr "Object"
IL_004c: ldnull
IL_004d: ldnull
IL_004e: ldnull
IL_004f: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0054: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0059: call "Sub System.Console.WriteLine(Object)"
IL_005e: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateIndexCompound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As object = New cls1
x(Eval) += 1
Console.WriteLine(x(1))
End Sub
Private Function Eval() As Integer
Console.WriteLine("Eval")
Return 1
End Function
Structure cls1
Private _p1 As Integer
Default Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Structure
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Eval
Get
Set
Get
4]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 109 (0x6d)
.maxstack 9
.locals init (Object V_0, //x
Program.cls1 V_1,
Object V_2,
Object V_3)
IL_0000: ldloca.s V_1
IL_0002: initobj "Program.cls1"
IL_0008: ldloc.1
IL_0009: box "Program.cls1"
IL_000e: stloc.0
IL_000f: ldloc.0
IL_0010: stloc.2
IL_0011: ldloc.2
IL_0012: ldc.i4.2
IL_0013: newarr "Object"
IL_0018: dup
IL_0019: ldc.i4.0
IL_001a: call "Function Program.Eval() As Integer"
IL_001f: box "Integer"
IL_0024: dup
IL_0025: stloc.3
IL_0026: stelem.ref
IL_0027: dup
IL_0028: ldc.i4.1
IL_0029: ldloc.2
IL_002a: ldc.i4.1
IL_002b: newarr "Object"
IL_0030: dup
IL_0031: ldc.i4.0
IL_0032: ldloc.3
IL_0033: stelem.ref
IL_0034: ldnull
IL_0035: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_003a: ldc.i4.1
IL_003b: box "Integer"
IL_0040: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_0045: stelem.ref
IL_0046: ldnull
IL_0047: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object, Object(), String())"
IL_004c: ldloc.0
IL_004d: ldc.i4.1
IL_004e: newarr "Object"
IL_0053: dup
IL_0054: ldc.i4.0
IL_0055: ldc.i4.1
IL_0056: box "Integer"
IL_005b: stelem.ref
IL_005c: ldnull
IL_005d: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_0062: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0067: call "Sub System.Console.WriteLine(Object)"
IL_006c: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberCompound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
x.p(Eval) += 1
Console.WriteLine(x.p(1))
End Sub
Private Function Eval() As Integer
Console.WriteLine("Eval")
Return 1
End Function
Class cls1
Private _p1 As Integer
Default Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Eval
Get
Set
Get
4]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 123 (0x7b)
.maxstack 13
.locals init (Object V_0, //x
Object V_1,
Object V_2)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: stloc.1
IL_0008: ldloc.1
IL_0009: ldnull
IL_000a: ldstr "p"
IL_000f: ldc.i4.2
IL_0010: newarr "Object"
IL_0015: dup
IL_0016: ldc.i4.0
IL_0017: call "Function Program.Eval() As Integer"
IL_001c: box "Integer"
IL_0021: dup
IL_0022: stloc.2
IL_0023: stelem.ref
IL_0024: dup
IL_0025: ldc.i4.1
IL_0026: ldloc.1
IL_0027: ldnull
IL_0028: ldstr "p"
IL_002d: ldc.i4.1
IL_002e: newarr "Object"
IL_0033: dup
IL_0034: ldc.i4.0
IL_0035: ldloc.2
IL_0036: stelem.ref
IL_0037: ldnull
IL_0038: ldnull
IL_0039: ldnull
IL_003a: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_003f: ldc.i4.1
IL_0040: box "Integer"
IL_0045: call "Function Microsoft.VisualBasic.CompilerServices.Operators.AddObject(Object, Object) As Object"
IL_004a: stelem.ref
IL_004b: ldnull
IL_004c: ldnull
IL_004d: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object, System.Type, String, Object(), String(), System.Type())"
IL_0052: ldloc.0
IL_0053: ldnull
IL_0054: ldstr "p"
IL_0059: ldc.i4.1
IL_005a: newarr "Object"
IL_005f: dup
IL_0060: ldc.i4.0
IL_0061: ldc.i4.1
IL_0062: box "Integer"
IL_0067: stelem.ref
IL_0068: ldnull
IL_0069: ldnull
IL_006a: ldnull
IL_006b: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0070: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0075: call "Sub System.Console.WriteLine(Object)"
IL_007a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberInvoke()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
x.p(Eval)
End Sub
Private Function Eval() As Integer
Console.WriteLine("Eval")
Return 1
End Function
Class cls1
Private _p1 As Integer
Default Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Eval
Get]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 41 (0x29)
.maxstack 8
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: ldnull
IL_0006: ldstr "p"
IL_000b: ldc.i4.1
IL_000c: newarr "Object"
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: call "Function Program.Eval() As Integer"
IL_0018: box "Integer"
IL_001d: stelem.ref
IL_001e: ldnull
IL_001f: ldnull
IL_0020: ldnull
IL_0021: ldc.i4.1
IL_0022: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0027: pop
IL_0028: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberInvoke1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As New cls1
x.goo(c.p)
Console.WriteLine(c.p)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p() As Integer
Get
Console.WriteLine("Get")
Return _p1
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Set
Get
1]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 113 (0x71)
.maxstack 10
.locals init (Program.cls1 V_0, //c
Program.cls1 V_1,
Object() V_2,
Boolean() V_3)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: newobj "Sub Program.cls1..ctor()"
IL_000a: stloc.0
IL_000b: ldnull
IL_000c: ldstr "goo"
IL_0011: ldc.i4.1
IL_0012: newarr "Object"
IL_0017: dup
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: dup
IL_001b: stloc.1
IL_001c: callvirt "Function Program.cls1.get_p() As Integer"
IL_0021: box "Integer"
IL_0026: stelem.ref
IL_0027: dup
IL_0028: stloc.2
IL_0029: ldnull
IL_002a: ldnull
IL_002b: ldc.i4.1
IL_002c: newarr "Boolean"
IL_0031: dup
IL_0032: ldc.i4.0
IL_0033: ldc.i4.1
IL_0034: stelem.i1
IL_0035: dup
IL_0036: stloc.3
IL_0037: ldc.i4.1
IL_0038: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_003d: pop
IL_003e: ldloc.3
IL_003f: ldc.i4.0
IL_0040: ldelem.u1
IL_0041: brfalse.s IL_0065
IL_0043: ldloc.1
IL_0044: ldloc.2
IL_0045: ldc.i4.0
IL_0046: ldelem.ref
IL_0047: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_004c: ldtoken "Integer"
IL_0051: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0056: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object"
IL_005b: unbox.any "Integer"
IL_0060: callvirt "Sub Program.cls1.set_p(Integer)"
IL_0065: ldloc.0
IL_0066: callvirt "Function Program.cls1.get_p() As Integer"
IL_006b: call "Sub System.Console.WriteLine(Integer)"
IL_0070: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberInvoke1Readonly()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As New cls1
x.goo(c.p)
Console.WriteLine(c.p)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public ReadOnly Property p() As Integer
Get
Console.WriteLine("Get")
Return _p1
End Get
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
0]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 59 (0x3b)
.maxstack 8
.locals init (Program.cls1 V_0) //c
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: newobj "Sub Program.cls1..ctor()"
IL_000a: stloc.0
IL_000b: ldnull
IL_000c: ldstr "goo"
IL_0011: ldc.i4.1
IL_0012: newarr "Object"
IL_0017: dup
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: callvirt "Function Program.cls1.get_p() As Integer"
IL_001f: box "Integer"
IL_0024: stelem.ref
IL_0025: ldnull
IL_0026: ldnull
IL_0027: ldnull
IL_0028: ldc.i4.1
IL_0029: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_002e: pop
IL_002f: ldloc.0
IL_0030: callvirt "Function Program.cls1.get_p() As Integer"
IL_0035: call "Sub System.Console.WriteLine(Integer)"
IL_003a: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberInvokeLateBound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
x.goo(c.p)
Console.WriteLine(c.p)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p() As Integer
Get
Console.WriteLine("Get")
Return _p1
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Set
Get
1]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 137 (0x89)
.maxstack 13
.locals init (Object V_0, //c
Object V_1,
Object() V_2,
Boolean() V_3)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: newobj "Sub Program.cls1..ctor()"
IL_000a: stloc.0
IL_000b: ldnull
IL_000c: ldstr "goo"
IL_0011: ldc.i4.1
IL_0012: newarr "Object"
IL_0017: dup
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: ldnull
IL_001d: ldstr "p"
IL_0022: ldc.i4.0
IL_0023: newarr "Object"
IL_0028: ldnull
IL_0029: ldnull
IL_002a: ldnull
IL_002b: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0030: stelem.ref
IL_0031: dup
IL_0032: stloc.2
IL_0033: ldnull
IL_0034: ldnull
IL_0035: ldc.i4.1
IL_0036: newarr "Boolean"
IL_003b: dup
IL_003c: ldc.i4.0
IL_003d: ldc.i4.1
IL_003e: stelem.i1
IL_003f: dup
IL_0040: stloc.3
IL_0041: ldc.i4.1
IL_0042: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0047: pop
IL_0048: ldloc.3
IL_0049: ldc.i4.0
IL_004a: ldelem.u1
IL_004b: brfalse.s IL_0069
IL_004d: ldloc.1
IL_004e: ldnull
IL_004f: ldstr "p"
IL_0054: ldc.i4.1
IL_0055: newarr "Object"
IL_005a: dup
IL_005b: ldc.i4.0
IL_005c: ldloc.2
IL_005d: ldc.i4.0
IL_005e: ldelem.ref
IL_005f: stelem.ref
IL_0060: ldnull
IL_0061: ldnull
IL_0062: ldc.i4.1
IL_0063: ldc.i4.0
IL_0064: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(Object, System.Type, String, Object(), String(), System.Type(), Boolean, Boolean)"
IL_0069: ldloc.0
IL_006a: ldnull
IL_006b: ldstr "p"
IL_0070: ldc.i4.0
IL_0071: newarr "Object"
IL_0076: ldnull
IL_0077: ldnull
IL_0078: ldnull
IL_0079: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_007e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0083: call "Sub System.Console.WriteLine(Object)"
IL_0088: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateMemberInvokeLateBoundReadonly()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
x.goo(c.p)
Console.WriteLine(c.p)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public ReadOnly Property p() As Integer
Get
Console.WriteLine("Get")
Return _p1
End Get
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
0]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 137 (0x89)
.maxstack 13
.locals init (Object V_0, //c
Object V_1,
Object() V_2,
Boolean() V_3)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: newobj "Sub Program.cls1..ctor()"
IL_000a: stloc.0
IL_000b: ldnull
IL_000c: ldstr "goo"
IL_0011: ldc.i4.1
IL_0012: newarr "Object"
IL_0017: dup
IL_0018: ldc.i4.0
IL_0019: ldloc.0
IL_001a: stloc.1
IL_001b: ldloc.1
IL_001c: ldnull
IL_001d: ldstr "p"
IL_0022: ldc.i4.0
IL_0023: newarr "Object"
IL_0028: ldnull
IL_0029: ldnull
IL_002a: ldnull
IL_002b: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0030: stelem.ref
IL_0031: dup
IL_0032: stloc.2
IL_0033: ldnull
IL_0034: ldnull
IL_0035: ldc.i4.1
IL_0036: newarr "Boolean"
IL_003b: dup
IL_003c: ldc.i4.0
IL_003d: ldc.i4.1
IL_003e: stelem.i1
IL_003f: dup
IL_0040: stloc.3
IL_0041: ldc.i4.1
IL_0042: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0047: pop
IL_0048: ldloc.3
IL_0049: ldc.i4.0
IL_004a: ldelem.u1
IL_004b: brfalse.s IL_0069
IL_004d: ldloc.1
IL_004e: ldnull
IL_004f: ldstr "p"
IL_0054: ldc.i4.1
IL_0055: newarr "Object"
IL_005a: dup
IL_005b: ldc.i4.0
IL_005c: ldloc.2
IL_005d: ldc.i4.0
IL_005e: ldelem.ref
IL_005f: stelem.ref
IL_0060: ldnull
IL_0061: ldnull
IL_0062: ldc.i4.1
IL_0063: ldc.i4.0
IL_0064: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(Object, System.Type, String, Object(), String(), System.Type(), Boolean, Boolean)"
IL_0069: ldloc.0
IL_006a: ldnull
IL_006b: ldstr "p"
IL_0070: ldc.i4.0
IL_0071: newarr "Object"
IL_0076: ldnull
IL_0077: ldnull
IL_0078: ldnull
IL_0079: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_007e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0083: call "Sub System.Console.WriteLine(Object)"
IL_0088: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateRedim()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New Integer(5) {}
ReDim x(10)
Console.WriteLine(x.Length)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[11]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levels()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
Dim v As Object = 1
x.goo(c.p(v))
Console.WriteLine(c.p(1))
Console.WriteLine(v)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Set
Get
4
1]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levelsByVal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
Dim v As Object = 1
x.goo((c.p(v)))
Console.WriteLine(c.p(1))
Console.WriteLine(v)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
1
1]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levelsCompound()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
Dim v As Object = 1
x.p(c.p(v)) += 1
Console.WriteLine(x.p(1))
Console.WriteLine(c.p(1))
Console.WriteLine(v)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
Set
Get
4
Get
1
1]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levelsCompoundProp()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As New cls1
Dim v As Object = 1
x.p(c.p(v)) += 1
Console.WriteLine(x.p(1))
Console.WriteLine(c.p(1))
Console.WriteLine(v)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
x += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
Set
Get
4
Get
1
1]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levels1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
Dim v As Object = 1
x.goo(c.goo(v))
Console.WriteLine(c.p(1))
Console.WriteLine(v)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer)
Console.WriteLine("goo")
x += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[goo
goo
Get
1
2]]>)
End Sub
<Fact()>
Public Sub LateMemberLateBound2levels2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim x As Object = New cls1
Dim c As Object = New cls1
Dim v As Object = 1
Dim v1 As Object = 5
x.goo(c.p(v), c.p(v))
x.goo(v1, v1)
Console.WriteLine(c.p(1))
Console.WriteLine(v)
Console.WriteLine(v1)
End Sub
Class cls1
Public Sub goo(ByRef x As Integer, ByRef y As Integer)
x += 1
y += 1
End Sub
Private _p1 As Integer
Public Property p(x As Integer) As Integer
Get
Console.WriteLine("Get")
Return _p1 + x
End Get
Set(value As Integer)
Console.WriteLine("Set")
_p1 = value + x
End Set
End Property
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Get
Get
Set
Set
Get
4
1
6]]>)
End Sub
<Fact()>
Public Sub LateMemberArgConvert()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
imports system
Module Program
Sub Main()
Dim obj As Object = New cls1
goo(obj.moo)
End Sub
Sub goo(byref x As Integer)
Console.WriteLine(x)
End Sub
Public Class cls1
Public Function moo() As Integer
Return 42
End Function
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[42]]>)
End Sub
<Fact()>
Public Sub Bug257437Legacy()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Class Bug257437
Shared Result As Integer
Shared Sub goo(ByVal i As Integer, ByVal b As Byte)
Result = 1
End Sub
Shared Sub goo(ByVal i As Integer, ByVal b As Int16)
Result = 2
End Sub
Shared Sub goo(ByVal i As Integer, ByVal b As Int32)
Result = 3
End Sub
Shared Sub goo(ByVal i As Integer, ByVal b As String, Optional ByVal x As Integer = 1)
Result = 4
End Sub
Shared Sub Main()
Console.WriteLine("*** Bug 257437")
Try
Dim fnum
Console.Write(" 1) ")
goo(fnum, CByte(255))
PassFail(Result = 1)
Console.Write(" 2) ")
goo(fnum, -1S)
PassFail(Result = 2)
Console.Write(" 3) ")
goo(fnum, -1I)
PassFail(Result = 3)
Console.Write(" 4) ")
goo(fnum, "abc")
PassFail(Result = 4)
Catch ex As Exception
Failed(ex)
End Try
End Sub
End Class
Module TestHarness
Sub Failed(ByVal ex As Exception)
If ex Is Nothing Then
Console.WriteLine("NULL System.Exception")
Else
Console.WriteLine(ex.GetType().FullName)
End If
Console.WriteLine(ex.Message)
Console.WriteLine(ex.StackTrace)
Console.WriteLine("FAILED !!!")
End Sub
Sub Failed()
Console.WriteLine("FAILED !!!")
End Sub
Sub Passed()
Console.WriteLine("passed")
End Sub
Sub PassFail(ByVal bPassed As Boolean)
If bPassed Then
Console.WriteLine("passed")
Else
Console.WriteLine("FAILED !!!")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[*** Bug 257437
1) passed
2) passed
3) passed
4) passed]]>)
End Sub
<Fact()>
Public Sub Bug168135Legacy()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Bug168135
'This tests setting/getting of array fields
Sub Main()
Dim bFailed As Boolean
Console.WriteLine("Regression test Bug168135")
Try
Dim o As Object = New Class1()
If o.Ary(0) <> 6 Then
Console.WriteLine("Bug168135: FAILED step 1a")
bFailed = True
End If
o.Ary(4) = 11 'this is causing an unexpected MissingMethodException
If o.Ary(4) <> 11 Then
Console.WriteLine("Bug168135: FAILED step 1b")
bFailed = True
End If
Catch ex As Exception
Console.WriteLine(ex.GetType().Name & ": " & ex.Message)
Console.WriteLine("Bug168135: FAILED step 1c")
bFailed = True
End Try
Try
Dim o As Object = New Class1()
If o.ObjectValue(0) <> 1 Then
Console.WriteLine("Bug168135: FAILED step 2a")
bFailed = True
End If
o.ObjectValue(4) = 6 'this is causing an unexpected MissingMethodException
If o.ObjectValue(4) <> 6 Then
Console.WriteLine("Bug168135: FAILED step 2b")
bFailed = True
End If
Catch ex As Exception
Failed(ex)
Console.WriteLine("Bug168135: FAILED step 2c")
bFailed = True
End Try
Try
Dim o As Object = New Class1()
If o(0) <> "A" Then
Console.WriteLine("Bug168135: FAILED step 3a")
bFailed = True
End If
o(4) = "X" 'this is causing an unexpected MissingMethodException
If o(4) <> "X" Then
Console.WriteLine("Bug168135: FAILED step 3b")
bFailed = True
End If
Catch ex As Exception
Failed(ex)
Console.WriteLine("Bug168135: FAILED step 3c")
bFailed = True
End Try
If Not bFailed Then
Console.WriteLine("Bug168135: PASSED")
End If
End Sub
End Module
Public Class Class1
Private m_default() As String
Private Shared PrivateSharedValue As Integer = 12
Protected Shared ProtectedSharedValue As Integer = 23
Public Shared PublicSharedValue As Integer = 12345
Sub New()
ObjectValue = New Integer() {1, 2, 3, 4, 5}
m_default = New String() {"A", "B", "C", "D", "E"}
Ary = New Integer() {6, 7, 8, 9, 10}
End Sub
Public Ary(4) As Integer
Public ObjectValue As Object
Public ShortValue As Short
Public IntegerValue As Integer
Public LongValue As Long
Public SingleValue As Single
Public DoubleValue As Double
Public DateValue As Date
Public DecimalValue As Decimal
Public StringValue As String
Private PrivateValue As String
Protected Property ProtectedProp() As Integer
Get
Return 12345
End Get
Set(ByVal Value As Integer)
If Value <> 12345 Then
Throw New ArgumentException("Argument was not correct")
End If
End Set
End Property
Default Public Property DefaultProp(ByVal Index As Integer) As String
Get
Return m_default(Index)
End Get
Set(ByVal Value As String)
m_default(Index) = Value
End Set
End Property
Friend Declare Ansi Function AnsiStrFunction Lib "DeclExtNightly001.DLL" Alias "StrFunction" (ByVal Arg As String, ByVal Arg1 As Integer, ByVal Arg2 As Integer, ByVal Arg3 As Boolean) As Boolean
Public Declare Sub MsgBeep Lib "user32.DLL" Alias "MessageBeep" (Optional ByVal x As Integer = 0)
End Class
Module TestHarness
Sub Failed(ByVal ex As Exception)
If ex Is Nothing Then
Console.WriteLine("NULL System.Exception")
Else
Console.WriteLine(ex.GetType().FullName)
End If
Console.WriteLine(ex.Message)
Console.WriteLine(ex.StackTrace)
Console.WriteLine("FAILED !!!")
End Sub
Sub Failed()
Console.WriteLine("FAILED !!!")
End Sub
Sub Passed()
Console.WriteLine("passed")
End Sub
Sub PassFail(ByVal bPassed As Boolean)
If bPassed Then
Console.WriteLine("passed")
Else
Console.WriteLine("FAILED !!!")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Regression test Bug168135
Bug168135: PASSED]]>)
End Sub
<Fact()>
Public Sub Bug302246Legacy()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Bug302246
Private m_i As Integer
Private m_ArgInteger As Integer
Private m_Arg2 As Integer
Private m_ArgString As Integer
Public Class Class1
Public Sub goo(ByVal Arg As Integer, ByVal Arg2 As Integer) ', Optional ByVal Arg2 As Long = 40)
m_i = 1
m_ArgInteger = Arg
m_Arg2 = Arg2
End Sub
Public Sub Goo(ByVal Arg2 As Integer, ByVal Arg As String)
m_i = 2
m_ArgString = Arg
m_Arg2 = Arg2
End Sub
End Class
Sub Main()
Console.Write("Bug 302246: ")
Try
Dim iEarly As Integer
Dim c As New Class1()
Dim o As Object = c
m_i = -1
c.goo(40, Arg:=50)
iEarly = m_i
m_i = -1
o.goo(40, Arg:=50) 'this late bound case throws an unexpected exception - BUG
PassFail(m_i = iEarly AndAlso m_ArgString = "50" AndAlso m_Arg2 = 40)
Catch ex As Exception
Failed(ex)
End Try
End Sub
End Module
Module TestHarness
Sub Failed(ByVal ex As Exception)
If ex Is Nothing Then
Console.WriteLine("NULL System.Exception")
Else
Console.WriteLine(ex.GetType().FullName)
End If
Console.WriteLine(ex.Message)
Console.WriteLine(ex.StackTrace)
Console.WriteLine("FAILED !!!")
End Sub
Sub Failed()
Console.WriteLine("FAILED !!!")
End Sub
Sub Passed()
Console.WriteLine("passed")
End Sub
Sub PassFail(ByVal bPassed As Boolean)
If bPassed Then
Console.WriteLine("passed")
Else
Console.WriteLine("FAILED !!!")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Bug 302246: passed]]>)
End Sub
<Fact()>
Public Sub Bug231364Legacy()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Bug231364
Delegate Sub goo(ByRef x As Short, ByRef y As Long)
Sub goo1(ByRef x As Short, Optional ByRef y As Long = 0)
y = 8 / 2
End Sub
Sub Main()
Console.Write("Bug 231364: ")
Try
Dim var As Object
var = New goo(AddressOf goo1)
var2 = 8
var3 = 10
var.Invoke(var3, y:=var2)
PassFail(var2 = 4)
Catch ex As Exception
Failed(ex)
End Try
End Sub
Private _value2 As Long
Private Property var2 As Long
Get
Console.WriteLine("GetVar2")
Return _value2
End Get
Set(value As Long)
Console.WriteLine("SetVar2")
_value2 = value
End Set
End Property
Private _value3 As Long
Private Property var3 As Long
Get
Console.WriteLine("GetVar3")
Return _value3
End Get
Set(value As Long)
Console.WriteLine("SetVar3")
_value3 = value
End Set
End Property
End Module
Module TestHarness
Sub Failed(ByVal ex As Exception)
If ex Is Nothing Then
Console.WriteLine("NULL System.Exception")
Else
Console.WriteLine(ex.GetType().FullName)
End If
Console.WriteLine(ex.Message)
Console.WriteLine(ex.StackTrace)
Console.WriteLine("FAILED !!!")
End Sub
Sub Failed()
Console.WriteLine("FAILED !!!")
End Sub
Sub Passed()
Console.WriteLine("passed")
End Sub
Sub PassFail(ByVal bPassed As Boolean)
If bPassed Then
Console.WriteLine("passed")
Else
Console.WriteLine("FAILED !!!")
End If
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Bug 231364: SetVar2
SetVar3
GetVar3
GetVar2
SetVar3
SetVar2
GetVar2
passed]]>)
End Sub
<Fact()>
Public Sub OverflowInCopyback()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program1
Delegate Sub goo(ByRef x As Short, ByRef y As Long)
Sub goo1(ByRef x As Short, Optional ByRef y As Long = 0)
y = 8 / 2
x = -1
End Sub
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Dim var As Object
var = New goo(AddressOf goo1)
Dim var2 = 8
Dim var3 As ULong = 10
var.Invoke(var3, y:=var2)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Arithmetic operation resulted in an overflow.]]>)
End Sub
<Fact()>
Public Sub LateCallMissing()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
obj.goo(, y:=obj.goo(, ))
End Sub
Class cls1
Shared Sub goo(Optional x As Integer = 1, Optional y As Integer = 2)
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[3
1]]>).
VerifyIL("Program.Main",
<![CDATA[
{
// Code size 161 (0xa1)
.maxstack 13
.locals init (Object V_0, //obj
Object V_1,
Object V_2,
Object V_3,
Object() V_4,
Boolean() V_5,
Object() V_6)
IL_0000: newobj "Sub Program.cls1..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldnull
IL_0008: ldstr "goo"
IL_000d: ldc.i4.2
IL_000e: newarr "Object"
IL_0013: stloc.s V_6
IL_0015: ldloc.s V_6
IL_0017: ldc.i4.1
IL_0018: ldsfld "System.Reflection.Missing.Value As System.Reflection.Missing"
IL_001d: stelem.ref
IL_001e: ldloc.s V_6
IL_0020: ldc.i4.0
IL_0021: ldloc.0
IL_0022: stloc.1
IL_0023: ldloc.1
IL_0024: ldnull
IL_0025: ldstr "goo"
IL_002a: ldc.i4.2
IL_002b: newarr "Object"
IL_0030: dup
IL_0031: ldc.i4.0
IL_0032: ldsfld "System.Reflection.Missing.Value As System.Reflection.Missing"
IL_0037: dup
IL_0038: stloc.2
IL_0039: stelem.ref
IL_003a: dup
IL_003b: ldc.i4.1
IL_003c: ldsfld "System.Reflection.Missing.Value As System.Reflection.Missing"
IL_0041: dup
IL_0042: stloc.3
IL_0043: stelem.ref
IL_0044: ldnull
IL_0045: ldnull
IL_0046: ldnull
IL_0047: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_004c: stelem.ref
IL_004d: ldloc.s V_6
IL_004f: dup
IL_0050: stloc.s V_4
IL_0052: ldc.i4.1
IL_0053: newarr "String"
IL_0058: dup
IL_0059: ldc.i4.0
IL_005a: ldstr "y"
IL_005f: stelem.ref
IL_0060: ldnull
IL_0061: ldc.i4.2
IL_0062: newarr "Boolean"
IL_0067: dup
IL_0068: ldc.i4.0
IL_0069: ldc.i4.1
IL_006a: stelem.i1
IL_006b: dup
IL_006c: stloc.s V_5
IL_006e: ldc.i4.1
IL_006f: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0074: pop
IL_0075: ldloc.s V_5
IL_0077: ldc.i4.0
IL_0078: ldelem.u1
IL_0079: brfalse.s IL_00a0
IL_007b: ldloc.1
IL_007c: ldnull
IL_007d: ldstr "goo"
IL_0082: ldc.i4.3
IL_0083: newarr "Object"
IL_0088: dup
IL_0089: ldc.i4.0
IL_008a: ldloc.2
IL_008b: stelem.ref
IL_008c: dup
IL_008d: ldc.i4.1
IL_008e: ldloc.3
IL_008f: stelem.ref
IL_0090: dup
IL_0091: ldc.i4.2
IL_0092: ldloc.s V_4
IL_0094: ldc.i4.0
IL_0095: ldelem.ref
IL_0096: stelem.ref
IL_0097: ldnull
IL_0098: ldnull
IL_0099: ldc.i4.1
IL_009a: ldc.i4.0
IL_009b: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(Object, System.Type, String, Object(), String(), System.Type(), Boolean, Boolean)"
IL_00a0: ret
}
]]>)
End Sub
<Fact>
Public Sub LateAddressOfTrueClosure()
Dim source =
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Class C
Dim _id As Integer
Sub New(id As Integer)
_id = id
End Sub
Function G(x As C) As C
Console.WriteLine(x._id)
Return x
End Function
Sub goo(x As Integer, y As Integer)
End Sub
End Class
Module Program
Sub Main()
Dim obj0 As Object = New C(1)
Dim obj1 As Object = New C(2)
Dim o As Action(Of Byte, Integer) = AddressOf obj0.G(obj1).goo
obj1 = New C(5)
o(1, 2)
End Sub
End Module
</file>
</compilation>
Dim c = CompileAndVerify(source, expectedOutput:="5", options:=TestOptions.DebugExe.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator:=
Sub(m)
Dim closure = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program._Closure$__0-0")
AssertEx.Equal(
{
"Public $VB$Local_obj0 As Object",
"Public $VB$Local_obj1 As Object",
"Public Sub New()",
"Friend Sub _Lambda$__0(a0 As Byte, a1 As Integer)"
}, closure.GetMembers().Select(Function(x) x.ToString()))
End Sub)
End Sub
<Fact()>
Public Sub LateAddressOf()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Sub Main()
Dim obj As Object = New cls1
Dim o As Action(Of Integer, Integer) = AddressOf obj.goo
o(1, 2)
End Sub
Class cls1
Shared Sub goo(x As Integer, y As Integer)
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>,
expectedOutput:="3")
c.VerifyIL("Program._Closure$__0-0._Lambda$__0",
<![CDATA[
{
// Code size 134 (0x86)
.maxstack 10
.locals init (Object() V_0,
Boolean() V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Program._Closure$__0-0.$VB$Local_obj As Object"
IL_0006: ldnull
IL_0007: ldstr "goo"
IL_000c: ldc.i4.2
IL_000d: newarr "Object"
IL_0012: dup
IL_0013: ldc.i4.0
IL_0014: ldarg.1
IL_0015: box "Integer"
IL_001a: stelem.ref
IL_001b: dup
IL_001c: ldc.i4.1
IL_001d: ldarg.2
IL_001e: box "Integer"
IL_0023: stelem.ref
IL_0024: dup
IL_0025: stloc.0
IL_0026: ldnull
IL_0027: ldnull
IL_0028: ldc.i4.2
IL_0029: newarr "Boolean"
IL_002e: dup
IL_002f: ldc.i4.0
IL_0030: ldc.i4.1
IL_0031: stelem.i1
IL_0032: dup
IL_0033: ldc.i4.1
IL_0034: ldc.i4.1
IL_0035: stelem.i1
IL_0036: dup
IL_0037: stloc.1
IL_0038: ldc.i4.1
IL_0039: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_003e: pop
IL_003f: ldloc.1
IL_0040: ldc.i4.0
IL_0041: ldelem.u1
IL_0042: brfalse.s IL_0062
IL_0044: ldloc.0
IL_0045: ldc.i4.0
IL_0046: ldelem.ref
IL_0047: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_004c: ldtoken "Integer"
IL_0051: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0056: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object"
IL_005b: unbox.any "Integer"
IL_0060: starg.s V_1
IL_0062: ldloc.1
IL_0063: ldc.i4.1
IL_0064: ldelem.u1
IL_0065: brfalse.s IL_0085
IL_0067: ldloc.0
IL_0068: ldc.i4.1
IL_0069: ldelem.ref
IL_006a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_006f: ldtoken "Integer"
IL_0074: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0079: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object"
IL_007e: unbox.any "Integer"
IL_0083: starg.s V_2
IL_0085: ret
}
]]>)
End Sub
<Fact()>
Public Sub LateAddressOfRef()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Program
Delegate Sub d1(ByRef x As Integer, y As Integer)
Sub Main()
Dim obj As Object = New cls1
Dim o As d1 = AddressOf obj.goo
Dim l As Integer = 0
o(l, 2)
Console.WriteLine(l)
End Sub
Class cls1
Shared Sub goo(ByRef x As Integer, y As Integer)
x = 42
Console.WriteLine(x + y)
End Sub
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[44
42]]>)
End Sub
<Fact()>
Public Sub Regress14733()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim obj As Object = New C3()
Try
obj.x()
Catch e As MissingMemberException
End Try
End Sub
End Module
Class C1
Overridable Sub x()
Console.WriteLine("True")
End Sub
End Class
Class C2
Inherits C1
Overridable Shadows Sub x(ByVal i As Integer)
End Sub
End Class
Class C3
Inherits C2
Overrides Sub x(ByVal i As Integer)
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[True]]>)
End Sub
<Fact()>
Public Sub Regress14991()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Class C1
Shared Widening Operator CType(ByVal arg As Integer) As C1
Return New C1
End Operator
Shared Widening Operator CType(ByVal arg As C1) As Integer
Return 0
End Operator
End Class
Dim c1Obj As New C1
Class C2
Sub goo(Of T)(ByRef x As T)
x = Nothing
End Sub
End Class
Sub Main()
Dim c2Obj As New C2
Dim obj As Object = c2Obj
obj.goo(Of Integer)(c1Obj)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[]]>).
VerifyIL("Module1.Main",
<![CDATA[
{
// Code size 105 (0x69)
.maxstack 10
.locals init (Object() V_0,
Boolean() V_1)
IL_0000: newobj "Sub Module1.C2..ctor()"
IL_0005: ldnull
IL_0006: ldstr "goo"
IL_000b: ldc.i4.1
IL_000c: newarr "Object"
IL_0011: dup
IL_0012: ldc.i4.0
IL_0013: ldsfld "Module1.c1Obj As Module1.C1"
IL_0018: stelem.ref
IL_0019: dup
IL_001a: stloc.0
IL_001b: ldnull
IL_001c: ldc.i4.1
IL_001d: newarr "System.Type"
IL_0022: dup
IL_0023: ldc.i4.0
IL_0024: ldtoken "Integer"
IL_0029: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_002e: stelem.ref
IL_002f: ldc.i4.1
IL_0030: newarr "Boolean"
IL_0035: dup
IL_0036: ldc.i4.0
IL_0037: ldc.i4.1
IL_0038: stelem.i1
IL_0039: dup
IL_003a: stloc.1
IL_003b: ldc.i4.1
IL_003c: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0041: pop
IL_0042: ldloc.1
IL_0043: ldc.i4.0
IL_0044: ldelem.u1
IL_0045: brfalse.s IL_0068
IL_0047: ldloc.0
IL_0048: ldc.i4.0
IL_0049: ldelem.ref
IL_004a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_004f: ldtoken "Module1.C1"
IL_0054: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0059: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object"
IL_005e: castclass "Module1.C1"
IL_0063: stsfld "Module1.c1Obj As Module1.C1"
IL_0068: ret
}
]]>)
End Sub
<Fact()>
Public Sub Regress15196()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
imports system
Module Test
Sub Main()
Dim a = New class1
Dim O As Object = 5S
a.Bb(O)
End Sub
Friend Class class1
Public Overridable Sub Bb(ByRef y As String)
Console.WriteLine("string")
End Sub
Public Overridable Sub BB(ByRef y As Short)
Console.WriteLine("short")
End Sub
End Class
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[short]]>)
End Sub
<WorkItem(546467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546467")>
<Fact()>
Public Sub Bug15939_1()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
I0.GoHome()
I1.GoHome()
I2.GoHome()
I3.GoHome()
End Sub
<InterfaceType(CType(3, ComInterfaceType))>
Interface II0
End Interface
Property I0 As II0
<InterfaceType(ComInterfaceType.InterfaceIsDual)>
Interface II1
End Interface
Property I1 As II1
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Interface II2
End Interface
Property I2 As II2
<InterfaceType(ComInterfaceType.InterfaceIsIDispatch)>
Interface II3
End Interface
Property I3 As II3
End Module
</file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "I1.GoHome").WithArguments("GoHome", "Module1.II1"),
Diagnostic(ERRID.ERR_NameNotMember2, "I2.GoHome").WithArguments("GoHome", "Module1.II2"))
End Sub
<WorkItem(546467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546467")>
<Fact()>
Public Sub Bug15939_2()
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
I0.GoHome()
I1.GoHome()
I2.GoHome()
I3.GoHome()
I4.GoHome()
End Sub
<TypeLibType(100000)>
Interface II0
End Interface
Property I0 As II0
<TypeLibType(1000000)>
Interface II1
End Interface
Property I1 As II1
<TypeLibType(0)>
Interface II2
End Interface
Property I2 As II2
<TypeLibType(TypeLibTypeFlags.FCanCreate)>
Interface II3
End Interface
Property I3 As II3
<TypeLibType(TypeLibTypeFlags.FCanCreate Or TypeLibTypeFlags.FNonExtensible)>
Interface II4
End Interface
Property I4 As II4
End Module
</file>
</compilation>).VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "I0.GoHome").WithArguments("GoHome", "Module1.II0"),
Diagnostic(ERRID.ERR_NameNotMember2, "I4.GoHome").WithArguments("GoHome", "Module1.II4"))
End Sub
<Fact()>
Public Sub Regress14722()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
imports system
imports Microsoft.VisualBasic
Friend Module Module1
Sub Main()
Dim Res
Dim clt As Collection = New Collection()
clt.Add("Roslyn", "RsKey")
Dim embclt As Collection = New Collection()
embclt.Add(clt, "MyKey")
'Try a Get
Res = embclt!MyKey!RsKey
Console.WriteLine(Res)
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[Roslyn]]>)
End Sub
<Fact()>
Public Sub Regress17205()
CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Imports System
Module Module1
Sub Main()
Dim x = New C
Dim x1 = New C(123)
End Sub
End Module
Class C
Sub New()
Me.New(Goo(CObj(42)))
End Sub
Sub New(a As Integer)
Me.New(Sub(x) Goo(x))
End Sub
Sub New(x As Action(Of Object))
x(777)
End Sub
Sub New(x As Object)
End Sub
Sub Goo(x As String)
End Sub
Shared Sub Goo(x As Integer)
Console.WriteLine(x)
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[42
777]]>)
End Sub
<Fact(), WorkItem(531546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531546")>
Public Sub Bug18273()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class VBIDO
Public Property Item2(Optional ByVal p1 As String = "", Optional ByVal p2 As Integer = 0) As Long
Get
Return 0
End Get
Set(ByVal value As Long)
System.Console.WriteLine(p1)
System.Console.WriteLine(p2)
System.Console.WriteLine(value)
End Set
End Property
End Class
Module Program
Sub Main()
Dim o As Object = New VBIDO
o.Item2("hello", p2:="1") = 2
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
hello
1
2
]]>)
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 63 (0x3f)
.maxstack 8
IL_0000: newobj "Sub VBIDO..ctor()"
IL_0005: ldnull
IL_0006: ldstr "Item2"
IL_000b: ldc.i4.3
IL_000c: newarr "Object"
IL_0011: dup
IL_0012: ldc.i4.1
IL_0013: ldstr "hello"
IL_0018: stelem.ref
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldstr "1"
IL_0020: stelem.ref
IL_0021: dup
IL_0022: ldc.i4.2
IL_0023: ldc.i4.2
IL_0024: box "Integer"
IL_0029: stelem.ref
IL_002a: ldc.i4.1
IL_002b: newarr "String"
IL_0030: dup
IL_0031: ldc.i4.0
IL_0032: ldstr "p2"
IL_0037: stelem.ref
IL_0038: ldnull
IL_0039: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Object, System.Type, String, Object(), String(), System.Type())"
IL_003e: ret
}
]]>)
End Sub
<Fact(), WorkItem(531546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531546")>
Public Sub Bug18273_2()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class VBIDO
Public Sub Item2(Optional ByVal p1 As String = "", Optional ByVal p2 As Integer = 0)
System.Console.WriteLine(p1)
System.Console.WriteLine(p2)
End Sub
End Class
Module Program
Sub Main()
Dim o As Object = New VBIDO
o.Item2("hello", p2:="1")
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
hello
1
]]>)
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 57 (0x39)
.maxstack 8
IL_0000: newobj "Sub VBIDO..ctor()"
IL_0005: ldnull
IL_0006: ldstr "Item2"
IL_000b: ldc.i4.2
IL_000c: newarr "Object"
IL_0011: dup
IL_0012: ldc.i4.1
IL_0013: ldstr "hello"
IL_0018: stelem.ref
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldstr "1"
IL_0020: stelem.ref
IL_0021: ldc.i4.1
IL_0022: newarr "String"
IL_0027: dup
IL_0028: ldc.i4.0
IL_0029: ldstr "p2"
IL_002e: stelem.ref
IL_002f: ldnull
IL_0030: ldnull
IL_0031: ldc.i4.1
IL_0032: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_0037: pop
IL_0038: ret
}
]]>)
End Sub
<Fact(), WorkItem(531546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531546")>
Public Sub Bug18273_3()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class VBIDO
Public Function Item2(Optional ByVal p1 As String = "", Optional ByVal p2 As Integer = 0) As Integer
System.Console.WriteLine(p1)
System.Console.WriteLine(p2)
Return 2
End Function
End Class
Module Program
Sub Main()
Dim o As Object = New VBIDO
System.Console.WriteLine(o.Item2("hello", p2:="1"))
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
hello
1
2
]]>)
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 65 (0x41)
.maxstack 8
IL_0000: newobj "Sub VBIDO..ctor()"
IL_0005: ldnull
IL_0006: ldstr "Item2"
IL_000b: ldc.i4.2
IL_000c: newarr "Object"
IL_0011: dup
IL_0012: ldc.i4.1
IL_0013: ldstr "hello"
IL_0018: stelem.ref
IL_0019: dup
IL_001a: ldc.i4.0
IL_001b: ldstr "1"
IL_0020: stelem.ref
IL_0021: ldc.i4.1
IL_0022: newarr "String"
IL_0027: dup
IL_0028: ldc.i4.0
IL_0029: ldstr "p2"
IL_002e: stelem.ref
IL_002f: ldnull
IL_0030: ldnull
IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0036: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_003b: call "Sub System.Console.WriteLine(Object)"
IL_0040: ret
}
]]>)
End Sub
<Fact(), WorkItem(531546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531546")>
Public Sub Bug18273_4()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class VBIDO
Public Default Property Item2(ByVal p1 As String, ByVal p2 As Integer) As Long
Get
Return 0
End Get
Set(ByVal value As Long)
System.Console.WriteLine(p1)
System.Console.WriteLine(p2)
System.Console.WriteLine(value)
End Set
End Property
End Class
Module Program
Sub Main()
Dim o As Object = New VBIDO
o("hello", p2:="1") = 2
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
hello
1
2
]]>)
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 56 (0x38)
.maxstack 6
IL_0000: newobj "Sub VBIDO..ctor()"
IL_0005: ldc.i4.3
IL_0006: newarr "Object"
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldstr "hello"
IL_0012: stelem.ref
IL_0013: dup
IL_0014: ldc.i4.0
IL_0015: ldstr "1"
IL_001a: stelem.ref
IL_001b: dup
IL_001c: ldc.i4.2
IL_001d: ldc.i4.2
IL_001e: box "Integer"
IL_0023: stelem.ref
IL_0024: ldc.i4.1
IL_0025: newarr "String"
IL_002a: dup
IL_002b: ldc.i4.0
IL_002c: ldstr "p2"
IL_0031: stelem.ref
IL_0032: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexSet(Object, Object(), String())"
IL_0037: ret
}
]]>)
End Sub
<Fact(), WorkItem(531546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531546")>
Public Sub Bug18273_5()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Public Class VBIDO
Public Default Property Item2(ByVal p1 As String, ByVal p2 As Integer) As Long
Get
System.Console.WriteLine(p1)
System.Console.WriteLine(p2)
Return 2
End Get
Set(ByVal value As Long)
End Set
End Property
End Class
Module Program
Sub Main()
Dim o As Object = New VBIDO
System.Console.WriteLine(o("hello", p2:="1"))
End Sub
End Module
</file>
</compilation>, expectedOutput:=
<![CDATA[
hello
1
2
]]>)
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 57 (0x39)
.maxstack 6
IL_0000: newobj "Sub VBIDO..ctor()"
IL_0005: ldc.i4.2
IL_0006: newarr "Object"
IL_000b: dup
IL_000c: ldc.i4.1
IL_000d: ldstr "hello"
IL_0012: stelem.ref
IL_0013: dup
IL_0014: ldc.i4.0
IL_0015: ldstr "1"
IL_001a: stelem.ref
IL_001b: ldc.i4.1
IL_001c: newarr "String"
IL_0021: dup
IL_0022: ldc.i4.0
IL_0023: ldstr "p2"
IL_0028: stelem.ref
IL_0029: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateIndexGet(Object, Object(), String()) As Object"
IL_002e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0033: call "Sub System.Console.WriteLine(Object)"
IL_0038: ret
}
]]>)
End Sub
<Fact(), WorkItem(531547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531547")>
Public Sub Bug18274()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Module Program
Sub Main()
Dim o As Object = Nothing
Dim x = New With {.a = ""}
o.Func(o.Func(x.a))
End Sub
End Module
</file>
</compilation>)
End Sub
<Fact(), WorkItem(531547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531547")>
Public Sub Bug18274_1()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict Off
Module Module1
Sub Main()
System.Console.WriteLine("-----1")
Case1()
System.Console.WriteLine("-----2")
Case2()
System.Console.WriteLine("-----3")
Case3()
System.Console.WriteLine("-----4")
Case4()
System.Console.WriteLine("-----5")
Case5()
System.Console.WriteLine("-----6")
Case6()
System.Console.WriteLine("-----7")
Case7()
System.Console.WriteLine("-----8")
Case8()
System.Console.WriteLine("-----9")
Case9()
System.Console.WriteLine("-----10")
Case10()
System.Console.WriteLine("-----11")
Case11()
System.Console.WriteLine("-----12")
Case12()
System.Console.WriteLine("-----13")
Case13()
System.Console.WriteLine("-----14")
Case14()
System.Console.WriteLine("-----15")
Case15()
System.Console.WriteLine("-----16")
Case16()
System.Console.WriteLine("-----17")
Case17()
System.Console.WriteLine("-----18")
Case18()
System.Console.WriteLine("-----19")
Case19()
System.Console.WriteLine("-----20")
Case20()
System.Console.WriteLine("-----21")
Case21()
System.Console.WriteLine("-----22")
Case22()
System.Console.WriteLine("-----23")
Case23()
System.Console.WriteLine("-----24")
Case24()
System.Console.WriteLine("-----25")
Case25()
System.Console.WriteLine("-----26")
Case26()
System.Console.WriteLine("-----27")
Case27()
System.Console.WriteLine("-----28")
Case28()
'System.Console.WriteLine()
'System.Console.WriteLine()
'System.Console.WriteLine()
'System.Console.WriteLine()
'Dim caseN As Integer = 7
'Dim members = {"M1", "P1"}
'For i As Integer = 0 To 1
' For j As Integer = 0 To 1
' For k As Integer = 0 To 1
' For l As Integer = 0 To 1
' 'System.Console.WriteLine(" System.Console.WriteLine(""-----{0}"")", caseN)
' 'System.Console.WriteLine(" Case{0}()", caseN)
' System.Console.WriteLine(" Sub Case{0}()", caseN)
' System.Console.WriteLine("#If EarlyBound")
' System.Console.WriteLine(" Dim t1 As New Test1()")
' System.Console.WriteLine("#Else")
' System.Console.WriteLine(" Dim t1 As Object = New Test1()")
' System.Console.WriteLine("#EndIf")
' System.Console.WriteLine(" Dim x = t1.{0}(t1.{1}(t1.{2}(t1.{3}(0))))", members(i), members(j), members(k), members(l))
' System.Console.WriteLine(" End Sub")
' System.Console.WriteLine()
' caseN += 1
' Next
' Next
' Next
'Next
End Sub
Sub Case0()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(0))
End Sub
Sub Case1()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(0))
End Sub
Sub Case2()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1((t1.P1(0)))
End Sub
Sub Case3()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.P1(0)))
End Sub
Sub Case4()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(t1.P1(0)))
End Sub
Sub Case5()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.M1(0)))
End Sub
Sub Case6()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(t1.M1(0)))
End Sub
Sub Case7()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.M1(t1.M1(0))))
End Sub
Sub Case8()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.M1(t1.P1(0))))
End Sub
Sub Case9()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.P1(t1.M1(0))))
End Sub
Sub Case10()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.P1(t1.P1(0))))
End Sub
Sub Case11()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(t1.M1(t1.M1(0))))
End Sub
Sub Case12()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(t1.M1(t1.P1(0))))
End Sub
Sub Case13()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(t1.P1(t1.M1(0))))
End Sub
Sub Case14()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.P1(t1.P1(t1.P1(0))))
End Sub
Sub Case15()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(t1.M1(t1.M1(0))))
End Sub
Sub Case16()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(t1.M1(t1.P1(0))))
End Sub
Sub Case17()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(t1.P1(t1.M1(0))))
End Sub
Sub Case18()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.M1(t1.P1(t1.P1(0))))
End Sub
Sub Case19()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.P1(t1.M1(t1.M1(0))))
End Sub
Sub Case20()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.P1(t1.M1(t1.P1(0))))
End Sub
Sub Case21()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.P1(t1.P1(t1.M1(0))))
End Sub
Sub Case22()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.P1(t1.P1(t1.P1(t1.P1(0))))
End Sub
Sub Case23()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1(t1.M1((t1.P1(0)))))
End Sub
Sub Case24()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1(t1.M1((t1.P1(t1.M1(0)))))
End Sub
Sub Case25()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
Dim x = t1.M1((t1.P1(t1.M1(t1.M1(0)))))
End Sub
Sub Case26()
Dim t1 As New Test1()
Dim t2 As Object = New Test1()
Dim x = t1.M1(t2.P1(0))
End Sub
Sub Case27()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
ReDim t1.P2(t1.P1(0))(2)
End Sub
Sub Case28()
#If EarlyBound Then
Dim t1 As New Test1()
#Else
Dim t1 As Object = New Test1()
#End If
ReDim Preserve t1.P2(t1.P1(1))(3)
End Sub
End Module
Class Test1
Private _m1 As Integer = 200
Public Function M1(ByRef x As Integer) As Integer
_m1 += 1
System.Console.WriteLine("M1 {0} ({1})", _m1, x)
Return _m1
End Function
Private _p1 As Integer = 300
Public Property P1(x As Integer) As Integer
Get
_p1 += 1
System.Console.WriteLine("get_P1 {0} ({1})", _p1, x)
Return _p1
End Get
Set(value As Integer)
_p1 += 1
System.Console.WriteLine("set_P1 {0} ({1}) = {2}", _p1, x, value)
End Set
End Property
Private _p2 As Integer = 400
Public Property P2(x As Integer) As Object()
Get
_p2 += 1
System.Console.WriteLine("get_P2 {0} ({1})", _p2, x)
Return {_p2}
End Get
Set(value As Object())
_p2 += 1
System.Console.WriteLine("set_P2 {0} ({1}) = {2} {3}", _p2, x, value.Length, If(value(0),"null"))
End Set
End Property
End Class
</file>
</compilation>, expectedOutput:=
<![CDATA[
-----1
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
-----2
get_P1 301 (0)
M1 201 (301)
-----3
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
M1 202 (201)
-----4
get_P1 301 (0)
get_P1 302 (301)
M1 201 (302)
set_P1 303 (301) = 302
-----5
M1 201 (0)
M1 202 (201)
M1 203 (202)
-----6
M1 201 (0)
M1 202 (201)
get_P1 301 (202)
-----7
M1 201 (0)
M1 202 (201)
M1 203 (202)
M1 204 (203)
-----8
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
M1 202 (201)
M1 203 (202)
-----9
M1 201 (0)
get_P1 301 (201)
M1 202 (301)
set_P1 302 (201) = 301
M1 203 (202)
-----10
get_P1 301 (0)
get_P1 302 (301)
M1 201 (302)
set_P1 303 (301) = 302
M1 202 (201)
-----11
M1 201 (0)
M1 202 (201)
get_P1 301 (202)
M1 203 (301)
set_P1 302 (202) = 301
-----12
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
get_P1 303 (201)
M1 202 (303)
set_P1 304 (201) = 303
-----13
M1 201 (0)
get_P1 301 (201)
get_P1 302 (301)
M1 202 (302)
set_P1 303 (301) = 302
-----14
get_P1 301 (0)
get_P1 302 (301)
get_P1 303 (302)
M1 201 (303)
set_P1 304 (302) = 303
-----15
M1 201 (0)
M1 202 (201)
M1 203 (202)
get_P1 301 (203)
-----16
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
M1 202 (201)
get_P1 303 (202)
-----17
M1 201 (0)
get_P1 301 (201)
M1 202 (301)
set_P1 302 (201) = 301
get_P1 303 (202)
-----18
get_P1 301 (0)
get_P1 302 (301)
M1 201 (302)
set_P1 303 (301) = 302
get_P1 304 (201)
-----19
M1 201 (0)
M1 202 (201)
get_P1 301 (202)
get_P1 302 (301)
-----20
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
get_P1 303 (201)
get_P1 304 (303)
-----21
M1 201 (0)
get_P1 301 (201)
get_P1 302 (301)
get_P1 303 (302)
-----22
get_P1 301 (0)
get_P1 302 (301)
get_P1 303 (302)
get_P1 304 (303)
-----23
get_P1 301 (0)
M1 201 (301)
M1 202 (201)
M1 203 (202)
-----24
M1 201 (0)
get_P1 301 (201)
M1 202 (301)
M1 203 (202)
-----25
M1 201 (0)
M1 202 (201)
get_P1 301 (202)
M1 203 (301)
-----26
get_P1 301 (0)
M1 201 (301)
set_P1 302 (0) = 301
-----27
get_P1 301 (0)
set_P2 401 (301) = 3 null
-----28
get_P1 301 (1)
get_P2 401 (301)
set_P2 402 (301) = 4 401
]]>)
End Sub
<Fact>
Public Sub LateBoundArgumentForByRefParameterInEarlyBoundCall_Diagnostic()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
Class Test2
Shared Sub Test()
Dim t2 As Object = Nothing
M1(t2.p1(0))
End Sub
Public Shared Sub M1(ByRef x As Integer)
End Sub
End Class </file>
</compilation>, TestOptions.ReleaseDll.WithOptionStrict(OptionStrict.Custom))
CompileAndVerify(compilation)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42017: Late bound resolution; runtime errors could occur.
M1(t2.p1(0))
~~~~~
BC42016: Implicit conversion from 'Object' to 'Integer'.
M1(t2.p1(0))
~~~~~~~~
</expected>)
End Sub
<Fact(), WorkItem(531153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531153")>
Public Sub Bug531153()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Sub1(ByRef x)
Console.WriteLine(x)
End Sub
Sub Main(args As String())
Dim VI As Object = 1
Sub1(Math.Abs(VI))
End Sub
End Module
</file>
</compilation>, expectedOutput:="1")
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 82 (0x52)
.maxstack 10
.locals init (Object V_0, //VI
Object V_1,
Object() V_2,
Boolean() V_3)
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: stloc.0
IL_0007: ldnull
IL_0008: ldtoken "System.Math"
IL_000d: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0012: ldstr "Abs"
IL_0017: ldc.i4.1
IL_0018: newarr "Object"
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldloc.0
IL_0020: stelem.ref
IL_0021: dup
IL_0022: stloc.2
IL_0023: ldnull
IL_0024: ldnull
IL_0025: ldc.i4.1
IL_0026: newarr "Boolean"
IL_002b: dup
IL_002c: ldc.i4.0
IL_002d: ldc.i4.1
IL_002e: stelem.i1
IL_002f: dup
IL_0030: stloc.3
IL_0031: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0036: ldloc.3
IL_0037: ldc.i4.0
IL_0038: ldelem.u1
IL_0039: brfalse.s IL_0044
IL_003b: ldloc.2
IL_003c: ldc.i4.0
IL_003d: ldelem.ref
IL_003e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0043: stloc.0
IL_0044: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0049: stloc.1
IL_004a: ldloca.s V_1
IL_004c: call "Sub Program.Sub1(ByRef Object)"
IL_0051: ret
}
]]>)
End Sub
<Fact(), WorkItem(531153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531153")>
Public Sub Bug531153_1()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Sub1(ByRef x)
Console.WriteLine(x)
End Sub
Sub Main(args As String())
Dim VI As Object = 1
Sub1(P1(VI))
End Sub
Public ReadOnly Property P1(x As Integer) As Integer
Get
Return 1
End Get
End Property
Public ReadOnly Property P1(x As string) As Integer
Get
Return 2
End Get
End Property
End Module
</file>
</compilation>, expectedOutput:="1")
verifier.VerifyIL("Program.Main",
<![CDATA[
{
// Code size 96 (0x60)
.maxstack 8
.locals init (Object V_0, //VI
Object V_1,
Object V_2)
IL_0000: ldc.i4.1
IL_0001: box "Integer"
IL_0006: stloc.0
IL_0007: ldnull
IL_0008: ldtoken "Program"
IL_000d: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0012: ldstr "P1"
IL_0017: ldc.i4.1
IL_0018: newarr "Object"
IL_001d: dup
IL_001e: ldc.i4.0
IL_001f: ldloc.0
IL_0020: dup
IL_0021: stloc.1
IL_0022: stelem.ref
IL_0023: ldnull
IL_0024: ldnull
IL_0025: ldnull
IL_0026: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_002b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0030: stloc.2
IL_0031: ldloca.s V_2
IL_0033: call "Sub Program.Sub1(ByRef Object)"
IL_0038: ldnull
IL_0039: ldtoken "Program"
IL_003e: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_0043: ldstr "P1"
IL_0048: ldc.i4.2
IL_0049: newarr "Object"
IL_004e: dup
IL_004f: ldc.i4.0
IL_0050: ldloc.1
IL_0051: stelem.ref
IL_0052: dup
IL_0053: ldc.i4.1
IL_0054: ldloc.2
IL_0055: stelem.ref
IL_0056: ldnull
IL_0057: ldnull
IL_0058: ldc.i4.1
IL_0059: ldc.i4.0
IL_005a: call "Sub Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSetComplex(Object, System.Type, String, Object(), String(), System.Type(), Boolean, Boolean)"
IL_005f: ret
}
]]>)
End Sub
<WorkItem(575833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575833")>
<Fact()>
Public Sub OverloadedMethodUsingNamespaceDotMethodSyntax()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit Off
Option Strict Off
Namespace N
Module M1
Sub main
End Sub
Friend Sub F(o As String)
End Sub
Friend Sub F(o As Integer)
End Sub
End Module
Module M2
Sub M(o)
N.F(o)
End Sub
End Module
End Namespace
]]></file>
</compilation>)
compilation.AssertNoErrors()
End Sub
<WorkItem(531569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531569")>
<Fact()>
Public Sub ObjectToXmlLiteral()
Dim verifier = CompileAndVerify(
<compilation>
<file name="a.vb">
<![CDATA[
Option Explicit Off
Option Strict Off
Imports System
Imports System.Xml.Linq
Friend Module Program
Sub Main()
Dim o2 As Object = "E"
o2 = XName.Get("HELLO")
Dim y2 = <<%= o2 %>></>
Console.WriteLine(y2.Name)
End Sub
End Module
]]>
</file>
</compilation>, expectedOutput:="HELLO", additionalRefs:=XmlReferences)
End Sub
<WorkItem(531569, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531569")>
<Fact()>
Public Sub ObjectToXmlLiteral_Err()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntimeAndReferences(
<compilation>
<file name="a.vb"><![CDATA[
Option Explicit Off
Option Strict On
Imports System
Imports System.Xml.Linq
Friend Module Program
Sub Main()
Dim o2 As Object = "E"
o2 = XName.Get("HELLO")
Dim y2 = <<%= o2 %>></>
Console.WriteLine(y2.Name)
End Sub
End Module
]]></file>
</compilation>, additionalRefs:=XmlReferences)
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC30518: Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Overloads Sub New(name As XName)': Option Strict On disallows implicit conversions from 'Object' to 'XName'.
'Public Overloads Sub New(other As XElement)': Option Strict On disallows implicit conversions from 'Object' to 'XElement'.
'Public Overloads Sub New(other As XStreamingElement)': Option Strict On disallows implicit conversions from 'Object' to 'XStreamingElement'.
Dim y2 = <<%= o2 %>></>
~~~~~~~~~
]]>
</expected>)
End Sub
<WorkItem(632206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632206")>
<Fact()>
Public Sub LateBang()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlibAndVBRuntime(
<compilation>
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Module Program
Sub Main(args As String())
Dim test As Object = Nothing
' error
test.dictionaryField!second
' error
test.dictionaryField!second()
' not an error
Dim o = test.dictionaryField!second
' not an error
o = test.dictionaryField!second()
' not an error
moo(test.dictionaryField!second)
End Sub
Sub moo(ByRef o As Object)
End Sub
End Module
]]>
</file>
</compilation>)
compilation.AssertTheseDiagnostics(
<expected><![CDATA[
BC30454: Expression is not a method.
test.dictionaryField!second
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30454: Expression is not a method.
test.dictionaryField!second()
~~~~~~~~~~~~~~~~~~~~~~~~~~~
]]>
</expected>)
End Sub
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenLateBound.vb
|
Visual Basic
|
apache-2.0
| 101,923
|
' 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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit
Imports Roslyn.Test.Utilities
Imports System.IO
Imports System.Reflection
Imports System.Xml.Linq
Imports Xunit
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Emit
Imports System.Collections.Immutable
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class NoPiaEmbedTypes
Inherits BasicTestBase
' See C# EmbedClass1 and EmbedClass2 tests.
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
Public Module M
End Module
Public Structure S
End Structure
Public Delegate Sub D()
Public Enum E
A
End Enum
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Imports B = A
Class C(Of T)
Sub M(o As Object)
Dim _1 As A = Nothing
Dim _2 As C(Of A) = Nothing
Dim _3 = GetType(A)
Dim _4 = GetType(A())
Dim _5 = GetType(B)
Dim _6 = GetType(M)
Dim _7 As S = Nothing
Dim _8 As D = Nothing
Dim _9 As E = Nothing
M(_1)
M(_2)
M(_3)
M(_4)
M(_5)
M(_6)
M(_7)
M(_8)
M(_9)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _1 As A = Nothing
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _2 As C(Of A) = Nothing
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _3 = GetType(A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _4 = GetType(A())
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Dim _5 = GetType(B)
~
BC31541: Reference to class 'M' is not allowed when its assembly is configured to embed interop types.
Dim _6 = GetType(M)
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
' See C# EmbedClass3 test.
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1_2()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Interface I(Of T)
End Interface
Class C(Of T)
End Class
Class B1
Inherits A
End Class
Class B2
Inherits C(Of A)
Implements I(Of A)
End Class
Class B3
Inherits C(Of I(Of A))
Implements I(Of C(Of A))
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits A
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits C(Of A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Implements I(Of A)
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Inherits C(Of I(Of A))
~
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Implements I(Of C(Of A))
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub BC31541ERR_CannotLinkClassWithNoPIA1_3()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Class A
End Class
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Imports COfA = C(Of A)
Class C(Of T)
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31541: Reference to class 'A' is not allowed when its assembly is configured to embed interop types.
Imports COfA = C(Of A)
~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub BC31558ERR_InvalidInteropType()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface IA
Interface IB
End Interface
Class C
End Class
Structure S
End Structure
Delegate Sub D()
Enum E
A
End Enum
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Dim _1 As IA.IB
Dim _2 As IA.C
Dim _3 As IA.S
Dim _4 As IA.D
Dim _5 As IA.E
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31558: Nested type 'IA.IB' cannot be embedded.
Dim _1 As IA.IB
~~~~~
BC31541: Reference to class 'IA.C' is not allowed when its assembly is configured to embed interop types.
Dim _2 As IA.C
~~~~
BC31558: Nested type 'IA.S' cannot be embedded.
Dim _3 As IA.S
~~~~
BC31558: Nested type 'IA.D' cannot be embedded.
Dim _4 As IA.D
~~~~
BC31558: Nested type 'IA.E' cannot be embedded.
Dim _5 As IA.E
~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={AssemblyMetadata.CreateFromImage(compilation1.EmitToArray()).GetReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub EmbedNestedType1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As S1.S2
End Interface
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F1(o As I) As Object
Dim x = o.F()
Return x
End Function
Function F2(o As I) As Object
Dim x As S1.S2 = o.F()
Return x
End Function
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Dim x = o.F()
~~~~~
BC31558: Nested type 'S1.S2' cannot be embedded.
Dim x As S1.S2 = o.F()
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub EmbedNestedType2()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As S1.S2
End Interface
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F(o As I) As Object
Return o.F()
End Function
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Return o.F()
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub EmbedNestedType3()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Structure S1
Structure S2
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As S1.S2)
End Sub
End Module
]]></file>
</compilation>
Dim errors2 = <errors>
BC31558: Nested type 'S1.S2' cannot be embedded.
Sub M(o As S1.S2)
~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors2)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors2)
End Sub
' See C# EmbedGenericType* tests.
<Fact()>
Public Sub BC36923ERR_CannotEmbedInterfaceWithGeneric()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1(Of T)
Interface I2
End Interface
Class C2
End Class
Structure S2
End Structure
Enum E2
A
End Enum
End Interface
Public Class C1(Of T)
End Class
Public Structure S1(Of T)
End Structure
Public Delegate Sub D1(Of T)()
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Dim _1 As I1(Of Object)
Dim _2 As I1(Of Object).I2
Dim _3 As I1(Of Object).C2
Dim _4 As I1(Of Object).S2
Dim _5 As I1(Of Object).E2
Dim _6 As C1(Of Object)
Dim _7 As S1(Of Object) ' No error from Dev11
Dim _8 As D1(Of Object) ' No error from Dev11
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC36923: Type 'I1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _1 As I1(Of Object)
~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).I2' cannot be embedded.
Dim _2 As I1(Of Object).I2
~~~~~~~~~~~~~~~~
BC31541: Reference to class 'I1(Of T).C2' is not allowed when its assembly is configured to embed interop types.
Dim _3 As I1(Of Object).C2
~~~~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).S2' cannot be embedded.
Dim _4 As I1(Of Object).S2
~~~~~~~~~~~~~~~~
BC31558: Nested type 'I1(Of T).E2' cannot be embedded.
Dim _5 As I1(Of Object).E2
~~~~~~~~~~~~~~~~
BC31541: Reference to class 'C1(Of T)' is not allowed when its assembly is configured to embed interop types.
Dim _6 As C1(Of Object)
~~~~~~~~~~~~~
BC36923: Type 'S1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _7 As S1(Of Object) ' No error from Dev11
~~~~~~~~~~~~~
BC36923: Type 'D1(Of T)' cannot be embedded because it has generic argument. Consider disabling the embedding of interop types.
Dim _8 As D1(Of Object) ' No error from Dev11
~~~~~~~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
Private Shared Sub VerifyEmitDiagnostics(compilation As VisualBasicCompilation, Optional errors As XElement = Nothing)
If errors Is Nothing Then
errors = <errors/>
End If
Using executableStream As New MemoryStream()
Dim result = compilation.Emit(executableStream)
result.Diagnostics.AssertTheseDiagnostics(errors)
End Using
End Sub
Private Shared Sub VerifyEmitMetadataOnlyDiagnostics(compilation As VisualBasicCompilation, Optional errors As XElement = Nothing)
If errors Is Nothing Then
errors = <errors/>
End If
Using executableStream As New MemoryStream()
Dim result = compilation.Emit(executableStream, options:=New EmitOptions(metadataOnly:=True))
result.Diagnostics.AssertTheseDiagnostics(errors)
End Using
End Sub
' See C# EmbedStructWith* tests.
<Fact()>
Public Sub BC31542ERR_InvalidStructMemberNoPIA1()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
' Public field
Public Structure S0
Public F As Object
End Structure
' Private field
Public Structure S1
Friend F As Object
End Structure
' Shared field
Public Structure S2
Public Shared F As Object
End Structure
' Public method
Public Structure S3
Public Sub F()
End Sub
End Structure
' Public property
Public Structure S4
Public Property P As Object
End Structure
' Public event
Public Delegate Sub D()
Public Structure S5
Public Event E As D
End Structure
' Public type
Public Structure S6
Public Structure T
End Structure
End Structure
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F0() As Object
Return DirectCast(Nothing, S0)
End Function
Function F1() As Object
Return DirectCast(Nothing, S1)
End Function
Function F2() As Object
Return DirectCast(Nothing, S2)
End Function
Function F3() As Object
Return DirectCast(Nothing, S3)
End Function
Function F4() As Object
Return DirectCast(Nothing, S4)
End Function
Function F5() As Object
Return DirectCast(Nothing, S5)
End Function
Function F6() As Object
Return DirectCast(Nothing, S6)
End Function
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31542: Embedded interop structure 'S1' can contain only public instance fields.
Return DirectCast(Nothing, S1)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S2' can contain only public instance fields.
Return DirectCast(Nothing, S2)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S3' can contain only public instance fields.
Return DirectCast(Nothing, S3)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S4' can contain only public instance fields.
Return DirectCast(Nothing, S4)
~~~~~~~~~~~~~~~~~~~~~~~
BC31542: Embedded interop structure 'S5' can contain only public instance fields.
Return DirectCast(Nothing, S5)
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub BC31561ERR_InteropMethodWithBody1()
Dim sources1 = <![CDATA[
.assembly extern mscorlib { .ver 4:0:0:0 .publickeytoken = (B7 7A 5C 56 19 34 E0 89) }
.assembly A
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = {string('_.dll')}
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = {string('f9c2d51d-4f44-45f0-9eda-c9d599b58257')}
}
.class public sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor(object o, native int m) runtime { }
.method public hidebysig instance void Invoke() runtime { }
.method public hidebysig instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback c, object o) runtime { }
.method public hidebysig instance void EndInvoke(class [mscorlib]System.IAsyncResult r) runtime { }
.method public static void M1() { ldnull throw }
.method public static pinvokeimpl("A.dll" winapi) void M2() { }
.method public instance void M3() { ldnull throw }
}
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As D)
D.M1()
D.M2()
o.M3()
End Sub
End Module
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(sources2, references:={reference1})
VerifyEmitDiagnostics(compilation2, <errors>
BC31561: Embedded interop method 'Sub D.M1()' contains a body.
D.M1()
~~~~~~
BC31561: Embedded interop method 'Sub D.M3()' contains a body.
D.M1()
~~~~~~
</errors>)
VerifyEmitMetadataOnlyDiagnostics(compilation2, <errors>
BC31561: Embedded interop method 'Sub D.M1()' contains a body.
BC31561: Embedded interop method 'Sub D.M3()' contains a body.
</errors>)
End Sub
<Fact()>
Public Sub TypeIdentifierIsMissing1()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Structure S
End Structure
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Function F() As Object
Dim x As S = Nothing
Return x
End Function
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' is not defined.
Dim x As S = Nothing
~~~~~~~
</errors>
Dim compilation0 = CreateEmptyCompilationWithReferences(sources0, references:={MscorlibRef_v20})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, <errors/>)
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v20, New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v20, compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub TypeIdentifierIsMissing2()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Function F() As Object
Dim y = DirectCast(Nothing, I)
Return y
End Function
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.TypeIdentifierAttribute..ctor' is not defined.
Dim y = DirectCast(Nothing, I)
~
</errors>
Dim compilation0 = CreateEmptyCompilationWithReferences(sources0, references:={MscorlibRef_v20})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
options:=TestOptions.DebugDll,
references:={MscorlibRef_v20, New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
options:=TestOptions.DebugDll,
references:={MscorlibRef_v20, compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub LocalTypeMetadata_Simple()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
Public Interface ITest1
End Interface
Public Structure Test2
Implements ITest1
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58259")>
Public Interface ITest3
Inherits ITest1
End Interface
Public Interface ITest4
End Interface
<Serializable()>
<StructLayout(LayoutKind.Explicit, CharSet:=CharSet.Unicode, Pack:=16, Size:=64)>
Public Structure Test5
<FieldOffset(2)>
Public F5 As Integer
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58260")>
Public Interface ITest6
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58261")>
Public Interface ITest7
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58262")>
Public Interface ITest8
End Interface
Public Enum Test9
F1 = 1
F2 = 2
End Enum
<Serializable()>
<StructLayout(LayoutKind.Sequential)>
Public Structure Test10
<NonSerialized()>
Public F3 As Integer
<MarshalAs(UnmanagedType.U4)>
Public F4 As Integer
End Structure
Public Delegate Sub Test11()
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58264")>
Public Interface ITest13
Sub M13(x As Integer)
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58265")>
Public Interface ITest14
Sub M14()
WriteOnly Property P6 As Integer
Event E4 As Action
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58266")>
Public Interface ITest15
Inherits ITest14
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58267")>
Public Interface ITest16
Sub M16()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58268")>
Public Interface ITest17
Sub M17()
Sub _VtblGap()
Sub M18()
Sub _VtblGap3_2()
Sub M19()
Sub _VtblGap4_2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58269")>
Public Interface ITest18
Sub _VtblGap3_2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58270")>
Public Interface ITest19
Function M20(ByRef x As Integer, ByRef y As Integer, <[In]()> ByRef z As Integer, <[In](), Out()> ByRef u As Integer, <[Optional]()> v As Integer, Optional w As Integer = 34) As String
Function M21(<MarshalAs(UnmanagedType.U4)> x As Integer) As <MarshalAs(UnmanagedType.LPWStr)> String
End Interface
Public Structure Test20
End Structure
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface ITest21
<SpecialName()>
Property P1 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface ITest22
Property P2 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface ITest23
ReadOnly Property P3 As Integer
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface ITest24
WriteOnly Property P4 As Integer
Event E3 As Action
Sub M27()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58275")>
Public Interface ITest25
<SpecialName()>
Event E1 As Action
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58276")>
Public Interface ITest26
Event E2 As Action
WriteOnly Property P5 As Integer
Sub M26()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Imports System
Class UsePia
Shared Sub Main()
Dim x As New Test2()
Dim y As ITest3 = Nothing
Console.WriteLine(x)
Console.WriteLine(y)
Dim x5 As New Test5()
Console.WriteLine(x5)
End Sub
<MyAttribute(GetType(ITest7))>
Sub M2(x As ITest6)
End Sub
End Class
Class UsePia1
Implements ITest8
End Class
Class MyAttribute
Inherits Attribute
Public Sub New(type As Type)
End Sub
End Class
Class UsePia2
Sub Test(x As Test10, x11 As Test11)
Console.WriteLine(Test9.F1.ToString())
Console.WriteLine(x.F4)
Dim y As ITest17 = Nothing
y.M17()
y.M19()
End Sub
End Class
Class UsePia3
Implements ITest13
Sub M13(x As Integer) Implements ITest13.M13
End Sub
Sub M14(x As ITest13)
x.M13(1)
x.M13(1)
End Sub
End Class
Interface IUsePia4
Inherits ITest15, ITest16, ITest18, ITest19
End Interface
Class UsePia4
Public Function M1(x As ITest21) As Integer
Return x.P1
End Function
Public Sub M2(x As ITest22)
x.P2 = 1
End Sub
Public Function M3(x As ITest23) As Integer
Return x.P3
End Function
Public Sub M4(x As ITest24)
x.P4 = 1
End Sub
Public Sub M5(x As ITest25)
AddHandler x.E1, Nothing
End Sub
Public Sub M6(x As ITest26)
RemoveHandler x.E2, Nothing
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim itest1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest1")
Assert.Equal(TypeKind.Interface, itest1.TypeKind)
Assert.Null(itest1.BaseType)
Assert.Equal(0, itest1.Interfaces.Length)
Assert.True(itest1.IsComImport)
Assert.False(itest1.IsSerializable)
Assert.False(itest1.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, itest1.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest1.Layout.Kind)
Assert.Equal(0, itest1.Layout.Alignment)
Assert.Equal(0, itest1.Layout.Size)
Dim attributes = itest1.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58258"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
' TypDefName: ITest1 (02000018)
' Flags : [Public] [AutoLayout] [Interface] [Abstract] [Import] [AnsiClass] (000010a1)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Interface Or TypeAttributes.Abstract Or TypeAttributes.Import Or TypeAttributes.AnsiClass, itest1.TypeDefFlags)
Dim test2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test2")
Assert.Equal(TypeKind.Structure, test2.TypeKind)
Assert.Equal(SpecialType.System_ValueType, test2.BaseType.SpecialType)
Assert.Same(itest1, test2.Interfaces.Single())
Assert.False(test2.IsComImport)
Assert.False(test2.IsSerializable)
Assert.True(test2.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test2.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Sequential, test2.Layout.Kind)
Assert.Equal(0, test2.Layout.Alignment)
Assert.Equal(1, test2.Layout.Size)
' TypDefName: Test2 (02000013)
' Flags : [Public] [SequentialLayout] [Class] [Sealed] [AnsiClass] [BeforeFieldInit] (00100109)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.SequentialLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass Or TypeAttributes.BeforeFieldInit, test2.TypeDefFlags)
attributes = test2.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test2"")", attributes(1).ToString())
Dim itest3 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest3")
Assert.Equal(TypeKind.Interface, itest3.TypeKind)
Assert.Same(itest1, itest3.Interfaces.Single())
Assert.True(itest3.IsComImport)
Assert.False(itest3.IsSerializable)
Assert.False(itest3.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, itest3.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, itest3.Layout.Kind)
Assert.Equal(0, itest3.Layout.Alignment)
Assert.Equal(0, itest3.Layout.Size)
Assert.Equal(0, [module].GlobalNamespace.GetTypeMembers("ITest4").Length)
Dim test5 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test5")
Assert.Equal(TypeKind.Structure, test5.TypeKind)
Assert.False(test5.IsComImport)
Assert.True(test5.IsSerializable)
Assert.True(test5.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Unicode, test5.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Explicit, test5.Layout.Kind)
Assert.Equal(16, test5.Layout.Alignment)
Assert.Equal(64, test5.Layout.Size)
Dim f5 = DirectCast(test5.GetMembers()(0), PEFieldSymbol)
Assert.Equal("Test5.F5 As System.Int32", f5.ToTestDisplayString())
Assert.Equal(2, f5.TypeLayoutOffset.Value)
' Field Name: F5 (04000003)
' Flags : [Public] (00000006)
Assert.Equal(FieldAttributes.Public, f5.FieldFlags)
Dim itest6 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest6")
Assert.Equal(TypeKind.Interface, itest6.TypeKind)
Dim itest7 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest7")
Assert.Equal(TypeKind.Interface, itest7.TypeKind)
Dim itest8 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest8")
Assert.Equal(TypeKind.Interface, itest8.TypeKind)
Assert.Same(itest8, [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("UsePia1").Interfaces.Single())
Dim test9 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test9")
Assert.Equal(TypeKind.Enum, test9.TypeKind)
Assert.False(test9.IsComImport)
Assert.False(test9.IsSerializable)
Assert.True(test9.IsNotInheritable)
Assert.Equal(System.Runtime.InteropServices.CharSet.Ansi, test9.MarshallingCharSet)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Auto, test9.Layout.Kind)
Assert.Equal(SpecialType.System_Int32, test9.EnumUnderlyingType.SpecialType)
' TypDefName: Test9 (02000016)
' Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass, test9.TypeDefFlags)
attributes = test9.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test9"")", attributes(1).ToString())
Dim fieldToEmit = test9.GetFieldsToEmit().ToArray().AsImmutableOrNull()
Assert.Equal(3, fieldToEmit.Length)
Dim value__ = DirectCast(fieldToEmit(0), PEFieldSymbol)
Assert.Equal(Accessibility.Public, value__.DeclaredAccessibility)
Assert.Equal("Test9.value__ As System.Int32", value__.ToTestDisplayString())
Assert.False(value__.IsShared)
Assert.True(value__.HasSpecialName)
Assert.True(value__.HasRuntimeSpecialName)
Assert.Null(value__.ConstantValue)
' Field Name: value__ (04000004)
' Flags : [Public] [SpecialName] [RTSpecialName] (00000606)
Assert.Equal(FieldAttributes.Public Or FieldAttributes.SpecialName Or FieldAttributes.RTSpecialName, value__.FieldFlags)
Dim f1 = DirectCast(fieldToEmit(1), PEFieldSymbol)
Assert.Equal(Accessibility.Public, f1.DeclaredAccessibility)
Assert.Equal("Test9.F1", f1.ToTestDisplayString())
Assert.True(f1.IsShared)
Assert.False(f1.HasSpecialName)
Assert.False(f1.HasRuntimeSpecialName)
Assert.Equal(1, f1.ConstantValue)
' Field Name: F1 (04000005)
' Flags : [Public] [Static] [Literal] [HasDefault] (00008056)
Assert.Equal(FieldAttributes.Public Or FieldAttributes.Static Or FieldAttributes.Literal Or FieldAttributes.HasDefault, f1.FieldFlags)
Dim f2 = DirectCast(fieldToEmit(2), PEFieldSymbol)
Assert.Equal("Test9.F2", f2.ToTestDisplayString())
Assert.Equal(2, f2.ConstantValue)
Assert.Equal(4, test9.GetMembers().Length)
Assert.Equal("Test9.value__ As System.Int32", test9.GetMembers()(0).ToTestDisplayString())
Assert.Same(f1, test9.GetMembers()(1))
Assert.Same(f2, test9.GetMembers()(2))
Assert.True(DirectCast(test9.GetMembers()(3), MethodSymbol).IsDefaultValueTypeConstructor())
Dim test10 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test10")
Assert.Equal(TypeKind.Structure, test10.TypeKind)
Assert.Equal(System.Runtime.InteropServices.LayoutKind.Sequential, test10.Layout.Kind)
Assert.Equal(3, test10.GetMembers().Length)
Dim f3 = DirectCast(test10.GetMembers()(0), FieldSymbol)
Assert.Equal(Accessibility.Public, f3.DeclaredAccessibility)
Assert.Equal("Test10.F3 As System.Int32", f3.ToTestDisplayString())
Assert.False(f3.IsShared)
Assert.False(f3.HasSpecialName)
Assert.False(f3.HasRuntimeSpecialName)
Assert.Null(f3.ConstantValue)
Assert.Equal(0, f3.MarshallingType)
Assert.False(f3.TypeLayoutOffset.HasValue)
Assert.True(f3.IsNotSerialized)
Dim f4 = DirectCast(test10.GetMembers()(1), FieldSymbol)
Assert.Equal("Test10.F4 As System.Int32", f4.ToTestDisplayString())
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.U4, f4.MarshallingType)
Assert.False(f4.IsNotSerialized)
Assert.True(DirectCast(test10.GetMembers()(2), MethodSymbol).IsDefaultValueTypeConstructor())
Dim test11 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("Test11")
Assert.Equal(TypeKind.Delegate, test11.TypeKind)
Assert.Equal(SpecialType.System_MulticastDelegate, test11.BaseType.SpecialType)
' TypDefName: Test11 (02000012)
' Flags : [Public] [AutoLayout] [Class] [Sealed] [AnsiClass] (00000101)
Assert.Equal(TypeAttributes.Public Or TypeAttributes.AutoLayout Or TypeAttributes.Class Or TypeAttributes.Sealed Or TypeAttributes.AnsiClass, test11.TypeDefFlags)
attributes = test11.GetAttributes()
Assert.Equal(2, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""Test11"")", attributes(1).ToString())
Assert.Equal(4, test11.GetMembers().Length)
Dim ctor = DirectCast(test11.GetMethod(".ctor"), PEMethodSymbol)
' MethodName: .ctor (0600000F)
' Flags : [Public] [ReuseSlot] [SpecialName] [RTSpecialName] [.ctor] (00001886)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 2 Arguments
' Argument #1: Object
' Argument #2: I
Assert.Equal(MethodAttributes.Public Or MethodAttributes.ReuseSlot Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName, ctor.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, ctor.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, ctor.CallingConvention)
Assert.Equal("Sub Test11..ctor(TargetObject As System.Object, TargetMethod As System.IntPtr)", ctor.ToTestDisplayString())
Dim begin = test11.GetMember(Of PEMethodSymbol)("BeginInvoke")
' MethodName: BeginInvoke (06000011)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Class System.IAsyncResult
' 2 Arguments
' Argument #1: Class System.AsyncCallback
' Argument #2: Object
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, begin.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, begin.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, begin.CallingConvention)
Assert.Equal("Function Test11.BeginInvoke(DelegateCallback As System.AsyncCallback, DelegateAsyncState As System.Object) As System.IAsyncResult", begin.ToTestDisplayString())
Dim [end] = test11.GetMember(Of PEMethodSymbol)("EndInvoke")
' MethodName: EndInvoke (06000012)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 1 Arguments
' Argument #1: Class System.IAsyncResult
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, [end].MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, [end].ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, [end].CallingConvention)
Assert.Equal("Sub Test11.EndInvoke(DelegateAsyncResult As System.IAsyncResult)", [end].ToTestDisplayString())
Dim invoke = test11.GetMember(Of PEMethodSymbol)("Invoke")
' MethodName: Invoke (06000010)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] (000001c6)
' ImplFlags : [Runtime] [Managed] (00000003)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' No arguments.
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot, invoke.MethodFlags)
Assert.Equal(MethodImplAttributes.Runtime, invoke.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, invoke.CallingConvention)
Assert.Equal("Sub Test11.Invoke()", invoke.ToTestDisplayString())
Dim itest13 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest13")
Assert.Equal(TypeKind.Interface, itest13.TypeKind)
Dim m13 = DirectCast(itest13.GetMembers()(0), PEMethodSymbol)
' MethodName: M13 (06000001)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] [Abstract] (000005c6)
' ImplFlags : [IL] [Managed] (00000000)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' 1 Arguments
' Argument #1: I4
' 1 Parameters
' (1) ParamToken : (08000001) Name : x flags: [none] (00000000)
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot Or MethodAttributes.Abstract, m13.MethodFlags)
Assert.Equal(MethodImplAttributes.IL, m13.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.HasThis, m13.CallingConvention)
Assert.Equal("Sub ITest13.M13(x As System.Int32)", m13.ToTestDisplayString())
Dim itest14 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest14")
Assert.Equal(TypeKind.Interface, itest14.TypeKind)
Assert.Equal(6, itest14.GetMembers().Length)
Assert.Equal("Sub ITest14.M14()", itest14.GetMembers()(0).ToTestDisplayString())
Assert.Equal("Sub ITest14.set_P6(Value As System.Int32)", itest14.GetMembers()(1).ToTestDisplayString())
Assert.Equal("Sub ITest14.add_E4(obj As System.Action)", itest14.GetMembers()(2).ToTestDisplayString())
Assert.Equal("Sub ITest14.remove_E4(obj As System.Action)", itest14.GetMembers()(3).ToTestDisplayString())
Assert.Equal("WriteOnly Property ITest14.P6 As System.Int32", itest14.GetMembers()(4).ToTestDisplayString())
Assert.Equal("Event ITest14.E4 As System.Action", itest14.GetMembers()(5).ToTestDisplayString())
Dim itest16 = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("ITest16")
Assert.Equal(TypeKind.Interface, itest16.TypeKind)
Assert.Equal("Sub ITest16.M16()", itest16.GetMembers()(0).ToTestDisplayString())
Dim itest17 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest17")
Assert.Equal(TypeKind.Interface, itest17.TypeKind)
Dim metadata = DirectCast([module], PEModuleSymbol).Module
Dim methodNames = metadata.GetMethodsOfTypeOrThrow(itest17.Handle).AsEnumerable().Select(
Function(rid) metadata.GetMethodDefNameOrThrow(rid)).ToArray()
Assert.Equal(3, methodNames.Length)
Assert.Equal("M17", methodNames(0))
Assert.Equal("_VtblGap1_4", methodNames(1))
Assert.Equal("M19", methodNames(2))
Dim gapMethodDef = metadata.GetMethodsOfTypeOrThrow(itest17.Handle).AsEnumerable().ElementAt(1)
Dim name As String = Nothing
Dim implFlags As MethodImplAttributes = Nothing
Dim flags As MethodAttributes = Nothing
Dim rva As Integer = Nothing
metadata.GetMethodDefPropsOrThrow(gapMethodDef, name, implFlags, flags, rva)
Assert.Equal(MethodAttributes.Public Or MethodAttributes.RTSpecialName Or MethodAttributes.SpecialName, flags)
Assert.Equal(MethodImplAttributes.IL Or MethodImplAttributes.Runtime, implFlags)
Dim signatureHeader As SignatureHeader = Nothing
Dim mrEx As BadImageFormatException = Nothing
Dim paramInfo = New MetadataDecoder(DirectCast([module], PEModuleSymbol), itest17).GetSignatureForMethod(gapMethodDef, signatureHeader:=signatureHeader, metadataException:=mrEx)
Assert.Null(mrEx)
Assert.Equal(CByte(SignatureCallingConvention.Default) Or CByte(SignatureAttributes.Instance), signatureHeader.RawValue)
Assert.Equal(1, paramInfo.Length)
Assert.Equal(SpecialType.System_Void, paramInfo(0).Type.SpecialType)
Assert.False(paramInfo(0).IsByRef)
Assert.True(paramInfo(0).CustomModifiers.IsDefault)
Assert.Equal(2, itest17.GetMembers().Length)
Dim m17 = itest17.GetMember(Of PEMethodSymbol)("M17")
' MethodName: M17 (06000013)
' Flags : [Public] [Virtual] [CheckAccessOnOverride] [NewSlot] [Abstract] (000005c6)
' ImplFlags : [IL] [Managed] (00000000)
' CallCnvntn: [DEFAULT]
' hasThis
' ReturnType: Void
' No arguments.
Assert.Equal(MethodAttributes.Public Or MethodAttributes.Virtual Or MethodAttributes.CheckAccessOnOverride Or MethodAttributes.NewSlot Or MethodAttributes.Abstract, m17.MethodFlags)
Assert.Equal(MethodImplAttributes.IL, m17.ImplementationAttributes)
Assert.Equal(Microsoft.Cci.CallingConvention.Default Or Microsoft.Cci.CallingConvention.HasThis, m17.CallingConvention)
Assert.Equal("Sub ITest17.M17()", m17.ToTestDisplayString())
Dim itest18 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest18")
Assert.Equal(TypeKind.Interface, itest18.TypeKind)
Assert.False(metadata.GetMethodsOfTypeOrThrow(itest18.Handle).AsEnumerable().Any())
Dim itest19 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest19")
Dim m20 = itest19.GetMember(Of PEMethodSymbol)("M20")
' 6 Arguments
' Argument #1: ByRef I4
' Argument #2: ByRef I4
' Argument #3: ByRef I4
' Argument #4: ByRef I4
' Argument #5: I4
' Argument #6: I4
' 6 Parameters
' (1) ParamToken : (08000008) Name : x flags: [none] (00000000)
' (2) ParamToken : (08000009) Name : y flags: [none] (00000000)
' (3) ParamToken : (0800000a) Name : z flags: [In] (00000001)
' (4) ParamToken : (0800000b) Name : u flags: [In] [Out] (00000003)
' (5) ParamToken : (0800000c) Name : v flags: [Optional] (00000010)
' (6) ParamToken : (0800000d) Name : w flags: [Optional] [HasDefault] (00001010) Default: (I4) 34
Dim param = DirectCast(m20.Parameters(0), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.None, param.ParamFlags)
param = DirectCast(m20.Parameters(1), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.None, param.ParamFlags)
param = DirectCast(m20.Parameters(2), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.In, param.ParamFlags)
param = DirectCast(m20.Parameters(3), PEParameterSymbol)
Assert.True(param.IsByRef)
Assert.Equal(ParameterAttributes.In Or ParameterAttributes.Out, param.ParamFlags)
param = DirectCast(m20.Parameters(4), PEParameterSymbol)
Assert.False(param.IsByRef)
Assert.Equal(ParameterAttributes.Optional, param.ParamFlags)
Assert.Null(param.ExplicitDefaultConstantValue)
param = DirectCast(m20.Parameters(5), PEParameterSymbol)
Assert.False(param.IsByRef)
Assert.Equal(ParameterAttributes.Optional Or ParameterAttributes.HasDefault, param.ParamFlags)
Assert.Equal(34, param.ExplicitDefaultValue)
Assert.False(m20.ReturnValueIsMarshalledExplicitly)
Dim m21 = itest19.GetMember(Of PEMethodSymbol)("M21")
' 1 Arguments
' Argument #1: I4
' 2 Parameters
' (0) ParamToken : (0800000e) Name : flags: [HasFieldMarshal] (00002000)
' NATIVE_TYPE_LPWSTR
' (1) ParamToken : (0800000f) Name : x flags: [HasFieldMarshal] (00002000)
' NATIVE_TYPE_U4
param = DirectCast(m21.Parameters(0), PEParameterSymbol)
Assert.Equal(ParameterAttributes.HasFieldMarshal, param.ParamFlags)
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.U4, CType(param.MarshallingDescriptor(0), System.Runtime.InteropServices.UnmanagedType))
Assert.True(m21.ReturnValueIsMarshalledExplicitly)
Assert.Equal(System.Runtime.InteropServices.UnmanagedType.LPWStr, CType(m21.ReturnValueMarshallingDescriptor(0), System.Runtime.InteropServices.UnmanagedType))
Dim itest21 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest21")
Dim p1 = itest21.GetMember(Of PEPropertySymbol)("P1")
Assert.Equal(Accessibility.Public, p1.DeclaredAccessibility)
Assert.True(p1.HasSpecialName)
Assert.False(p1.HasRuntimeSpecialName)
Dim get_P1 = itest21.GetMember(Of PEMethodSymbol)("get_P1")
Dim set_P1 = itest21.GetMember(Of PEMethodSymbol)("set_P1")
Assert.Same(p1.GetMethod, get_P1)
Assert.Same(p1.SetMethod, set_P1)
Dim itest22 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest22")
Dim p2 = itest22.GetMember(Of PEPropertySymbol)("P2")
Dim get_P2 = itest22.GetMember(Of PEMethodSymbol)("get_P2")
Dim set_P2 = itest22.GetMember(Of PEMethodSymbol)("set_P2")
Assert.Same(p2.GetMethod, get_P2)
Assert.Same(p2.SetMethod, set_P2)
Dim itest23 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest23")
Dim p3 = itest23.GetMember(Of PEPropertySymbol)("P3")
Dim get_P3 = itest23.GetMember(Of PEMethodSymbol)("get_P3")
Assert.Same(p3.GetMethod, get_P3)
Assert.Null(p3.SetMethod)
Dim itest24 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest24")
Dim p4 = itest24.GetMember(Of PEPropertySymbol)("P4")
Assert.Equal(2, itest24.GetMembers().Length)
Assert.False(p4.HasSpecialName)
Assert.False(p4.HasRuntimeSpecialName)
Assert.Equal(CByte(SignatureKind.Property) Or CByte(SignatureAttributes.Instance), CByte(p4.CallingConvention))
Dim set_P4 = itest24.GetMember(Of PEMethodSymbol)("set_P4")
Assert.Null(p4.GetMethod)
Assert.Same(p4.SetMethod, set_P4)
Dim itest25 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest25")
Dim e1 = itest25.GetMember(Of PEEventSymbol)("E1")
Assert.True(e1.HasSpecialName)
Assert.False(e1.HasRuntimeSpecialName)
Dim add_E1 = itest25.GetMember(Of PEMethodSymbol)("add_E1")
Dim remove_E1 = itest25.GetMember(Of PEMethodSymbol)("remove_E1")
Assert.Same(e1.AddMethod, add_E1)
Assert.Same(e1.RemoveMethod, remove_E1)
Dim itest26 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("ITest26")
Dim e2 = itest26.GetMember(Of PEEventSymbol)("E2")
Assert.Equal(3, itest26.GetMembers().Length)
Assert.False(e2.HasSpecialName)
Assert.False(e2.HasRuntimeSpecialName)
Dim add_E2 = itest26.GetMember(Of PEMethodSymbol)("add_E2")
Dim remove_E2 = itest26.GetMember(Of PEMethodSymbol)("remove_E2")
Assert.Same(e2.AddMethod, add_E2)
Assert.Same(e2.RemoveMethod, remove_E2)
End Sub
Dim expected_M5 = <![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldnull
IL_0003: callvirt "Sub ITest25.add_E1(System.Action)"
IL_0008: nop
IL_0009: ret
}
]]>
Dim expected_M6 = <![CDATA[
{
// Code size 10 (0xa)
.maxstack 2
IL_0000: nop
IL_0001: ldarg.1
IL_0002: ldnull
IL_0003: callvirt "Sub ITest26.remove_E2(System.Action)"
IL_0008: nop
IL_0009: ret
}
]]>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugExe,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
verifier.VerifyDiagnostics()
verifier.VerifyIL("UsePia4.M5", expected_M5)
verifier.VerifyIL("UsePia4.M6", expected_M6)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugExe,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
verifier.VerifyDiagnostics()
verifier.VerifyIL("UsePia4.M5", expected_M5)
verifier.VerifyIL("UsePia4.M6", expected_M6)
End Sub
<Fact()>
Public Sub LocalTypeMetadata_GenericParameters()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface I2
Sub M(Of T1, T2 As I1, T3 As New, T4 As Structure, T5 As Class, T6 As T1)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Interface I3
Inherits I2
End Interface
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Assert.Equal(TypeKind.Interface, type1.TypeKind)
Dim type2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Assert.Equal(TypeKind.Interface, type2.TypeKind)
Dim method = type2.GetMember(Of PEMethodSymbol)("M")
Dim tp = method.TypeParameters
Assert.Equal(6, tp.Length)
Dim t1 = tp(0)
Assert.Equal("T1", t1.Name)
Assert.False(t1.HasConstructorConstraint)
Assert.False(t1.HasValueTypeConstraint)
Assert.False(t1.HasReferenceTypeConstraint)
Assert.Equal(0, t1.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t1.Variance)
Dim t2 = tp(1)
Assert.Equal("T2", t2.Name)
Assert.False(t2.HasConstructorConstraint)
Assert.False(t2.HasValueTypeConstraint)
Assert.False(t2.HasReferenceTypeConstraint)
Assert.Equal(1, t2.ConstraintTypes.Length)
Assert.Same(type1, t2.ConstraintTypes(0))
Assert.Equal(VarianceKind.None, t2.Variance)
Dim t3 = tp(2)
Assert.Equal("T3", t3.Name)
Assert.True(t3.HasConstructorConstraint)
Assert.False(t3.HasValueTypeConstraint)
Assert.False(t3.HasReferenceTypeConstraint)
Assert.Equal(0, t3.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t3.Variance)
Dim t4 = tp(3)
Assert.Equal("T4", t4.Name)
Assert.False(t4.HasConstructorConstraint)
Assert.True(t4.HasValueTypeConstraint)
Assert.False(t4.HasReferenceTypeConstraint)
Assert.Equal(0, t4.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t4.Variance)
Dim t5 = tp(4)
Assert.Equal("T5", t5.Name)
Assert.False(t5.HasConstructorConstraint)
Assert.False(t5.HasValueTypeConstraint)
Assert.True(t5.HasReferenceTypeConstraint)
Assert.Equal(0, t5.ConstraintTypes.Length)
Assert.Equal(VarianceKind.None, t5.Variance)
Dim t6 = tp(5)
Assert.Equal("T6", t6.Name)
Assert.False(t6.HasConstructorConstraint)
Assert.False(t6.HasValueTypeConstraint)
Assert.False(t6.HasReferenceTypeConstraint)
Assert.Equal(1, t6.ConstraintTypes.Length)
Assert.Same(t1, t6.ConstraintTypes(0))
Assert.Equal(VarianceKind.None, t6.Variance)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator, verify:=Verification.Fails)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub NewWithoutCoClass()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I()
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC30375: 'New' cannot be used on an interface.
Return New I()
~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
<Fact()>
Public Sub NewCoClassWithoutGiud()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
Public Class C
Public Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I() With {.P = 2}
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'C' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
Return New I() With {.P = 2}
~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub NewCoClassWithGiud()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public MustInherit Class C
Protected Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I() With {.P = 2}
End Function
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attr = i.GetAttributes("System.Runtime.InteropServices", "CoClassAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.CoClassAttribute(GetType(Object))", attr.ToString())
End Sub
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("S.F", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldstr "f9c2d51d-4f44-45f0-9eda-c9d599b58278"
IL_0005: newobj "Sub System.Guid..ctor(String)"
IL_000a: call "Function System.Type.GetTypeFromCLSID(System.Guid) As System.Type"
IL_000f: call "Function System.Activator.CreateInstance(System.Type) As Object"
IL_0014: castclass "I"
IL_0019: dup
IL_001a: ldc.i4.2
IL_001b: callvirt "Sub I.set_P(Integer)"
IL_0020: ret
}
]]>)
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef_v4_0_30316_17626, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("S.F", <![CDATA[
{
// Code size 33 (0x21)
.maxstack 3
IL_0000: ldstr "f9c2d51d-4f44-45f0-9eda-c9d599b58278"
IL_0005: newobj "Sub System.Guid..ctor(String)"
IL_000a: call "Function System.Runtime.InteropServices.Marshal.GetTypeFromCLSID(System.Guid) As System.Type"
IL_000f: call "Function System.Activator.CreateInstance(System.Type) As Object"
IL_0014: castclass "I"
IL_0019: dup
IL_001a: ldc.i4.2
IL_001b: callvirt "Sub I.set_P(Integer)"
IL_0020: ret
}
]]>)
End Sub
<Fact()>
Public Sub NewCoClassWithGiud_Generic()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C(Of)))>
Public Interface I
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public MustInherit Class C(Of T)
Protected Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Function F() As I
Return New I()
End Function
End Module
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, <errors>
BC31450: Type 'C(Of )' cannot be used as an implementing class.
Return New I()
~~~~~~~
</errors>)
End Sub
''' <summary>
''' Report error attempting to instantiate NoPIA CoClass with arguments.
''' Note: Dev11 silently drops any arguments and does not report an error.
''' </summary>
<Fact()>
Public Sub NewCoClassWithArguments()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
Property P As Integer
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Class C
Public Sub New(o As Object)
End Sub
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Structure S
Function F() As I
Return New I("")
End Function
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
' No errors for /r:_.dll
Dim compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, MetadataReference.CreateFromImage(compilation0.EmitToArray())})
compilation1.AssertTheseDiagnostics()
' Error for /l:_.dll
compilation1 = CreateEmptyCompilationWithReferences(
sources1,
references:={MscorlibRef, SystemRef, compilation0.EmitToImageReference(embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30516: Overload resolution failed because no accessible 'New' accepts this number of arguments.
Return New I("")
~~~~~~~~~
</errors>)
' Verify the unused argument is available in the SemanticModel.
Dim syntaxTree = compilation1.SyntaxTrees(0)
Dim model = compilation1.GetSemanticModel(syntaxTree)
Dim node = DirectCast(syntaxTree.FindNodeOrTokenByKind(SyntaxKind.StringLiteralExpression).AsNode(), ExpressionSyntax)
Dim expr = model.GetTypeInfo(node)
Assert.Equal(expr.Type.SpecialType, SpecialType.System_String)
End Sub
<Fact()>
Public Sub NewCoClassMissingWellKnownMembers()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
<CoClass(GetType(C))>
Public Interface I
End Interface
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Class C
End Class
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Namespace System
Public Class Guid
Private Sub New()
End Sub
End Class
Public Class Activator
End Class
End Namespace
]]></file>
<file name="b.vb"><![CDATA[
Structure S
Function F() As I
Dim x As New I()
Return x
End Function
End Structure
]]></file>
</compilation>
Dim errors = <errors>
BC35000: Requested operation is not available because the runtime library function 'System.Activator.CreateInstance' is not defined.
Dim x As New I()
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Guid..ctor' is not defined.
Dim x As New I()
~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Type.GetTypeFromCLSID' is not defined.
Dim x As New I()
~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
' See C# AddHandler_Simple and RemoveHandler_Simple.
<Fact()>
Public Sub AddRemoveHandler()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I1
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I2
Inherits I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Sub Add(x As I1)
AddHandler x.E, AddressOf M
End Sub
Sub Remove(Of T As {Structure, I2})(x As T)
RemoveHandler x.E, AddressOf M
End Sub
Sub M()
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Assert.Equal("mscorlib", references(0).Name)
Assert.Equal("System.Core", references(1).Name)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.ComEventInterfaceAttribute(GetType(IE), GetType(IE))", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""I1"")", attributes(2).ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("IE")
attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
Dim method = type.GetMember(Of PEMethodSymbol)("E")
Assert.NotNull(method)
End Sub
Dim expectedAdd = <![CDATA[
{
// Code size 41 (0x29)
.maxstack 4
IL_0000: nop
IL_0001: ldtoken "I1"
IL_0006: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000b: ldstr "E"
IL_0010: newobj "Sub System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, String)"
IL_0015: ldarg.1
IL_0016: ldarg.0
IL_0017: ldftn "Sub C.M()"
IL_001d: newobj "Sub D..ctor(Object, System.IntPtr)"
IL_0022: callvirt "Sub System.Runtime.InteropServices.ComAwareEventInfo.AddEventHandler(Object, System.Delegate)"
IL_0027: nop
IL_0028: ret
}
]]>
Dim expectedRemove = <![CDATA[
{
// Code size 46 (0x2e)
.maxstack 4
IL_0000: nop
IL_0001: ldtoken "I1"
IL_0006: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type"
IL_000b: ldstr "E"
IL_0010: newobj "Sub System.Runtime.InteropServices.ComAwareEventInfo..ctor(System.Type, String)"
IL_0015: ldarg.1
IL_0016: box "T"
IL_001b: ldarg.0
IL_001c: ldftn "Sub C.M()"
IL_0022: newobj "Sub D..ctor(Object, System.IntPtr)"
IL_0027: callvirt "Sub System.Runtime.InteropServices.ComAwareEventInfo.RemoveEventHandler(Object, System.Delegate)"
IL_002c: nop
IL_002d: ret
}
]]>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("C.Add", expectedAdd)
verifier.VerifyIL("C.Remove(Of T)", expectedRemove)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
verifier.VerifyIL("C.Add", expectedAdd)
verifier.VerifyIL("C.Remove(Of T)", expectedRemove)
End Sub
<Fact()>
Public Sub [RaiseEvent]()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Implements I
Friend Event E As D Implements I.E
Sub Raise()
RaiseEvent E
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Assert.Equal("mscorlib", references(0).Name)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.ComEventInterfaceAttribute(GetType(IE), GetType(IE))", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"", ""I"")", attributes(2).ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("IE")
attributes = type.GetAttributes()
Assert.Equal(3, attributes.Length)
Assert.Equal("System.Runtime.CompilerServices.CompilerGeneratedAttribute", attributes(0).ToString())
Assert.Equal("System.Runtime.InteropServices.GuidAttribute(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")", attributes(1).ToString())
Assert.Equal("System.Runtime.InteropServices.TypeIdentifierAttribute", attributes(2).ToString())
Dim method = type.GetMember(Of PEMethodSymbol)("E")
Assert.NotNull(method)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<WorkItem(837420, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/837420")>
<Fact()>
Public Sub BC31556ERR_SourceInterfaceMustBeInterface()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(Object()), GetType(Object))>
Public Interface I1
Event E As D
End Interface
<ComEventInterface(GetType(Object()), GetType(Object))>
Public Interface I2
Event E As D
End Interface
<ComEventInterface(Nothing, Nothing)>
Public Interface I3
Event E As D
End Interface
<ComEventInterface(Nothing, Nothing)>
Public Interface I4
Event E As D
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M1(x1 As I1)
AddHandler x1.E, AddressOf H
End Sub
Sub M2(x2 As I2)
End Sub
Sub M3(x3 As I3)
End Sub
Sub M4(x4 As I4)
AddHandler x4.E, AddressOf H
End Sub
Sub H()
End Sub
End Class
]]></file>
</compilation>
' Note: Dev12 reports errors for all four interfaces,
' even though only I1.E and I4.E are referenced.
Dim errors = <errors>
BC31556: Interface 'I1' has an invalid source interface which is required to embed event 'Event E As D'.
AddHandler x1.E, AddressOf H
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31556: Interface 'I4' has an invalid source interface which is required to embed event 'Event E As D'.
AddHandler x4.E, AddressOf H
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
<Fact()>
Public Sub BC31557ERR_EventNoPIANoBackingMember()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Object))>
Public Interface I
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M1(x As I)
AddHandler x.E, AddressOf M2
End Sub
Sub M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31557: Source interface 'IE' is missing method 'E', which is required to embed event 'Event E As D'.
AddHandler x.E, AddressOf M2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
compilation0.AssertTheseDiagnostics()
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), SystemCoreRef})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, <errors/>)
End Sub
' See C# MissingComImport test.
<Fact()>
Public Sub BC31543ERR_NoPIAAttributeMissing2_ComImport()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Event D As D
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I)
AddHandler o.D, Nothing
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute.
AddHandler o.D, Nothing
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim errorsMetadataOnly = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.ComImportAttribute' attribute.
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
End Sub
' See C# MissingGuid test.
<Fact()>
Public Sub BC31543ERR_NoPIAAttributeMissing2_Guid()
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComImport()>
Public Interface I
Event D As D
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I)
AddHandler o.D, Nothing
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
AddHandler o.D, Nothing
~~~~~~~~~~~~~~~~~~~~~~~
</errors>
Dim errorsMetadataOnly = <errors>
BC31543: Interop type 'I' cannot be embedded because it is missing the required 'System.Runtime.InteropServices.GuidAttribute' attribute.
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
compilation1.AssertTheseDiagnostics()
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errorsMetadataOnly)
End Sub
<Fact()>
Public Sub InterfaceTypeAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
<InterfaceType(CShort(ComInterfaceType.InterfaceIsIUnknown))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I1, I2
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.InterfaceTypeAttribute(System.Runtime.InteropServices.ComInterfaceType.InterfaceIsIUnknown)", attr.ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
attr = type.GetAttributes("System.Runtime.InteropServices", "InterfaceTypeAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.InterfaceTypeAttribute(1)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub BestFitMappingAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
<BestFitMapping(True)>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
<BestFitMapping(False)>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I1, I2
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.BestFitMappingAttribute(True)", attr.ToString())
type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
attr = type.GetAttributes("System.Runtime.InteropServices", "BestFitMappingAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.BestFitMappingAttribute(False)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub FlagsAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<Flags()>
Public Enum E
A = 0
End Enum
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As E)
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("E")
Dim attr = type.GetAttributes("System", "FlagsAttribute").Single()
Assert.Equal("System.FlagsAttribute", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DefaultMemberAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Reflection
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
<DefaultMember("M")>
Public Interface I
Function M() As Integer()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim attr = type.GetAttributes("System.Reflection", "DefaultMemberAttribute").Single()
Assert.Equal("System.Reflection.DefaultMemberAttribute(""M"")", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub LCIDConversionAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<LCIDConversion(123)>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M() Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.GetAttributes("System.Runtime.InteropServices", "LCIDConversionAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.LCIDConversionAttribute(123)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DispIdAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<DispId(124)>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M() Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.GetAttributes("System.Runtime.InteropServices", "DispIdAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.DispIdAttribute(124)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub ParamArrayAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(ParamArray x As Integer())
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Implements I
Private Sub M(ParamArray x As Integer()) Implements I.M
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim param = method.Parameters(0)
Assert.Equal(0, param.GetAttributes().Length)
Assert.True(param.IsParamArray)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DateTimeConstantAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(<[Optional](), DateTimeConstant(987654321)> x As DateTime)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Assert.Equal(New Date(987654321), method.Parameters(0).ExplicitDefaultValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M(x As Date)'.
x.M()
~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DecimalConstantAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M1(<[Optional](), DecimalConstant(0, 0, Integer.MinValue, -2, -3)> x As Decimal)
Sub M2(<[Optional](), DecimalConstant(0, 0, UInteger.MaxValue, 2, 3)> x As Decimal)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M1()
x.M2()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M1")
Assert.Equal(39614081275578912866186559485D, method.Parameters(0).ExplicitDefaultValue)
method = type.GetMember(Of PEMethodSymbol)("M2")
Assert.Equal(79228162495817593528424333315D, method.Parameters(0).ExplicitDefaultValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M1(x As Decimal)'.
x.M1()
~~
BC30455: Argument not specified for parameter 'x' of 'Sub M2(x As Decimal)'.
x.M2()
~~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub DefaultParameterValueAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M(<[Optional](), DefaultParameterValue(123.456)> x As Decimal)
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40AndReferences(
sources0,
references:={SystemRef})
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Dim attr = method.Parameters(0).GetAttributes("System.Runtime.InteropServices", "DefaultParameterValueAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.DefaultParameterValueAttribute(123.456)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
compilation1.AssertTheseDiagnostics(<errors>
BC30455: Argument not specified for parameter 'x' of 'Sub M(x As Decimal)'.
x.M()
~
</errors>)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub UnmanagedFunctionPointerAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<UnmanagedFunctionPointerAttribute(CallingConvention.StdCall, SetLastError:=True)>
Public Delegate Sub D()
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As D)
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("D")
Dim attr = type.GetAttributes("System.Runtime.InteropServices", "UnmanagedFunctionPointerAttribute").Single()
Assert.Equal("System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute(System.Runtime.InteropServices.CallingConvention.StdCall, SetLastError:=True)", attr.ToString())
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub PreserveSigAttribute()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.CompilerServices
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
<PreserveSig()>
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Structure S
Sub M(x As I)
x.M()
End Sub
End Structure
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
Dim type = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I")
Dim method = type.GetMember(Of PEMethodSymbol)("M")
Assert.Equal(MethodImplAttributes.IL Or MethodImplAttributes.PreserveSig, CType(method.ImplementationAttributes, MethodImplAttributes))
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
' See C# TypeNameConflict1 test.
<Fact()>
Public Sub BC31552ERR_DuplicateLocalTypes3()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58256")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface I3
Inherits I1
End Interface
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Module M
Sub M(x As I2, y As I3)
End Sub
End Module
]]></file>
</compilation>
Dim errors = <errors>
BC31552: Cannot embed interop type 'I1' found in both assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and '1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider disabling the embedding of interop types.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
VerifyEmitDiagnostics(compilation0)
Dim compilation1 = CreateCompilationWithMscorlib40(sources1)
VerifyEmitDiagnostics(compilation1)
' No errors for /r:0.dll /l:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
' Errors for /l:0.dll /l:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
' See C# TypeNameConflict2 test.
<Fact()>
Public Sub BC31560ERR_LocalTypeNameClash2()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I0
Sub M1(o As I1)
Sub M2(o As I2)
Sub M3(o As I3)
Sub M4(o As I4)
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I2
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58274")>
Public Interface I3
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58275")>
Public Interface I4
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Module M
Sub M(o As I0)
o.M1(Nothing)
o.M2(Nothing)
o.M3(Nothing)
End Sub
End Module
Class I1
End Class
Delegate Sub I2()
Structure I3
End Structure
Structure I4
End Structure
]]></file>
</compilation>
' Note: Dev11 does not report any errors although the
' generated assembly fails peverify in these cases.
Dim errors = <errors>
BC31560: Embedding the interop type 'I1' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
BC31560: Embedding the interop type 'I2' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
BC31560: Embedding the interop type 'I3' from assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' causes a name clash in the current assembly. Consider disabling the embedding of interop types.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
VerifyEmitDiagnostics(compilation0)
' No errors for /r:0.dll.
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation1)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=False)})
VerifyEmitDiagnostics(compilation1)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
' Errors for /l:0.dll.
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub NoIndirectReference()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Public Class A
Public Shared F As Object
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Class B
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(1, references.Length)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation1)
AssertTheseDiagnostics(verifier, (<errors/>))
' No errors for /r:0.dll /r:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2)
AssertTheseDiagnostics(verifier, (<errors/>))
' Errors for /l:0.dll /r:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub IndirectReference()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Sub M()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Public Class A
Public Shared F As Object
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim sources2 = <compilation name="2">
<file name="a.vb"><![CDATA[
Class B
Private Shared F = A.F
Private Shared Sub M(o As I)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC40059: A reference was created to embedded interop assembly '0, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because of an indirect reference to that assembly from assembly '1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Consider changing the 'Embed Interop Types' property on either assembly.
</errors>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim references = [module].GetReferencedAssemblySymbols()
Assert.Equal(2, references.Length)
Assert.Equal("1", references(1).Name)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation1)
AssertTheseDiagnostics(verifier, (<errors/>))
' No errors for /r:0.dll /r:1.dll.
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=False), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2)
AssertTheseDiagnostics(verifier, (<errors/>))
' Errors for /l:0.dll /r:1.dll.
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), New VisualBasicCompilationReference(compilation1, embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources2,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True), compilation1.EmitToImageReference(embedInteropTypes:=False)})
verifier = CompileAndVerify(compilation2, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, errors)
End Sub
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_1()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Interface I
Inherits I3
End Interface
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim m1 = i1.GetMember(Of PEMethodSymbol)("M1")
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Dim m2 = i2.GetMember(Of PEMethodSymbol)("M2")
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Dim m3 = i3.GetMember(Of PEMethodSymbol)("M3")
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
' See C# ImplementedInterfacesAndTheirMembers_2
' and ExplicitInterfaceImplementation tests.
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_2()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Implements I3
Sub M() Implements I1.M1, I2.M2, I3.M3
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Dim m1 = i1.GetMember(Of PEMethodSymbol)("M1")
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Dim m2 = i2.GetMember(Of PEMethodSymbol)("M2")
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Dim m3 = i3.GetMember(Of PEMethodSymbol)("M3")
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub ImplementedInterfacesAndTheirMembers_3()
Dim sources0 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I1
Sub M1()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58272")>
Public Interface I2
Inherits I1
Sub M2()
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58273")>
Public Interface I3
Inherits I2
Sub M3()
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I3)
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
CompileAndVerify(compilation0)
compilation0.AssertTheseDiagnostics()
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim i1 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I1")
Assert.Equal(0, i1.GetMembers().Length)
Dim i2 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I2")
Assert.Equal(0, i2.GetMembers().Length)
Dim i3 = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("I3")
Assert.Equal(0, i3.GetMembers().Length)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
CompileAndVerify(compilation1, symbolValidator:=validator)
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
CompileAndVerify(compilation2, symbolValidator:=validator)
End Sub
<Fact()>
Public Sub EmbedEnum()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58271")>
Public Interface I
Function F() As E
End Interface
Public Enum E
A
B = 3
End Enum
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Private Const F As E = E.B
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim validator As Action(Of ModuleSymbol) = Sub([module])
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Assert.Equal(1, [module].GetReferencedAssemblySymbols().Length)
Dim e = [module].GlobalNamespace.GetMember(Of PENamedTypeSymbol)("E")
Dim f = e.GetMember(Of PEFieldSymbol)("A")
Assert.Equal(f.ConstantValue, 0)
f = e.GetMember(Of PEFieldSymbol)("B")
Assert.Equal(f.ConstantValue, 3)
f = e.GetMember(Of PEFieldSymbol)("value__")
Assert.False(f.HasConstantValue)
End Sub
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
compilation1 = CreateCompilationWithMscorlib40AndReferences(
sources1,
references:={compilation0.EmitToImageReference(embedInteropTypes:=True)})
verifier = CompileAndVerify(compilation1, symbolValidator:=validator)
AssertTheseDiagnostics(verifier, (<errors/>))
End Sub
<Fact()>
Public Sub ErrorType1()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub ErrorType2()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(I1), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim fullName = MetadataTypeName.FromFullName("I1")
Dim isNoPiaLocalType = False
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim assembly = compilation1.SourceModule.GetReferencedAssemblySymbols()(1)
Dim [module] = assembly.Modules(0)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
assembly = compilation2.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(DirectCast([module], PEModuleSymbol).LookupTopLevelMetadataType(fullName, isNoPiaLocalType))
Assert.True(isNoPiaLocalType)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3)
assembly = compilation3.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4)
assembly = compilation4.SourceModule.GetReferencedAssemblySymbols()(1)
[module] = assembly.Modules(0)
Assert.IsType(Of NoPiaMissingCanonicalTypeSymbol)(DirectCast([module], PEModuleSymbol).LookupTopLevelMetadataType(fullName, isNoPiaLocalType))
Assert.True(isNoPiaLocalType)
Assert.IsType(Of MissingMetadataTypeSymbol.TopLevel)([module].LookupTopLevelMetadataType(fullName))
Assert.Null(assembly.GetTypeByMetadataName(fullName.FullName))
End Sub
<Fact()>
Public Sub ErrorType3()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(I1), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC31539: Cannot find the interop type that matches the embedded type 'I1'. Are you missing an assembly reference?
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3, verify:=Verification.Fails)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4, verify:=Verification.Fails)
End Sub
<Fact()>
Public Sub ErrorType4()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(IList(Of List(Of I1))), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
End Sub
<Fact()>
Public Sub ErrorType5()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(IList(Of List(Of I1))), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
End Sub
<Fact()>
Public Sub ErrorType6()
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Inherits I1
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC30002: Type 'I1' is not defined.
</errors>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(pia2)
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
End Sub
<Fact()>
Public Sub ErrorType7()
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface I2
Sub M2(o As I1)
End Interface
]]></file>
</compilation>
Dim consumer = <compilation name="Consumer">
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
o.M2(Nothing)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC30002: Type 'I1' is not defined.
o.M2(Nothing)
~~~~~~~~~~~~~
</errors>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(pia2)
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
End Sub
<Fact()>
Public Sub ErrorType8()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(List(Of I1)), GetType(Object))>
Public Interface I2
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M(o As I2)
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
CompileAndVerify(piaCompilation2)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1, errors)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2, errors)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4)
End Sub
<Fact>
Public Sub ErrorType_Tuple()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
<Assembly: ImportedFromTypeLib("GeneralPIA1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface ITest33
End Interface
]]></file>
</compilation>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1, options:=TestOptions.ReleaseDll)
CompileAndVerify(piaCompilation1)
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Runtime.InteropServices
Imports System.Runtime.CompilerServices
Imports System.Collections.Generic
<assembly: ImportedFromTypeLib("GeneralPIA2.dll")>
<assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58290")>
<ComImport>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
Public Interface ITest34
Function M() As List(Of (ITest33, ITest33))
End Interface
]]></file>
</compilation>
Dim piaCompilation2 = CreateCompilationWithMscorlib40(
pia2, options:=TestOptions.ReleaseDll,
references:={piaCompilation1.EmitToImageReference(embedInteropTypes:=True), ValueTupleRef, SystemRuntimeFacadeRef})
CompileAndVerify(piaCompilation2)
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Imports System
Imports System.Collections.Generic
Public MustInherit Class UsePia5
Implements ITest34
End Class
]]></file>
</compilation>
Dim expected = <errors>
BC36924: Type 'List(Of ValueTuple(Of ITest33, ITest33))' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
Implements ITest34
~~~~~~~
</errors>
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.ToMetadataReference(embedInteropTypes:=True), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation1, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation1, expected)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation2, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation2, expected)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.ToMetadataReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation3, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation3, expected)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer, options:=TestOptions.ReleaseDll,
references:={piaCompilation2.EmitToImageReference(), piaCompilation1.ToMetadataReference(), ValueTupleRef, SystemRuntimeFacadeRef})
VerifyEmitDiagnostics(compilation4, expected)
VerifyEmitMetadataOnlyDiagnostics(compilation4, expected)
End Sub
<Fact()>
Public Sub ErrorType9()
Dim pia1 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("1.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58279")>
Public Interface I1
End Interface
]]></file>
</compilation>
Dim pia2 = <compilation>
<file name="a.vb"><![CDATA[
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("2.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58258")>
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58280")>
<ComEventInterface(GetType(List(Of I1)), GetType(Object))>
Public Interface I2
Sub M2()
End Interface
]]></file>
</compilation>
Dim consumer = <compilation>
<file name="a.vb"><![CDATA[
Class C
Sub M()
Dim o As I2 = Nothing
o.M2()
End Sub
End Class
]]></file>
</compilation>
Dim errors = <errors>
BC36924: Type 'List(Of I1)' cannot be used across assembly boundaries because it has a generic type argument that is an embedded interop type.
o.M2()
~~~~~~
</errors>
Dim piaCompilation1 = CreateCompilationWithMscorlib40(pia1)
CompileAndVerify(piaCompilation1)
Dim piaCompilation2 = CreateCompilationWithMscorlib40AndReferences(
pia2,
references:={New VisualBasicCompilationReference(piaCompilation1, embedInteropTypes:=True)})
'CompileAndVerify(piaCompilation2, emitOptions:=EmitOptions.RefEmitBug)
Dim compilation1 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2, embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation1, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation1)
Dim compilation2 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={piaCompilation2.EmitToImageReference(embedInteropTypes:=True)})
VerifyEmitDiagnostics(compilation2, errors)
VerifyEmitMetadataOnlyDiagnostics(compilation2)
Dim compilation3 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={New VisualBasicCompilationReference(piaCompilation2)})
CompileAndVerify(compilation3, verify:=Verification.Fails)
Dim compilation4 = CreateCompilationWithMscorlib40AndReferences(
consumer,
references:={MetadataReference.CreateFromImage(piaCompilation2.EmitToArray())})
CompileAndVerify(compilation4, verify:=Verification.Fails)
End Sub
<Fact(), WorkItem(673546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673546")>
Public Sub MissingComAwareEventInfo()
Dim sources0 = <compilation name="0">
<file name="a.vb"><![CDATA[
Imports System.Runtime.InteropServices
<Assembly: ImportedFromTypeLib("_.dll")>
<Assembly: Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58257")>
Public Delegate Sub D()
<ComEventInterface(GetType(IE), GetType(Integer))>
Public Interface I1
Event E As D
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58277")>
Public Interface I2
Inherits I1
End Interface
<ComImport()>
<Guid("f9c2d51d-4f44-45f0-9eda-c9d599b58278")>
Public Interface IE
Sub E
End Interface
]]></file>
</compilation>
Dim sources1 = <compilation name="1">
<file name="a.vb"><![CDATA[
Class C
Sub Add(x As I1)
AddHandler x.E, Sub() System.Console.WriteLine()
End Sub
End Class
]]></file>
</compilation>
Dim compilation0 = CreateCompilationWithMscorlib40(sources0)
Dim verifier = CompileAndVerify(compilation0)
AssertTheseDiagnostics(verifier, (<errors/>))
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(
sources1,
options:=TestOptions.DebugDll,
references:={New VisualBasicCompilationReference(compilation0, embedInteropTypes:=True)})
AssertTheseEmitDiagnostics(compilation1,
<expected>
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.InteropServices.ComAwareEventInfo..ctor' is not defined.
AddHandler x.E, Sub() System.Console.WriteLine()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
Private Shared Sub AssertTheseDiagnostics(verifier As CompilationVerifier, diagnostics As XElement)
verifier.Diagnostics.AssertTheseDiagnostics(diagnostics)
End Sub
<Fact()>
Public Sub DefaultValueWithoutOptional_01()
Dim sources1 = <![CDATA[
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern System
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly pia
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl
6C 00 00 ) // l..
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44
2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59
39 62 35 38 32 35 37 00 00 ) // 9b58257..
}
.module pia.dll
// MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
.class interface public abstract auto ansi import IA
{
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE
2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC
30 44 45 30 30 30 30 00 00 ) // 0DE0000..
.method public newslot abstract strict virtual
instance void M(int32 x) cil managed
{
.param [1] = int32(0x0000000C)
} // end of method IA::M
} // end of class IA
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Public Class B
Implements IA
Sub M(x As Integer) Implements IA.M
End Sub
End Class
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
CompileAndVerify(sources2, references:={reference1}, symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim ia = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("IA")
Dim m = CType(ia.GetMember("M"), MethodSymbol)
Dim p = DirectCast(m.Parameters(0), PEParameterSymbol)
Assert.False(p.IsMetadataOptional)
Assert.Equal(ParameterAttributes.HasDefault, p.ParamFlags)
Assert.Equal(CObj(&H0000000C), p.ExplicitDefaultConstantValue.Value)
Assert.False(p.HasExplicitDefaultValue)
Assert.Throws(GetType(InvalidOperationException), Sub()
Dim tmp = p.ExplicitDefaultValue
End Sub)
End Sub).VerifyDiagnostics()
End Sub
<Fact()>
Public Sub DefaultValueWithoutOptional_02()
Dim sources1 = <![CDATA[
.assembly extern mscorlib
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly extern System
{
.publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4..
.ver 4:0:0:0
}
.assembly pia
{
.custom instance void [mscorlib]System.Runtime.InteropServices.ImportedFromTypeLibAttribute::.ctor(string) = ( 01 00 0E 47 65 6E 65 72 61 6C 50 49 41 2E 64 6C // ...GeneralPIA.dl
6C 00 00 ) // l..
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 66 39 63 32 64 35 31 64 2D 34 66 34 34 // ..$f9c2d51d-4f44
2D 34 35 66 30 2D 39 65 64 61 2D 63 39 64 35 39 // -45f0-9eda-c9d59
39 62 35 38 32 35 37 00 00 ) // 9b58257..
}
.module pia.dll
// MVID: {FDF1B1F7-A867-40B9-83CD-3F75B2D2B3C2}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003 // WINDOWS_CUI
.corflags 0x00000001 // ILONLY
.class interface public abstract auto ansi import IA
{
.custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 44 45 41 44 42 45 45 46 2D 43 41 46 45 // ..$DEADBEEF-CAFE
2D 42 41 42 45 2D 42 41 41 44 2D 44 45 41 44 43 // -BABE-BAAD-DEADC
30 44 45 30 30 30 30 00 00 ) // 0DE0000..
.method public newslot abstract strict virtual
instance void M(valuetype [mscorlib]System.DateTime x) cil managed
{
.param [1]
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 B1 68 DE 3A 00 00 00 00 00 00 ) // ...h.:......
} // end of method IA::M
} // end of class IA
]]>.Value
Dim sources2 = <compilation>
<file name="a.vb"><![CDATA[
Public Class B
Implements IA
Sub M(x As System.DateTime) Implements IA.M
End Sub
End Class
]]></file>
</compilation>
Dim reference1 = CompileIL(sources1, prependDefaultHeader:=False, embedInteropTypes:=True)
CompileAndVerify(sources2, references:={reference1}, symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
Dim ia = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("IA")
Dim m = CType(ia.GetMember("M"), MethodSymbol)
Dim p = DirectCast(m.Parameters(0), PEParameterSymbol)
Assert.False(p.IsMetadataOptional)
Assert.Equal(ParameterAttributes.None, p.ParamFlags)
Assert.Equal("System.Runtime.CompilerServices.DateTimeConstantAttribute(987654321)", p.GetAttributes().Single().ToString())
Assert.Null(p.ExplicitDefaultConstantValue)
Assert.False(p.HasExplicitDefaultValue)
Assert.Throws(GetType(InvalidOperationException), Sub()
Dim tmp = p.ExplicitDefaultValue
End Sub)
End Sub).VerifyDiagnostics()
End Sub
<Fact, WorkItem(8088, "https://github.com/dotnet/roslyn/issues/8088")>
Public Sub ParametersWithoutNames()
Dim sources =
<compilation>
<file name="a.vb">
Public Class Program
Sub M(x As I1)
x.M1(1, 2, 3)
End Sub
Sub M1(value As Integer)
End Sub
Sub M2(Param As Integer)
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndReferences(sources,
{
AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.NoPia.ParametersWithoutNames).
GetReference(display:="ParametersWithoutNames.dll", embedInteropTypes:=True)
},
options:=TestOptions.ReleaseDll)
AssertParametersWithoutNames(compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I1").GetMember(Of MethodSymbol)("M1").Parameters, False)
CompileAndVerify(compilation,
symbolValidator:=
Sub([module] As ModuleSymbol)
DirectCast([module], PEModuleSymbol).Module.PretendThereArentNoPiaLocalTypes()
AssertParametersWithoutNames([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("I1").GetMember(Of MethodSymbol)("M1").Parameters, True)
Dim p As PEParameterSymbol
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M").Parameters(0), PEParameterSymbol)
Assert.Equal("x", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("x", p.Name)
Assert.Equal("x", p.MetadataName)
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M1").Parameters(0), PEParameterSymbol)
Assert.Equal("value", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("value", p.Name)
Assert.Equal("value", p.MetadataName)
p = DirectCast([module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("Program").GetMember(Of MethodSymbol)("M2").Parameters(0), PEParameterSymbol)
Assert.Equal("Param", DirectCast([module], PEModuleSymbol).Module.GetParamNameOrThrow(p.Handle))
Assert.Equal("Param", p.Name)
Assert.Equal("Param", p.MetadataName)
End Sub).VerifyDiagnostics()
End Sub
Private Shared Sub AssertParametersWithoutNames(parameters As ImmutableArray(Of ParameterSymbol), isEmbedded As Boolean)
Assert.True(DirectCast(parameters(0), PEParameterSymbol).Handle.IsNil)
Dim p1 = DirectCast(parameters(1), PEParameterSymbol)
Assert.True(p1.IsMetadataOptional)
Assert.False(p1.Handle.IsNil)
Assert.True(DirectCast(p1.ContainingModule, PEModuleSymbol).Module.MetadataReader.GetParameter(p1.Handle).Name.IsNil)
Dim p2 = DirectCast(parameters(2), PEParameterSymbol)
If isEmbedded Then
Assert.True(p2.Handle.IsNil)
Else
Assert.True(DirectCast(p2.ContainingModule, PEModuleSymbol).Module.MetadataReader.GetParameter(p2.Handle).Name.IsNil)
End If
For Each p In parameters
Assert.Equal("Param", p.Name)
Assert.Equal("", p.MetadataName)
Next
End Sub
End Class
End Namespace
|
VSadov/roslyn
|
src/Compilers/VisualBasic/Test/Emit/Emit/NoPiaEmbedTypes.vb
|
Visual Basic
|
apache-2.0
| 221,763
|
' 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 MyClassKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassInStatementTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>|</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterReturnTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Return |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterArgument1Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(|</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterArgument2Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar, |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterBinaryExpressionTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(bar + |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterNotTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Goo(Not |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterTypeOfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If TypeOf |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterDoWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do While |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterDoUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do Until |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterLoopWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop While |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterLoopUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop Until |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterElseIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>ElseIf |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterElseSpaceIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Else If |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterErrorTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Error |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterThrowTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Throw |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterInitializerTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterArrayInitializerSquiggleTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterArrayInitializerCommaTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {0, |</MethodBody>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassNotInModuleTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Module Goo
Sub Goo()
|
End Sub()
End Module</File>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassNotInSharedMethodTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Class Goo
Shared Sub Goo()
|
End Sub()
End Class</File>, "MyClass")
End Function
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassInStructureTest() As Task
Await VerifyRecommendationsMissingAsync(<File>
Module Goo
Sub Goo()
|
End Sub()
End Module</File>, "MyClass")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassAfterHandlesInClassWithEventsTest() As Task
Dim text = <ClassDeclaration>
Public Event Ev_Event()
Sub Handler() Handles |</ClassDeclaration>
Await VerifyRecommendationsContainAsync(text, "MyClass")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassNotAfterHandlesInClassWithNoEventsTest() As Task
Dim text = <ClassDeclaration>
Sub Handler() Handles |</ClassDeclaration>
Await VerifyRecommendationsMissingAsync(text, "MyClass")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassForDerivedEventTest() As Task
Dim text = <File>Public Class Base
Public Event Click()
End Class
Public Class Derived
Inherits Base
Sub Goo() Handles |
End Sub
End Class|</File>
Await VerifyRecommendationsContainAsync(text, "MyClass")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassInNameOf1Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim s = NameOf(|</MethodBody>, "MyClass")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function MyClassInNameOf2Test() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>Dim s = NameOf(System.|</MethodBody>, "MyClass")
End Function
End Class
End Namespace
|
bkoelman/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/MyClassKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 8,307
|
' 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.Host
Imports Microsoft.CodeAnalysis.Editor.Shared.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.ComponentModelHost
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim
Imports Microsoft.VisualStudio.Shell.Interop
Imports IVsTextBufferCoordinator = Microsoft.VisualStudio.TextManager.Interop.IVsTextBufferCoordinator
Imports VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Venus
Friend Class VisualBasicContainedLanguage
Inherits ContainedLanguage(Of VisualBasicPackage, VisualBasicLanguageService, VisualBasicProject)
Implements IVsContainedLanguageStaticEventBinding
Public Sub New(bufferCoordinator As IVsTextBufferCoordinator,
componentModel As IComponentModel,
project As VisualBasicProject,
hierarchy As IVsHierarchy,
itemid As UInteger,
languageService As VisualBasicLanguageService,
sourceCodeKind As SourceCodeKind)
MyBase.New(bufferCoordinator, componentModel, project, hierarchy, itemid, languageService, sourceCodeKind, VisualBasicHelperFormattingRule.Instance)
End Sub
Public Function AddStaticEventBinding(pszClassName As String,
pszUniqueMemberID As String,
pszObjectName As String,
pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.AddStaticEventBinding
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.Intellisense,
allowCancel:=False,
action:=Sub(c)
Dim visualStudioWorkspace = ComponentModel.GetService(Of visualStudioWorkspace)()
Dim document = GetThisDocument()
ContainedLanguageStaticEventBinding.AddStaticEventBinding(
document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.CancellationToken)
End Sub)
Return VSConstants.S_OK
End Function
Public Function EnsureStaticEventHandler(pszClassName As String,
pszObjectTypeName As String,
pszObjectName As String,
pszNameOfEvent As String,
pszEventHandlerName As String,
itemidInsertionPoint As UInteger,
ByRef pbstrUniqueMemberID As String,
ByRef pbstrEventBody As String,
pSpanInsertionPoint() As VsTextSpan) As Integer Implements IVsContainedLanguageStaticEventBinding.EnsureStaticEventHandler
Dim thisDocument = GetThisDocument()
Dim targetDocumentId = Me.ContainedDocument.FindProjectDocumentIdWithItemId(itemidInsertionPoint)
Dim targetDocument = thisDocument.Project.Solution.GetDocument(targetDocumentId)
If targetDocument Is Nothing Then
Throw New InvalidOperationException("Can't generate into that itemid")
End If
Dim idBodyAndInsertionPoint = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument,
targetDocument,
pszClassName,
pszObjectName,
pszObjectTypeName,
pszNameOfEvent,
pszEventHandlerName,
itemidInsertionPoint,
useHandlesClause:=True,
additionalFormattingRule:=New LineAdjustmentFormattingRule(),
cancellationToken:=Nothing)
pbstrUniqueMemberID = idBodyAndInsertionPoint.Item1
pbstrEventBody = idBodyAndInsertionPoint.Item2
pSpanInsertionPoint(0) = idBodyAndInsertionPoint.Item3
Return VSConstants.S_OK
End Function
Public Function GetStaticEventBindingsForObject(pszClassName As String,
pszObjectName As String,
ByRef pcMembers As Integer,
ppbstrEventNames As IntPtr,
ppbstrDisplayNames As IntPtr,
ppbstrMemberIDs As IntPtr) As Integer Implements IVsContainedLanguageStaticEventBinding.GetStaticEventBindingsForObject
Dim members As Integer
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.Intellisense,
allowCancel:=False,
action:=Sub(c)
Dim eventNamesAndMemberNamesAndIds = ContainedLanguageStaticEventBinding.GetStaticEventBindings(
GetThisDocument(), pszClassName, pszObjectName, c.CancellationToken)
members = eventNamesAndMemberNamesAndIds.Count()
CreateBSTRArray(ppbstrEventNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item1))
CreateBSTRArray(ppbstrDisplayNames, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item2))
CreateBSTRArray(ppbstrMemberIDs, eventNamesAndMemberNamesAndIds.Select(Function(e) e.Item3))
End Sub)
pcMembers = members
Return VSConstants.S_OK
End Function
Public Function RemoveStaticEventBinding(pszClassName As String,
pszUniqueMemberID As String,
pszObjectName As String,
pszNameOfEvent As String) As Integer Implements IVsContainedLanguageStaticEventBinding.RemoveStaticEventBinding
Me.ComponentModel.GetService(Of IWaitIndicator)().Wait(
BasicVSResources.Intellisense,
allowCancel:=False,
action:=Sub(c)
Dim visualStudioWorkspace = ComponentModel.GetService(Of visualStudioWorkspace)()
Dim document = GetThisDocument()
ContainedLanguageStaticEventBinding.RemoveStaticEventBinding(
document, visualStudioWorkspace, pszClassName, pszUniqueMemberID, pszObjectName, pszNameOfEvent, c.CancellationToken)
End Sub)
Return VSConstants.S_OK
End Function
Private Class VisualBasicHelperFormattingRule
Inherits AbstractFormattingRule
Public Shared Shadows Instance As IFormattingRule = New VisualBasicHelperFormattingRule()
Public Overrides Sub AddIndentBlockOperations(list As List(Of IndentBlockOperation), node As SyntaxNode, optionSet As OptionSet, nextOperation As NextAction(Of IndentBlockOperation))
' we need special behavior for VB due to @Helper code generation wierd-ness.
' this will looking for code gen specific style to make it not so expansive
If IsEndHelperPattern(node) Then
Return
End If
Dim multiLineLambda = TryCast(node, MultiLineLambdaExpressionSyntax)
If multiLineLambda IsNot Nothing AndAlso IsHelperSubLambda(multiLineLambda) Then
Return
End If
MyBase.AddIndentBlockOperations(list, node, optionSet, nextOperation)
End Sub
Private Shared Function IsHelperSubLambda(multiLineLambda As MultiLineLambdaExpressionSyntax) As Boolean
If multiLineLambda.Kind <> SyntaxKind.MultiLineSubLambdaExpression Then
Return False
End If
If multiLineLambda.SubOrFunctionHeader Is Nothing OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList Is Nothing OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters.Count <> 1 OrElse
multiLineLambda.SubOrFunctionHeader.ParameterList.Parameters(0).Identifier.Identifier.Text <> "__razor_helper_writer" Then
Return False
End If
Return True
End Function
Private Shared Function IsEndHelperPattern(node As SyntaxNode) As Boolean
If Not node.HasStructuredTrivia Then
Return False
End If
Dim method = TryCast(node, MethodBlockSyntax)
If method Is Nothing OrElse method.Statements.Count <> 2 Then
Return False
End If
Dim statementWithEndHelper = method.Statements(0)
Dim endToken = statementWithEndHelper.GetFirstToken()
If endToken.Kind <> SyntaxKind.EndKeyword Then
Return False
End If
Dim helperToken = endToken.GetNextToken(includeSkipped:=True)
If helperToken.Kind <> SyntaxKind.IdentifierToken OrElse
Not String.Equals(helperToken.Text, "Helper", StringComparison.OrdinalIgnoreCase) Then
Return False
End If
Dim asToken = helperToken.GetNextToken(includeSkipped:=True)
If asToken.Kind <> SyntaxKind.AsKeyword Then
Return False
End If
Return True
End Function
End Class
End Class
End Namespace
|
droyad/roslyn
|
src/VisualStudio/VisualBasic/Impl/Venus/VisualBasicContainedLanguage.vb
|
Visual Basic
|
apache-2.0
| 10,520
|
Public Class PrincipalRRHH
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/RRHH/Formulario/PrincipalRRHH.aspx.vb
|
Visual Basic
|
mit
| 183
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class FormMain
Inherits System.Windows.Forms.Form
'Das Formular überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen.
<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
'Wird vom Windows Form-Designer benötigt.
Private components As System.ComponentModel.IContainer
'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich.
'Das Bearbeiten ist mit dem Windows Form-Designer möglich.
'Das Bearbeiten mit dem Code-Editor ist nicht möglich.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(FormMain))
Me.MenuStripMain = New System.Windows.Forms.MenuStrip
Me.FileToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.SaveDatabaseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.RefreshDatabaseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ViewRawDatabaseToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ToolStripSeparator2 = New System.Windows.Forms.ToolStripSeparator
Me.PrintSelectedItemsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ToolStripSeparator1 = New System.Windows.Forms.ToolStripSeparator
Me.QuitToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.EditToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.MediaDatabaseInExcelToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ToolStripSeparator3 = New System.Windows.Forms.ToolStripSeparator
Me.EditSelectedItemToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.DeleteSelectedItemsToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ToolStripSeparator4 = New System.Windows.Forms.ToolStripSeparator
Me.AddItemToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ToolStripSeparator5 = New System.Windows.Forms.ToolStripSeparator
Me.PreferencesToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.ViewToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.FindToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.HelpToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.AboutToolStripMenuItem = New System.Windows.Forms.ToolStripMenuItem
Me.DataGridViewMedia = New System.Windows.Forms.DataGridView
Me.StatusStripMain = New System.Windows.Forms.StatusStrip
Me.ToolStripStatusLabelVersion = New System.Windows.Forms.ToolStripStatusLabel
Me.ToolStripStatusLabelTotalItems = New System.Windows.Forms.ToolStripStatusLabel
Me.ToolStripStatusLabelLastUpdated = New System.Windows.Forms.ToolStripStatusLabel
Me.GroupBoxFind = New System.Windows.Forms.GroupBox
Me.TextBoxFind = New System.Windows.Forms.TextBox
Me.ComboBoxField = New System.Windows.Forms.ComboBox
Me.ButtonFind = New System.Windows.Forms.Button
Me.ButtonFindClear = New System.Windows.Forms.Button
Me.ButtonFindHide = New System.Windows.Forms.Button
Me.MenuStripMain.SuspendLayout()
CType(Me.DataGridViewMedia, System.ComponentModel.ISupportInitialize).BeginInit()
Me.StatusStripMain.SuspendLayout()
Me.GroupBoxFind.SuspendLayout()
Me.SuspendLayout()
'
'MenuStripMain
'
Me.MenuStripMain.AccessibleDescription = Nothing
Me.MenuStripMain.AccessibleName = Nothing
resources.ApplyResources(Me.MenuStripMain, "MenuStripMain")
Me.MenuStripMain.BackgroundImage = Nothing
Me.MenuStripMain.Font = Nothing
Me.MenuStripMain.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FileToolStripMenuItem, Me.EditToolStripMenuItem, Me.ViewToolStripMenuItem, Me.HelpToolStripMenuItem})
Me.MenuStripMain.Name = "MenuStripMain"
'
'FileToolStripMenuItem
'
Me.FileToolStripMenuItem.AccessibleDescription = Nothing
Me.FileToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.FileToolStripMenuItem, "FileToolStripMenuItem")
Me.FileToolStripMenuItem.BackgroundImage = Nothing
Me.FileToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.SaveDatabaseToolStripMenuItem, Me.RefreshDatabaseToolStripMenuItem, Me.ViewRawDatabaseToolStripMenuItem, Me.ToolStripSeparator2, Me.PrintSelectedItemsToolStripMenuItem, Me.ToolStripSeparator1, Me.QuitToolStripMenuItem})
Me.FileToolStripMenuItem.Name = "FileToolStripMenuItem"
Me.FileToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'SaveDatabaseToolStripMenuItem
'
Me.SaveDatabaseToolStripMenuItem.AccessibleDescription = Nothing
Me.SaveDatabaseToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.SaveDatabaseToolStripMenuItem, "SaveDatabaseToolStripMenuItem")
Me.SaveDatabaseToolStripMenuItem.BackgroundImage = Nothing
Me.SaveDatabaseToolStripMenuItem.Name = "SaveDatabaseToolStripMenuItem"
Me.SaveDatabaseToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'RefreshDatabaseToolStripMenuItem
'
Me.RefreshDatabaseToolStripMenuItem.AccessibleDescription = Nothing
Me.RefreshDatabaseToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.RefreshDatabaseToolStripMenuItem, "RefreshDatabaseToolStripMenuItem")
Me.RefreshDatabaseToolStripMenuItem.BackgroundImage = Nothing
Me.RefreshDatabaseToolStripMenuItem.Name = "RefreshDatabaseToolStripMenuItem"
Me.RefreshDatabaseToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ViewRawDatabaseToolStripMenuItem
'
Me.ViewRawDatabaseToolStripMenuItem.AccessibleDescription = Nothing
Me.ViewRawDatabaseToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.ViewRawDatabaseToolStripMenuItem, "ViewRawDatabaseToolStripMenuItem")
Me.ViewRawDatabaseToolStripMenuItem.BackgroundImage = Nothing
Me.ViewRawDatabaseToolStripMenuItem.Name = "ViewRawDatabaseToolStripMenuItem"
Me.ViewRawDatabaseToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ToolStripSeparator2
'
Me.ToolStripSeparator2.AccessibleDescription = Nothing
Me.ToolStripSeparator2.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripSeparator2, "ToolStripSeparator2")
Me.ToolStripSeparator2.Name = "ToolStripSeparator2"
'
'PrintSelectedItemsToolStripMenuItem
'
Me.PrintSelectedItemsToolStripMenuItem.AccessibleDescription = Nothing
Me.PrintSelectedItemsToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.PrintSelectedItemsToolStripMenuItem, "PrintSelectedItemsToolStripMenuItem")
Me.PrintSelectedItemsToolStripMenuItem.BackgroundImage = Nothing
Me.PrintSelectedItemsToolStripMenuItem.Name = "PrintSelectedItemsToolStripMenuItem"
Me.PrintSelectedItemsToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ToolStripSeparator1
'
Me.ToolStripSeparator1.AccessibleDescription = Nothing
Me.ToolStripSeparator1.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripSeparator1, "ToolStripSeparator1")
Me.ToolStripSeparator1.Name = "ToolStripSeparator1"
'
'QuitToolStripMenuItem
'
Me.QuitToolStripMenuItem.AccessibleDescription = Nothing
Me.QuitToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.QuitToolStripMenuItem, "QuitToolStripMenuItem")
Me.QuitToolStripMenuItem.BackgroundImage = Nothing
Me.QuitToolStripMenuItem.Name = "QuitToolStripMenuItem"
Me.QuitToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'EditToolStripMenuItem
'
Me.EditToolStripMenuItem.AccessibleDescription = Nothing
Me.EditToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.EditToolStripMenuItem, "EditToolStripMenuItem")
Me.EditToolStripMenuItem.BackgroundImage = Nothing
Me.EditToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.MediaDatabaseInExcelToolStripMenuItem, Me.ToolStripSeparator3, Me.EditSelectedItemToolStripMenuItem, Me.DeleteSelectedItemsToolStripMenuItem, Me.ToolStripSeparator4, Me.AddItemToolStripMenuItem, Me.ToolStripSeparator5, Me.PreferencesToolStripMenuItem})
Me.EditToolStripMenuItem.Name = "EditToolStripMenuItem"
Me.EditToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'MediaDatabaseInExcelToolStripMenuItem
'
Me.MediaDatabaseInExcelToolStripMenuItem.AccessibleDescription = Nothing
Me.MediaDatabaseInExcelToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.MediaDatabaseInExcelToolStripMenuItem, "MediaDatabaseInExcelToolStripMenuItem")
Me.MediaDatabaseInExcelToolStripMenuItem.BackgroundImage = Nothing
Me.MediaDatabaseInExcelToolStripMenuItem.Name = "MediaDatabaseInExcelToolStripMenuItem"
Me.MediaDatabaseInExcelToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ToolStripSeparator3
'
Me.ToolStripSeparator3.AccessibleDescription = Nothing
Me.ToolStripSeparator3.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripSeparator3, "ToolStripSeparator3")
Me.ToolStripSeparator3.Name = "ToolStripSeparator3"
'
'EditSelectedItemToolStripMenuItem
'
Me.EditSelectedItemToolStripMenuItem.AccessibleDescription = Nothing
Me.EditSelectedItemToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.EditSelectedItemToolStripMenuItem, "EditSelectedItemToolStripMenuItem")
Me.EditSelectedItemToolStripMenuItem.BackgroundImage = Nothing
Me.EditSelectedItemToolStripMenuItem.Name = "EditSelectedItemToolStripMenuItem"
Me.EditSelectedItemToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'DeleteSelectedItemsToolStripMenuItem
'
Me.DeleteSelectedItemsToolStripMenuItem.AccessibleDescription = Nothing
Me.DeleteSelectedItemsToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.DeleteSelectedItemsToolStripMenuItem, "DeleteSelectedItemsToolStripMenuItem")
Me.DeleteSelectedItemsToolStripMenuItem.BackgroundImage = Nothing
Me.DeleteSelectedItemsToolStripMenuItem.Name = "DeleteSelectedItemsToolStripMenuItem"
Me.DeleteSelectedItemsToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ToolStripSeparator4
'
Me.ToolStripSeparator4.AccessibleDescription = Nothing
Me.ToolStripSeparator4.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripSeparator4, "ToolStripSeparator4")
Me.ToolStripSeparator4.Name = "ToolStripSeparator4"
'
'AddItemToolStripMenuItem
'
Me.AddItemToolStripMenuItem.AccessibleDescription = Nothing
Me.AddItemToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.AddItemToolStripMenuItem, "AddItemToolStripMenuItem")
Me.AddItemToolStripMenuItem.BackgroundImage = Nothing
Me.AddItemToolStripMenuItem.Name = "AddItemToolStripMenuItem"
Me.AddItemToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ToolStripSeparator5
'
Me.ToolStripSeparator5.AccessibleDescription = Nothing
Me.ToolStripSeparator5.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripSeparator5, "ToolStripSeparator5")
Me.ToolStripSeparator5.Name = "ToolStripSeparator5"
'
'PreferencesToolStripMenuItem
'
Me.PreferencesToolStripMenuItem.AccessibleDescription = Nothing
Me.PreferencesToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.PreferencesToolStripMenuItem, "PreferencesToolStripMenuItem")
Me.PreferencesToolStripMenuItem.BackgroundImage = Nothing
Me.PreferencesToolStripMenuItem.Name = "PreferencesToolStripMenuItem"
Me.PreferencesToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'ViewToolStripMenuItem
'
Me.ViewToolStripMenuItem.AccessibleDescription = Nothing
Me.ViewToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.ViewToolStripMenuItem, "ViewToolStripMenuItem")
Me.ViewToolStripMenuItem.BackgroundImage = Nothing
Me.ViewToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.FindToolStripMenuItem})
Me.ViewToolStripMenuItem.Name = "ViewToolStripMenuItem"
Me.ViewToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'FindToolStripMenuItem
'
Me.FindToolStripMenuItem.AccessibleDescription = Nothing
Me.FindToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.FindToolStripMenuItem, "FindToolStripMenuItem")
Me.FindToolStripMenuItem.BackgroundImage = Nothing
Me.FindToolStripMenuItem.Name = "FindToolStripMenuItem"
Me.FindToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'HelpToolStripMenuItem
'
Me.HelpToolStripMenuItem.AccessibleDescription = Nothing
Me.HelpToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.HelpToolStripMenuItem, "HelpToolStripMenuItem")
Me.HelpToolStripMenuItem.BackgroundImage = Nothing
Me.HelpToolStripMenuItem.DropDownItems.AddRange(New System.Windows.Forms.ToolStripItem() {Me.AboutToolStripMenuItem})
Me.HelpToolStripMenuItem.Name = "HelpToolStripMenuItem"
Me.HelpToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'AboutToolStripMenuItem
'
Me.AboutToolStripMenuItem.AccessibleDescription = Nothing
Me.AboutToolStripMenuItem.AccessibleName = Nothing
resources.ApplyResources(Me.AboutToolStripMenuItem, "AboutToolStripMenuItem")
Me.AboutToolStripMenuItem.BackgroundImage = Nothing
Me.AboutToolStripMenuItem.Name = "AboutToolStripMenuItem"
Me.AboutToolStripMenuItem.ShortcutKeyDisplayString = Nothing
'
'DataGridViewMedia
'
Me.DataGridViewMedia.AccessibleDescription = Nothing
Me.DataGridViewMedia.AccessibleName = Nothing
Me.DataGridViewMedia.AllowUserToAddRows = False
Me.DataGridViewMedia.AllowUserToDeleteRows = False
Me.DataGridViewMedia.AllowUserToOrderColumns = True
resources.ApplyResources(Me.DataGridViewMedia, "DataGridViewMedia")
Me.DataGridViewMedia.BackgroundImage = Nothing
Me.DataGridViewMedia.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.DataGridViewMedia.Font = Nothing
Me.DataGridViewMedia.Name = "DataGridViewMedia"
Me.DataGridViewMedia.ReadOnly = True
Me.DataGridViewMedia.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect
'
'StatusStripMain
'
Me.StatusStripMain.AccessibleDescription = Nothing
Me.StatusStripMain.AccessibleName = Nothing
resources.ApplyResources(Me.StatusStripMain, "StatusStripMain")
Me.StatusStripMain.BackgroundImage = Nothing
Me.StatusStripMain.Font = Nothing
Me.StatusStripMain.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripStatusLabelVersion, Me.ToolStripStatusLabelTotalItems, Me.ToolStripStatusLabelLastUpdated})
Me.StatusStripMain.Name = "StatusStripMain"
'
'ToolStripStatusLabelVersion
'
Me.ToolStripStatusLabelVersion.AccessibleDescription = Nothing
Me.ToolStripStatusLabelVersion.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripStatusLabelVersion, "ToolStripStatusLabelVersion")
Me.ToolStripStatusLabelVersion.BackgroundImage = Nothing
Me.ToolStripStatusLabelVersion.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right
Me.ToolStripStatusLabelVersion.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text
Me.ToolStripStatusLabelVersion.Name = "ToolStripStatusLabelVersion"
'
'ToolStripStatusLabelTotalItems
'
Me.ToolStripStatusLabelTotalItems.AccessibleDescription = Nothing
Me.ToolStripStatusLabelTotalItems.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripStatusLabelTotalItems, "ToolStripStatusLabelTotalItems")
Me.ToolStripStatusLabelTotalItems.BackgroundImage = Nothing
Me.ToolStripStatusLabelTotalItems.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Right
Me.ToolStripStatusLabelTotalItems.Name = "ToolStripStatusLabelTotalItems"
'
'ToolStripStatusLabelLastUpdated
'
Me.ToolStripStatusLabelLastUpdated.AccessibleDescription = Nothing
Me.ToolStripStatusLabelLastUpdated.AccessibleName = Nothing
resources.ApplyResources(Me.ToolStripStatusLabelLastUpdated, "ToolStripStatusLabelLastUpdated")
Me.ToolStripStatusLabelLastUpdated.BackgroundImage = Nothing
Me.ToolStripStatusLabelLastUpdated.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text
Me.ToolStripStatusLabelLastUpdated.Name = "ToolStripStatusLabelLastUpdated"
'
'GroupBoxFind
'
Me.GroupBoxFind.AccessibleDescription = Nothing
Me.GroupBoxFind.AccessibleName = Nothing
resources.ApplyResources(Me.GroupBoxFind, "GroupBoxFind")
Me.GroupBoxFind.BackgroundImage = Nothing
Me.GroupBoxFind.Controls.Add(Me.TextBoxFind)
Me.GroupBoxFind.Controls.Add(Me.ComboBoxField)
Me.GroupBoxFind.Controls.Add(Me.ButtonFind)
Me.GroupBoxFind.Controls.Add(Me.ButtonFindClear)
Me.GroupBoxFind.Controls.Add(Me.ButtonFindHide)
Me.GroupBoxFind.Font = Nothing
Me.GroupBoxFind.Name = "GroupBoxFind"
Me.GroupBoxFind.TabStop = False
'
'TextBoxFind
'
Me.TextBoxFind.AccessibleDescription = Nothing
Me.TextBoxFind.AccessibleName = Nothing
resources.ApplyResources(Me.TextBoxFind, "TextBoxFind")
Me.TextBoxFind.BackgroundImage = Nothing
Me.TextBoxFind.Font = Nothing
Me.TextBoxFind.Name = "TextBoxFind"
'
'ComboBoxField
'
Me.ComboBoxField.AccessibleDescription = Nothing
Me.ComboBoxField.AccessibleName = Nothing
resources.ApplyResources(Me.ComboBoxField, "ComboBoxField")
Me.ComboBoxField.BackgroundImage = Nothing
Me.ComboBoxField.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList
Me.ComboBoxField.Font = Nothing
Me.ComboBoxField.FormattingEnabled = True
Me.ComboBoxField.Name = "ComboBoxField"
'
'ButtonFind
'
Me.ButtonFind.AccessibleDescription = Nothing
Me.ButtonFind.AccessibleName = Nothing
resources.ApplyResources(Me.ButtonFind, "ButtonFind")
Me.ButtonFind.BackgroundImage = Nothing
Me.ButtonFind.Font = Nothing
Me.ButtonFind.Name = "ButtonFind"
Me.ButtonFind.UseVisualStyleBackColor = True
'
'ButtonFindClear
'
Me.ButtonFindClear.AccessibleDescription = Nothing
Me.ButtonFindClear.AccessibleName = Nothing
resources.ApplyResources(Me.ButtonFindClear, "ButtonFindClear")
Me.ButtonFindClear.BackgroundImage = Nothing
Me.ButtonFindClear.Font = Nothing
Me.ButtonFindClear.Name = "ButtonFindClear"
Me.ButtonFindClear.UseVisualStyleBackColor = True
'
'ButtonFindHide
'
Me.ButtonFindHide.AccessibleDescription = Nothing
Me.ButtonFindHide.AccessibleName = Nothing
resources.ApplyResources(Me.ButtonFindHide, "ButtonFindHide")
Me.ButtonFindHide.BackgroundImage = Nothing
Me.ButtonFindHide.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.ButtonFindHide.Font = Nothing
Me.ButtonFindHide.Name = "ButtonFindHide"
Me.ButtonFindHide.UseVisualStyleBackColor = True
'
'FormMain
'
Me.AcceptButton = Me.ButtonFind
Me.AccessibleDescription = Nothing
Me.AccessibleName = Nothing
resources.ApplyResources(Me, "$this")
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.BackgroundImage = Nothing
Me.CancelButton = Me.ButtonFindHide
Me.Controls.Add(Me.DataGridViewMedia)
Me.Controls.Add(Me.StatusStripMain)
Me.Controls.Add(Me.GroupBoxFind)
Me.Controls.Add(Me.MenuStripMain)
Me.Font = Nothing
Me.Icon = Nothing
Me.MainMenuStrip = Me.MenuStripMain
Me.Name = "FormMain"
Me.MenuStripMain.ResumeLayout(False)
Me.MenuStripMain.PerformLayout()
CType(Me.DataGridViewMedia, System.ComponentModel.ISupportInitialize).EndInit()
Me.StatusStripMain.ResumeLayout(False)
Me.StatusStripMain.PerformLayout()
Me.GroupBoxFind.ResumeLayout(False)
Me.GroupBoxFind.PerformLayout()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents MenuStripMain As System.Windows.Forms.MenuStrip
Friend WithEvents FileToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents QuitToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents DataGridViewMedia As System.Windows.Forms.DataGridView
Friend WithEvents EditToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents MediaDatabaseInExcelToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents PrintSelectedItemsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator1 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents SaveDatabaseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents RefreshDatabaseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator2 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents ViewRawDatabaseToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents StatusStripMain As System.Windows.Forms.StatusStrip
Friend WithEvents ToolStripStatusLabelVersion As System.Windows.Forms.ToolStripStatusLabel
Friend WithEvents ToolStripStatusLabelLastUpdated As System.Windows.Forms.ToolStripStatusLabel
Friend WithEvents ToolStripStatusLabelTotalItems As System.Windows.Forms.ToolStripStatusLabel
Friend WithEvents GroupBoxFind As System.Windows.Forms.GroupBox
Friend WithEvents ViewToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents FindToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents TextBoxFind As System.Windows.Forms.TextBox
Friend WithEvents ComboBoxField As System.Windows.Forms.ComboBox
Friend WithEvents ButtonFind As System.Windows.Forms.Button
Friend WithEvents ButtonFindClear As System.Windows.Forms.Button
Friend WithEvents ButtonFindHide As System.Windows.Forms.Button
Friend WithEvents ToolStripSeparator3 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents DeleteSelectedItemsToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents EditSelectedItemToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator4 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents AddItemToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents ToolStripSeparator5 As System.Windows.Forms.ToolStripSeparator
Friend WithEvents PreferencesToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents HelpToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
Friend WithEvents AboutToolStripMenuItem As System.Windows.Forms.ToolStripMenuItem
End Class
|
georgw777/MediaManager
|
MediaManager/FormMain.Designer.vb
|
Visual Basic
|
mit
| 24,880
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class AppSettings
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(AppSettings))
Me.SuspendLayout()
'
'AppSettings
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(586, 243)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.MaximizeBox = False
Me.MinimizeBox = False
Me.Name = "AppSettings"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "AppSettings"
Me.TopMost = True
Me.ResumeLayout(False)
End Sub
End Class
|
TheJaydox/TDM_BatchBackupTool
|
VS_Files/BackupTool/AppSettings.Designer.vb
|
Visual Basic
|
mit
| 1,750
|
Namespace Data
Public Interface IWatcher
Inherits IDisposable
Event Changed()
Sub Start()
Sub [Stop]()
End Interface
End Namespace
|
nublet/DMS
|
DMS.Base/Data/DBWatcher/IWatcher.vb
|
Visual Basic
|
mit
| 178
|
Imports PlayerIOClient
Public NotInheritable Class RefreshShopReceiveMessage
Inherits ReceiveMessage
'No arguments; this is just a request to refresh the shop on the client-side.
Friend Sub New(message As Message)
MyBase.New(message)
End Sub
End Class
|
TeamEEDev/EECloud
|
EECloud.API/Messages/Receive/RefreshShopReceiveMessage.vb
|
Visual Basic
|
mit
| 282
|
Option Infer On
Imports System
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim revolvedProtrusions As SolidEdgePart.RevolvedProtrusions = Nothing
Dim revolvedProtrusion As SolidEdgePart.RevolvedProtrusion = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
revolvedProtrusions = model.RevolvedProtrusions
For i As Integer = 1 To revolvedProtrusions.Count
revolvedProtrusion = revolvedProtrusions.Item(i)
Dim showDimensions = revolvedProtrusion.ShowDimensions
Next i
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.RevolvedProtrusion.ShowDimensions.vb
|
Visual Basic
|
mit
| 1,755
|
Imports System.Data.OleDb
Public Class Form4
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
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
'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.
Friend WithEvents pbSeat29b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat29a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat28b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat28a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat27b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat27a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat26b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat26a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat25b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat25a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat24b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat24a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat23b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat23a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat22b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat22a As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat21b As System.Windows.Forms.PictureBox
Friend WithEvents pbSeat21a As System.Windows.Forms.PictureBox
Friend WithEvents PictureBox1 As System.Windows.Forms.PictureBox
Friend WithEvents Button2 As System.Windows.Forms.Button
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
Friend WithEvents Button1 As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form4))
Me.pbSeat29b = New System.Windows.Forms.PictureBox
Me.pbSeat29a = New System.Windows.Forms.PictureBox
Me.pbSeat28b = New System.Windows.Forms.PictureBox
Me.pbSeat28a = New System.Windows.Forms.PictureBox
Me.pbSeat27b = New System.Windows.Forms.PictureBox
Me.pbSeat27a = New System.Windows.Forms.PictureBox
Me.pbSeat26b = New System.Windows.Forms.PictureBox
Me.pbSeat26a = New System.Windows.Forms.PictureBox
Me.pbSeat25b = New System.Windows.Forms.PictureBox
Me.pbSeat25a = New System.Windows.Forms.PictureBox
Me.pbSeat24b = New System.Windows.Forms.PictureBox
Me.pbSeat24a = New System.Windows.Forms.PictureBox
Me.pbSeat23b = New System.Windows.Forms.PictureBox
Me.pbSeat23a = New System.Windows.Forms.PictureBox
Me.pbSeat22b = New System.Windows.Forms.PictureBox
Me.pbSeat22a = New System.Windows.Forms.PictureBox
Me.pbSeat21b = New System.Windows.Forms.PictureBox
Me.pbSeat21a = New System.Windows.Forms.PictureBox
Me.PictureBox1 = New System.Windows.Forms.PictureBox
Me.Button2 = New System.Windows.Forms.Button
Me.TextBox1 = New System.Windows.Forms.TextBox
Me.Label1 = New System.Windows.Forms.Label
Me.Label2 = New System.Windows.Forms.Label
Me.TextBox2 = New System.Windows.Forms.TextBox
Me.Button1 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'pbSeat29b
'
Me.pbSeat29b.BackColor = System.Drawing.Color.Lime
Me.pbSeat29b.Location = New System.Drawing.Point(112, 510)
Me.pbSeat29b.Name = "pbSeat29b"
Me.pbSeat29b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat29b.TabIndex = 38
Me.pbSeat29b.TabStop = False
'
'pbSeat29a
'
Me.pbSeat29a.BackColor = System.Drawing.Color.Lime
Me.pbSeat29a.Location = New System.Drawing.Point(80, 510)
Me.pbSeat29a.Name = "pbSeat29a"
Me.pbSeat29a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat29a.TabIndex = 37
Me.pbSeat29a.TabStop = False
'
'pbSeat28b
'
Me.pbSeat28b.BackColor = System.Drawing.Color.Lime
Me.pbSeat28b.Location = New System.Drawing.Point(112, 486)
Me.pbSeat28b.Name = "pbSeat28b"
Me.pbSeat28b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat28b.TabIndex = 36
Me.pbSeat28b.TabStop = False
'
'pbSeat28a
'
Me.pbSeat28a.BackColor = System.Drawing.Color.Lime
Me.pbSeat28a.Location = New System.Drawing.Point(80, 486)
Me.pbSeat28a.Name = "pbSeat28a"
Me.pbSeat28a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat28a.TabIndex = 35
Me.pbSeat28a.TabStop = False
'
'pbSeat27b
'
Me.pbSeat27b.BackColor = System.Drawing.Color.Lime
Me.pbSeat27b.Location = New System.Drawing.Point(112, 462)
Me.pbSeat27b.Name = "pbSeat27b"
Me.pbSeat27b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat27b.TabIndex = 34
Me.pbSeat27b.TabStop = False
'
'pbSeat27a
'
Me.pbSeat27a.BackColor = System.Drawing.Color.Lime
Me.pbSeat27a.Location = New System.Drawing.Point(80, 462)
Me.pbSeat27a.Name = "pbSeat27a"
Me.pbSeat27a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat27a.TabIndex = 33
Me.pbSeat27a.TabStop = False
'
'pbSeat26b
'
Me.pbSeat26b.BackColor = System.Drawing.Color.Lime
Me.pbSeat26b.Location = New System.Drawing.Point(112, 430)
Me.pbSeat26b.Name = "pbSeat26b"
Me.pbSeat26b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat26b.TabIndex = 32
Me.pbSeat26b.TabStop = False
'
'pbSeat26a
'
Me.pbSeat26a.BackColor = System.Drawing.Color.Lime
Me.pbSeat26a.Location = New System.Drawing.Point(80, 430)
Me.pbSeat26a.Name = "pbSeat26a"
Me.pbSeat26a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat26a.TabIndex = 31
Me.pbSeat26a.TabStop = False
'
'pbSeat25b
'
Me.pbSeat25b.BackColor = System.Drawing.Color.Lime
Me.pbSeat25b.Location = New System.Drawing.Point(112, 406)
Me.pbSeat25b.Name = "pbSeat25b"
Me.pbSeat25b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat25b.TabIndex = 30
Me.pbSeat25b.TabStop = False
'
'pbSeat25a
'
Me.pbSeat25a.BackColor = System.Drawing.Color.Lime
Me.pbSeat25a.Location = New System.Drawing.Point(80, 406)
Me.pbSeat25a.Name = "pbSeat25a"
Me.pbSeat25a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat25a.TabIndex = 29
Me.pbSeat25a.TabStop = False
'
'pbSeat24b
'
Me.pbSeat24b.BackColor = System.Drawing.Color.Lime
Me.pbSeat24b.Location = New System.Drawing.Point(112, 382)
Me.pbSeat24b.Name = "pbSeat24b"
Me.pbSeat24b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat24b.TabIndex = 28
Me.pbSeat24b.TabStop = False
'
'pbSeat24a
'
Me.pbSeat24a.BackColor = System.Drawing.Color.Lime
Me.pbSeat24a.Location = New System.Drawing.Point(80, 382)
Me.pbSeat24a.Name = "pbSeat24a"
Me.pbSeat24a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat24a.TabIndex = 27
Me.pbSeat24a.TabStop = False
'
'pbSeat23b
'
Me.pbSeat23b.BackColor = System.Drawing.Color.Lime
Me.pbSeat23b.Location = New System.Drawing.Point(112, 358)
Me.pbSeat23b.Name = "pbSeat23b"
Me.pbSeat23b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat23b.TabIndex = 26
Me.pbSeat23b.TabStop = False
'
'pbSeat23a
'
Me.pbSeat23a.BackColor = System.Drawing.Color.Lime
Me.pbSeat23a.Location = New System.Drawing.Point(80, 358)
Me.pbSeat23a.Name = "pbSeat23a"
Me.pbSeat23a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat23a.TabIndex = 25
Me.pbSeat23a.TabStop = False
'
'pbSeat22b
'
Me.pbSeat22b.BackColor = System.Drawing.Color.Lime
Me.pbSeat22b.Location = New System.Drawing.Point(112, 334)
Me.pbSeat22b.Name = "pbSeat22b"
Me.pbSeat22b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat22b.TabIndex = 24
Me.pbSeat22b.TabStop = False
'
'pbSeat22a
'
Me.pbSeat22a.BackColor = System.Drawing.Color.Lime
Me.pbSeat22a.Location = New System.Drawing.Point(80, 334)
Me.pbSeat22a.Name = "pbSeat22a"
Me.pbSeat22a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat22a.TabIndex = 23
Me.pbSeat22a.TabStop = False
'
'pbSeat21b
'
Me.pbSeat21b.BackColor = System.Drawing.Color.Lime
Me.pbSeat21b.Location = New System.Drawing.Point(112, 310)
Me.pbSeat21b.Name = "pbSeat21b"
Me.pbSeat21b.Size = New System.Drawing.Size(16, 16)
Me.pbSeat21b.TabIndex = 22
Me.pbSeat21b.TabStop = False
'
'pbSeat21a
'
Me.pbSeat21a.BackColor = System.Drawing.Color.Lime
Me.pbSeat21a.Location = New System.Drawing.Point(80, 310)
Me.pbSeat21a.Name = "pbSeat21a"
Me.pbSeat21a.Size = New System.Drawing.Size(16, 16)
Me.pbSeat21a.TabIndex = 21
Me.pbSeat21a.TabStop = False
'
'PictureBox1
'
Me.PictureBox1.BackColor = System.Drawing.Color.Transparent
Me.PictureBox1.Image = CType(resources.GetObject("PictureBox1.Image"), System.Drawing.Image)
Me.PictureBox1.Location = New System.Drawing.Point(2, 66)
Me.PictureBox1.Name = "PictureBox1"
Me.PictureBox1.Size = New System.Drawing.Size(196, 596)
Me.PictureBox1.TabIndex = 20
Me.PictureBox1.TabStop = False
'
'Button2
'
Me.Button2.BackColor = System.Drawing.Color.Transparent
Me.Button2.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.Button2.Location = New System.Drawing.Point(892, 598)
Me.Button2.Name = "Button2"
Me.Button2.Size = New System.Drawing.Size(88, 56)
Me.Button2.TabIndex = 39
Me.Button2.Text = "EXIT"
'
'TextBox1
'
Me.TextBox1.Location = New System.Drawing.Point(0, 40)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New System.Drawing.Size(198, 22)
Me.TextBox1.TabIndex = 40
Me.TextBox1.Text = ""
'
'Label1
'
Me.Label1.BackColor = System.Drawing.Color.Transparent
Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.ForeColor = System.Drawing.Color.White
Me.Label1.Location = New System.Drawing.Point(6, 6)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(196, 28)
Me.Label1.TabIndex = 111
Me.Label1.Text = "Flight Number"
Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'Label2
'
Me.Label2.BackColor = System.Drawing.Color.Transparent
Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.8!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label2.ForeColor = System.Drawing.Color.White
Me.Label2.Location = New System.Drawing.Point(210, 6)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(196, 28)
Me.Label2.TabIndex = 113
Me.Label2.Text = "Seat Number"
Me.Label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'TextBox2
'
Me.TextBox2.Location = New System.Drawing.Point(206, 40)
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New System.Drawing.Size(198, 22)
Me.TextBox2.TabIndex = 112
Me.TextBox2.Text = ""
'
'Button1
'
Me.Button1.BackColor = System.Drawing.Color.Transparent
Me.Button1.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
Me.Button1.Location = New System.Drawing.Point(892, 538)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(88, 56)
Me.Button1.TabIndex = 114
Me.Button1.Text = "PICK SEAT"
'
'Form4
'
Me.AutoScaleBaseSize = New System.Drawing.Size(6, 15)
Me.BackColor = System.Drawing.Color.Yellow
Me.BackgroundImage = CType(resources.GetObject("$this.BackgroundImage"), System.Drawing.Image)
Me.ClientSize = New System.Drawing.Size(992, 664)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.TextBox2)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.Button2)
Me.Controls.Add(Me.pbSeat29b)
Me.Controls.Add(Me.pbSeat29a)
Me.Controls.Add(Me.pbSeat28b)
Me.Controls.Add(Me.pbSeat28a)
Me.Controls.Add(Me.pbSeat27b)
Me.Controls.Add(Me.pbSeat27a)
Me.Controls.Add(Me.pbSeat26b)
Me.Controls.Add(Me.pbSeat26a)
Me.Controls.Add(Me.pbSeat25b)
Me.Controls.Add(Me.pbSeat25a)
Me.Controls.Add(Me.pbSeat24b)
Me.Controls.Add(Me.pbSeat24a)
Me.Controls.Add(Me.pbSeat23b)
Me.Controls.Add(Me.pbSeat23a)
Me.Controls.Add(Me.pbSeat22b)
Me.Controls.Add(Me.pbSeat22a)
Me.Controls.Add(Me.pbSeat21b)
Me.Controls.Add(Me.pbSeat21a)
Me.Controls.Add(Me.PictureBox1)
Me.Name = "Form4"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "Beech"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddHandler pbSeat21a.Click, AddressOf whatever
AddHandler pbSeat21b.Click, AddressOf whatever
AddHandler pbSeat22a.Click, AddressOf whatever
AddHandler pbSeat22b.Click, AddressOf whatever
AddHandler pbSeat23a.Click, AddressOf whatever
AddHandler pbSeat23b.Click, AddressOf whatever
AddHandler pbSeat24a.Click, AddressOf whatever
AddHandler pbSeat24b.Click, AddressOf whatever
AddHandler pbSeat25a.Click, AddressOf whatever
AddHandler pbSeat25b.Click, AddressOf whatever
AddHandler pbSeat26a.Click, AddressOf whatever
AddHandler pbSeat26b.Click, AddressOf whatever
AddHandler pbSeat27a.Click, AddressOf whatever
AddHandler pbSeat27b.Click, AddressOf whatever
AddHandler pbSeat28a.Click, AddressOf whatever
AddHandler pbSeat28b.Click, AddressOf whatever
AddHandler pbSeat29a.Click, AddressOf whatever
AddHandler pbSeat29b.Click, AddressOf whatever
Dim objConnection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\cis430.mdb;")
Dim objcommand As New OleDbCommand("select seatnbr from reservations", objConnection)
Dim objAdapter As New OleDbDataAdapter
Dim objDataSet As New DataSet
'get the seat numbers out of the query results
Dim objRow As DataRow
Dim strcontrolname As String
Dim objcontrol As Control
objcommand.Connection.Open()
objAdapter.SelectCommand = objcommand
objAdapter.Fill(objDataSet)
PictureBox1.Image = Image.FromFile("c:\beh.gif")
'dim strselect case picturebox1.
For Each objRow In objDataSet.Tables(0).Rows
'control name is 'pbseat' followed by actual seat number
strcontrolname = "pbSeat2" & objRow(0)
objcontrol = getControl(strcontrolname)
objcontrol.BackColor = System.Drawing.Color.Gray
Next
End Sub
Private Function getControl(ByVal strcontrolname As String) As Control
Dim objcontrol As Control
For Each objcontrol In Me.Controls
If objcontrol.Name = strcontrolname Then
Return objcontrol
End If
Next
Return Nothing
End Function
Private Sub whatever(ByVal sender As System.Object, ByVal e As System.EventArgs)
Dim objcontrol As Control
Dim strcontrolname As String
strcontrolname = sender.name
objcontrol = getControl(strcontrolname)
objcontrol.BackColor = System.Drawing.Color.Orange
TextBox2.Text = sender.name
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Application.Exit()
End Sub
Public Property CustomerName() As String
Get
Return TextBox1.Text
End Get
Set(ByVal Value As String)
TextBox1.Text = Value
End Set
End Property
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myForm6 As New Form6
myForm6.SeatNum = TextBox2.Text
myForm6.FlightNum = TextBox1.Text
myForm6.Visible = True
Me.Visible = False
End Sub
End Class
|
AndrewSomorjai/flight__system
|
startmain/Form4.vb
|
Visual Basic
|
mit
| 18,359
|
#Region "License"
' The MIT License (MIT)
'
' Copyright (c) 2018 Richard L King (TradeWright Software Systems)
'
' 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.
#End Region
Imports System.Collections.Generic
Public Class ContractDescription
Public ReadOnly Property Contract As Contract
Public ReadOnly Property DerivativeSecTypes As List(Of String)
Private Sub New()
End Sub
Public Sub New(contract As Contract, derivativeSecTypes As List(Of String))
Me.Contract = contract
Me.DerivativeSecTypes = derivativeSecTypes
End Sub
Public Overrides Function ToString() As String
Return $"{Contract.ToString()}: derivativeSecTypes [{String.Join(", ", DerivativeSecTypes)}]"
End Function
End Class
|
tradewright/tradewright-twsapi
|
src/IBApi/ApiTypes/ContractDescription.vb
|
Visual Basic
|
mit
| 1,766
|
'------------------------------------------------------------------------------
' <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("u1p1e2.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
|
ikerlorente11/Egibide
|
DAM/2-Desarrollo-de-aplicaciones-multiplataforma-master/DI/Ejercicios/Tema1/Unidad1/u1p1e2/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,711
|
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:2.0.50727.42
'
' 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("VBSimpleTableDesign.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
|
AndreKuzubov/Easy_Report
|
packages/Independentsoft.Office.Word.2.0.400/Tutorial/VBSimpleTableDesign/My Project/Resources.Designer.vb
|
Visual Basic
|
apache-2.0
| 2,743
|
' Copyright 2016 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 Esri.ArcGISRuntime.Data
Imports Esri.ArcGISRuntime.Tasks
Imports Esri.ArcGISRuntime.Tasks.Geoprocessing
Imports System.Windows
Namespace ListGeodatabaseVersions
Public Class ListGeodatabaseVersionsVB
' Url to used geoprocessing service
Private Const ListVersionsUrl As String = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/GDBVersions/GPServer/ListVersions"
Public Sub New()
InitializeComponent()
' Create the UI, setup the control references and execute initialization
Initialize()
End Sub
Private Async Sub Initialize()
' Set the UI to indicate that the geoprocessing is running
SetBusy(True)
' Get versions from a geodatabase
Dim versionsFeatureSet As IFeatureSet = Await GetGeodatabaseVersionsAsync()
' Continue if we got a valid geoprocessing result
If versionsFeatureSet IsNot Nothing Then
' Create a string builder to hold all of the information from the geoprocessing
' task to display in the UI
Dim myStringBuilder = New System.Text.StringBuilder()
' Loop through each Feature in the FeatureSet
For Each version In versionsFeatureSet
' Get the attributes (a dictionary of <key,value> pairs) from the Feature
Dim myDictionary = version.Attributes
' Loop through each attribute (a <key,value> pair)
For Each oneAttribute In myDictionary
' Get the key
Dim myKey As String = oneAttribute.Key
' Get the value
Dim myValue As Object = oneAttribute.Value
If myKey IsNot Nothing And myValue IsNot Nothing Then
' Add the key and value strings to the string builder
myStringBuilder.AppendLine(myKey.ToString & ": " & myValue.ToString)
End If
Next oneAttribute
' Add a blank line after each Feature (the listing of geodatabase versions)
myStringBuilder.AppendLine()
Next version
' Display the result in the textbox
theTextBox.Text = myStringBuilder.ToString()
End If
' Set the UI to indicate that the geoprocessing is not running
SetBusy(False)
End Sub
Private Async Function GetGeodatabaseVersionsAsync() As Task(Of IFeatureSet)
' Results will be returned as a feature set
Dim results As IFeatureSet = Nothing
' Create new geoprocessing task
Dim listVersionsTask = New GeoprocessingTask(New Uri(ListVersionsUrl))
' Create parameters that are passed to the used geoprocessing task
Dim listVersionsParameters As New GeoprocessingParameters(GeoprocessingExecutionType.SynchronousExecute)
' Create job that handles the communication between the application and the geoprocessing task
Dim listVersionsJob = listVersionsTask.CreateJob(listVersionsParameters)
Try
' Execute analysis and wait for the results
Dim analysisResult As GeoprocessingResult = Await listVersionsJob.GetResultAsync()
' Get results from the outputs
Dim listVersionsResults As GeoprocessingFeatures = TryCast(analysisResult.Outputs("Versions"), GeoprocessingFeatures)
' Set results
results = listVersionsResults.Features
Catch ex As Exception
' Error handling if something goes wrong
If listVersionsJob.Status = JobStatus.Failed AndAlso listVersionsJob.Error IsNot Nothing Then
MessageBox.Show("Executing geoprocessing failed. " & listVersionsJob.Error.Message, "Geoprocessing error")
Else
MessageBox.Show("An error occurred. " & ex.ToString(), "Sample error")
End If
Finally
' Set the UI to indicate that the geoprocessing is not running
SetBusy(False)
End Try
Return results
End Function
Private Sub SetBusy(Optional ByVal isBusy As Boolean = True)
If isBusy Then
' Change UI to indicate that the geoprocessing is running
busyOverlay.Visibility = Visibility.Visible
progress.IsIndeterminate = True
Else
' Change UI to indicate that the geoprocessing is not running
busyOverlay.Visibility = Visibility.Collapsed
progress.IsIndeterminate = False
End If
End Sub
End Class
End Namespace
|
Arc3D/arcgis-runtime-samples-dotnet
|
src/WPF/ArcGISRuntime.WPF.Samples/Samples/Geoprocessing/ListGeodatabaseVersions/ListGeodatabaseVersionsVB.xaml.vb
|
Visual Basic
|
apache-2.0
| 5,511
|
' 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.[Shared].Collections
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(previousToken As SyntaxToken,
node As UsingBlockSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.UsingStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
|
eriawan/roslyn
|
src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb
|
Visual Basic
|
apache-2.0
| 1,248
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects.Physical
Public Class ReceptiveField
Inherits Framework.DataObject
#Region " Attributes "
Protected m_vVertex As Vec3d
Protected m_aryPairs As New Collections.SortedReceptiveFieldPairs(Me)
#End Region
#Region " Properties "
<Browsable(False)> _
Public Overridable Property Vertex() As Vec3d
Get
Return m_vVertex
End Get
Set(ByVal Value As Vec3d)
m_vVertex = Value
End Set
End Property
<Browsable(False)> _
Public Overridable ReadOnly Property FieldPairs() As Collections.SortedReceptiveFieldPairs
Get
Return m_aryPairs
End Get
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As Framework.DataObject)
MyBase.New(doParent)
End Sub
Public Sub New(ByVal doParent As Framework.DataObject, ByVal vVertex As Vec3d)
MyBase.New(doParent)
m_vVertex = vVertex
End Sub
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
End Sub
Public Overrides Function Clone(ByVal doParent As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject) As AnimatGUI.Framework.DataObject
Dim doNewRF As New ReceptiveField(doParent, m_vVertex)
Return doNewRF
End Function
#Region " Add-Remove to List Methods "
Public Overrides Sub AddToSim(ByVal bThrowError As Boolean, Optional ByVal bDoNotInit As Boolean = False)
If Not m_doParent Is Nothing Then
Util.Application.SimulationInterface.AddItem(m_doParent.ID, "ReceptiveField", Me.ID, Me.GetSimulationXml("ReceptiveField"), bThrowError, bDoNotInit)
InitializeSimulationReferences()
End If
End Sub
Public Overrides Sub RemoveFromSim(ByVal bThrowError As Boolean)
If Not m_doInterface Is Nothing AndAlso Not m_doParent Is Nothing Then
Util.Application.SimulationInterface.RemoveItem(m_doParent.ID, "ReceptiveField", Me.ID, bThrowError)
End If
m_doInterface = Nothing
End Sub
#End Region
Public Overridable Overloads Sub LoadData(ByRef doStructure As DataObjects.Physical.PhysicalStructure, ByVal oXml As ManagedAnimatInterfaces.IStdXml)
m_aryPairs.Clear()
oXml.IntoElem()
m_vVertex = Util.LoadVec3d(oXml, "Vertex", Nothing)
oXml.OutOfElem()
End Sub
Public Overridable Overloads Sub SaveData(ByRef doStructure As DataObjects.Physical.PhysicalStructure, ByVal oXml As ManagedAnimatInterfaces.IStdXml)
oXml.AddChildElement("ReceptiveField")
oXml.IntoElem()
oXml.AddChildElement("ID", m_strID)
Util.SaveVector(oXml, "Vertex", m_vVertex)
oXml.OutOfElem()
End Sub
Public Overrides Sub SaveSimulationXml(ByVal oXml As ManagedAnimatInterfaces.IStdXml, Optional ByRef nmParentControl As AnimatGUI.Framework.DataObject = Nothing, Optional ByVal strName As String = "")
oXml.AddChildElement("ReceptiveField")
oXml.IntoElem()
oXml.AddChildElement("ID", m_strID)
Util.SaveVector(oXml, "Vertex", m_vVertex)
oXml.OutOfElem()
End Sub
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/AnimatGUI/DataObjects/Physical/ReceptiveField.vb
|
Visual Basic
|
bsd-3-clause
| 3,944
|
Imports System
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Diagnostics
Imports System.IO
Imports System.Xml
Imports AnimatGuiCtrls.Controls
Imports AnimatGUI.Framework
Namespace DataObjects.Physical
Public Class Light
Inherits MovableItem
#Region " Delegates "
#End Region
#Region " Attributes "
Protected m_snRadius As AnimatGUI.Framework.ScaledNumber
Protected m_fltConstantAttenuation As Single = 0
Protected m_snLinearAttenuationDistance As AnimatGUI.Framework.ScaledNumber
Protected m_snQuadraticAttenuationDistance As AnimatGUI.Framework.ScaledNumber
Protected m_iLatitudeSegments As Integer = 10
Protected m_iLongtitudeSegments As Integer = 10
#End Region
#Region " Properties "
<Browsable(False)> _
Public Overrides ReadOnly Property WorkspaceImageName() As String
Get
Return "AnimatGUI.Lightbulb_Small.gif"
End Get
End Property
<Browsable(False)> _
Public Overrides ReadOnly Property StructureID() As String
Get
Return ""
End Get
End Property
<Browsable(False)> _
Public Overrides ReadOnly Property DefaultVisualSelectionMode() As Simulation.enumVisualSelectionMode
Get
Return Simulation.enumVisualSelectionMode.SelectGraphics
End Get
End Property
Public Overridable Property Radius() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snRadius
End Get
Set(ByVal value As AnimatGUI.Framework.ScaledNumber)
If value.ActualValue <= 0 Then
Throw New System.Exception("The Radius of the Sphere cannot be less than or equal to zero.")
End If
SetSimData("Radius", value.ActualValue.ToString, True)
m_snRadius.CopyData(value)
End Set
End Property
Public Overridable Property LatitudeSegments() As Integer
Get
Return m_iLatitudeSegments
End Get
Set(ByVal value As Integer)
If value < 10 Then
Throw New System.Exception("The number of latitude segments for the sphere cannot be less than ten.")
End If
SetSimData("LatitudeSegments", value.ToString, True)
m_iLatitudeSegments = value
End Set
End Property
Public Overridable Property LongtitudeSegments() As Integer
Get
Return m_iLongtitudeSegments
End Get
Set(ByVal value As Integer)
If value < 10 Then
Throw New System.Exception("The number of longtitude segments for the sphere cannot be less than ten.")
End If
SetSimData("LongtitudeSegments", value.ToString, True)
m_iLongtitudeSegments = value
End Set
End Property
Public Overridable Property ConstantAttenuation() As Single
Get
Return m_fltConstantAttenuation
End Get
Set(ByVal value As Single)
If value < 0 OrElse value > 1 Then
Throw New System.Exception("The constant attenuation ratio must be between 0 and 1.")
End If
SetSimData("ConstantAttenuation", value.ToString, True)
m_fltConstantAttenuation = value
End Set
End Property
Public Overridable Property LinearAttenuationDistance() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snLinearAttenuationDistance
End Get
Set(ByVal value As AnimatGUI.Framework.ScaledNumber)
If value.ActualValue < 0 Then
Throw New System.Exception("The linear attenuation distance cannot be less than zero.")
End If
SetSimData("LinearAttenuationDistance", value.ActualValue.ToString, True)
m_snLinearAttenuationDistance.CopyData(value)
End Set
End Property
Public Overridable Property QuadraticAttenuationDistance() As AnimatGUI.Framework.ScaledNumber
Get
Return m_snQuadraticAttenuationDistance
End Get
Set(ByVal value As AnimatGUI.Framework.ScaledNumber)
If value.ActualValue < 0 Then
Throw New System.Exception("The quadratic attenuation distance cannot be less than zero.")
End If
SetSimData("QuadraticAttenuationDistance", value.ActualValue.ToString, True)
m_snQuadraticAttenuationDistance.CopyData(value)
End Set
End Property
#End Region
#Region " Methods "
Public Sub New(ByVal doParent As Framework.DataObject)
MyBase.New(doParent)
m_svLocalPosition.CopyData(1, 10, 0, True)
m_clAmbient = Color.FromArgb(255, 255, 255, 255)
m_clDiffuse = Color.FromArgb(255, 255, 255, 255)
m_clSpecular = Color.FromArgb(255, 255, 255, 255)
m_snRadius = New AnimatGUI.Framework.ScaledNumber(Me, "Radius", "meters", "m")
m_snLinearAttenuationDistance = New AnimatGUI.Framework.ScaledNumber(Me, "LinearAttenuationDistance", "meters", "m")
m_snQuadraticAttenuationDistance = New AnimatGUI.Framework.ScaledNumber(Me, "QuadraticAttenuationDistance", "meters", "m")
If Not Util.Environment Is Nothing Then
m_snRadius.ActualValue = 0.5 * Util.Environment.DistanceUnitValue
m_snLinearAttenuationDistance.ActualValue = 0
m_snQuadraticAttenuationDistance.ActualValue = 10000 * Util.Environment.DistanceUnitValue
End If
End Sub
Public Overrides Sub BuildProperties(ByRef propTable As AnimatGuiCtrls.Controls.PropertyTable)
MyBase.BuildProperties(propTable)
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Enabled", GetType(Boolean), "Enabled", _
"Part Properties", "Determines if this light is enabled or not.", m_bEnabled))
Dim pbNumberBag As AnimatGuiCtrls.Controls.PropertyBag
pbNumberBag = m_snRadius.Properties
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Radius", pbNumberBag.GetType(), "Radius", _
"Size", "Sets the radius of the light sphere.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Latitude Segments", Me.LatitudeSegments.GetType(), "LatitudeSegments", _
"Size", "The number of segments along the latitude direction used to draw the light sphere.", Me.LatitudeSegments))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Longtitude Segments", Me.LongtitudeSegments.GetType(), "LongtitudeSegments", _
"Size", "The number of segments along the longtitude direction used to draw the light sphere.", Me.LongtitudeSegments))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Linear Distance", pbNumberBag.GetType(), "LinearAttenuationDistance", _
"Attenuation", "This is the distance at which the light intensity is halved using a linear equation. Set to zero to disable this attenuation.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Quadratic Distance", pbNumberBag.GetType(), "QuadraticAttenuationDistance", _
"Attenuation", "This is the distance at which the light intensity is halved using a quadratic equation. Set to zero to disable this attenuation.", pbNumberBag, _
"", GetType(AnimatGUI.Framework.ScaledNumber.ScaledNumericPropBagConverter)))
propTable.Properties.Add(New AnimatGuiCtrls.Controls.PropertySpec("Constant Ratio", Me.ConstantAttenuation.GetType(), "ConstantAttenuation", _
"Attenuation", "A ratio for constant attenuation. This must be between 0 and 1.", Me.ConstantAttenuation))
End Sub
Public Overrides Sub ClearIsDirty()
MyBase.ClearIsDirty()
If Not m_snRadius Is Nothing Then m_snRadius.ClearIsDirty()
If Not m_snLinearAttenuationDistance Is Nothing Then m_snLinearAttenuationDistance.ClearIsDirty()
If Not m_snQuadraticAttenuationDistance Is Nothing Then m_snQuadraticAttenuationDistance.ClearIsDirty()
End Sub
Protected Overrides Sub CloneInternal(ByVal doOriginal As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject)
MyBase.CloneInternal(doOriginal, bCutData, doRoot)
Dim doOrig As AnimatGUI.DataObjects.Physical.Light = DirectCast(doOriginal, Light)
m_snRadius = DirectCast(doOrig.m_snRadius.Clone(Me, bCutData, doRoot), AnimatGUI.Framework.ScaledNumber)
m_fltConstantAttenuation = doOrig.m_fltConstantAttenuation
m_snLinearAttenuationDistance = DirectCast(doOrig.m_snLinearAttenuationDistance.Clone(Me, bCutData, doRoot), AnimatGUI.Framework.ScaledNumber)
m_snQuadraticAttenuationDistance = DirectCast(doOrig.m_snQuadraticAttenuationDistance.Clone(Me, bCutData, doRoot), AnimatGUI.Framework.ScaledNumber)
m_iLatitudeSegments = doOrig.m_iLatitudeSegments
m_iLongtitudeSegments = doOrig.m_iLongtitudeSegments
End Sub
Public Overrides Function Clone(ByVal doParent As AnimatGUI.Framework.DataObject, ByVal bCutData As Boolean, _
ByVal doRoot As AnimatGUI.Framework.DataObject) As AnimatGUI.Framework.DataObject
Dim doItem As New Light(doParent)
doItem.CloneInternal(Me, bCutData, doRoot)
If Not doRoot Is Nothing AndAlso doRoot Is Me Then doItem.AfterClone(Me, bCutData, doRoot, doItem)
Return doItem
End Function
Public Overrides Sub SetupInitialTransparencies()
If Not m_Transparencies Is Nothing Then
m_Transparencies.GraphicsTransparency = 50
m_Transparencies.CollisionsTransparency = 50
m_Transparencies.JointsTransparency = 50
m_Transparencies.ReceptiveFieldsTransparency = 50
m_Transparencies.SimulationTransparency = 100
End If
End Sub
Public Overrides Sub CreateWorkspaceTreeView(ByVal doParent As Framework.DataObject, _
ByVal tnParentNode As Crownwood.DotNetMagic.Controls.Node, _
Optional ByVal bRootObject As Boolean = False)
If m_tnWorkspaceNode Is Nothing AndAlso (bRootObject OrElse (Not bRootObject AndAlso Not tnParentNode Is Nothing)) Then
m_tnWorkspaceNode = Util.ProjectWorkspace.AddTreeNode(Util.Environment.LightsTreeNode, Me.Name, Me.WorkspaceImageName)
m_tnWorkspaceNode.Tag = Me
If Me.Enabled Then
m_tnWorkspaceNode.BackColor = Color.White
Else
m_tnWorkspaceNode.BackColor = Color.Gray
End If
End If
End Sub
Public Overrides Function WorkspaceTreeviewPopupMenu(ByRef tnSelectedNode As Crownwood.DotNetMagic.Controls.Node, ByVal ptPoint As Point) As Boolean
If tnSelectedNode Is m_tnWorkspaceNode Then
Dim mcDelete As New System.Windows.Forms.ToolStripMenuItem("Delete Light", Util.Application.ToolStripImages.GetImage("AnimatGUI.Delete.gif"), New EventHandler(AddressOf Util.Application.OnDeleteFromWorkspace))
' Create the popup menu object
Dim popup As New AnimatContextMenuStrip("AnimatGUI.DataObjects.Charting.DataColumn.WorkspaceTreeviewPopupMenu", Util.SecurityMgr)
popup.Items.AddRange(New System.Windows.Forms.ToolStripItem() {mcDelete})
Util.ProjectWorkspace.ctrlTreeView.ContextMenuNode = popup
Return True
End If
Return False
End Function
Public Overrides Function Delete(Optional ByVal bAskToDelete As Boolean = True, Optional ByVal e As Crownwood.DotNetMagic.Controls.TGCloseRequestEventArgs = Nothing) As Boolean
Try
If Not bAskToDelete OrElse (bAskToDelete AndAlso Util.ShowMessage("Are you certain that you want to permanently delete this " & _
"light?", "Delete Light", MessageBoxButtons.YesNo) = DialogResult.Yes) Then
Util.Application.AppIsBusy = True
Util.Environment.Lights.Remove(Me.ID)
Me.RemoveWorksapceTreeView()
Return False
End If
Return True
Catch ex As Exception
Throw ex
Finally
Util.Application.AppIsBusy = True
End Try
End Function
#Region " Load/Save Methods "
Public Overridable Overloads Sub LoadData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.LoadData(oXml)
Try
oXml.IntoElem()
m_bEnabled = oXml.GetChildBool("Enabled", m_bEnabled)
m_snRadius.LoadData(oXml, "Radius")
m_fltConstantAttenuation = oXml.GetChildFloat("ConstantAttenuation", m_fltConstantAttenuation)
m_snLinearAttenuationDistance.LoadData(oXml, "LinearAttenuationDistance", False)
m_snQuadraticAttenuationDistance.LoadData(oXml, "QuadraticAttenuationDistance", False)
m_iLatitudeSegments = oXml.GetChildInt("LatitudeSegments", m_iLatitudeSegments)
m_iLongtitudeSegments = oXml.GetChildInt("LongtitudeSegments", m_iLongtitudeSegments)
oXml.OutOfElem()
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Public Overridable Overloads Sub SaveData(ByVal oXml As ManagedAnimatInterfaces.IStdXml)
MyBase.SaveData(oXml, "Light")
Try
oXml.IntoElem()
oXml.AddChildElement("Enabled", m_bEnabled)
m_snRadius.SaveData(oXml, "Radius")
oXml.AddChildElement("ConstantAttenuation", m_fltConstantAttenuation)
m_snLinearAttenuationDistance.SaveData(oXml, "LinearAttenuationDistance")
m_snQuadraticAttenuationDistance.SaveData(oXml, "QuadraticAttenuationDistance")
oXml.AddChildElement("LatitudeSegments", m_iLatitudeSegments)
oXml.AddChildElement("LongtitudeSegments", m_iLongtitudeSegments)
oXml.OutOfElem()
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
Public Overrides Sub SaveSimulationXml(ByVal oXml As ManagedAnimatInterfaces.IStdXml, Optional ByRef nmParentControl As Framework.DataObject = Nothing, Optional ByVal strName As String = "")
MyBase.SaveSimulationXml(oXml, nmParentControl, "Light")
Try
oXml.IntoElem()
oXml.AddChildElement("Type", "Light")
oXml.AddChildElement("Enabled", m_bEnabled)
m_snRadius.SaveSimulationXml(oXml, Me, "Radius")
oXml.AddChildElement("ConstantAttenuation", m_fltConstantAttenuation)
m_snLinearAttenuationDistance.SaveSimulationXml(oXml, Me, "LinearAttenuationDistance")
m_snQuadraticAttenuationDistance.SaveSimulationXml(oXml, Me, "QuadraticAttenuationDistance")
oXml.AddChildElement("LatitudeSegments", m_iLatitudeSegments)
oXml.AddChildElement("LongtitudeSegments", m_iLongtitudeSegments)
oXml.OutOfElem()
Catch ex As System.Exception
AnimatGUI.Framework.Util.DisplayError(ex)
End Try
End Sub
#End Region
#Region " Add-Remove to List Methods "
Public Overrides Sub AddToSim(ByVal bThrowError As Boolean, Optional ByVal bDoNotInit As Boolean = False)
If Not Util.Simulation Is Nothing Then
Util.Application.SimulationInterface.AddItem(Util.Simulation.ID, "Light", Me.ID, Me.GetSimulationXml("Light"), bThrowError, bDoNotInit)
InitializeSimulationReferences()
End If
End Sub
Public Overrides Sub RemoveFromSim(ByVal bThrowError As Boolean)
If Not Util.Simulation Is Nothing AndAlso Not m_doInterface Is Nothing Then
Util.Application.SimulationInterface.RemoveItem(Util.Simulation.ID, "Light", Me.ID, bThrowError)
End If
m_doInterface = Nothing
End Sub
#End Region
#End Region
#Region " Events "
#End Region
End Class
End Namespace
|
NeuroRoboticTech/AnimatLabPublicSource
|
Libraries/AnimatGUI/DataObjects/Physical/Light.vb
|
Visual Basic
|
bsd-3-clause
| 18,065
|
' 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.Threading
Imports Microsoft.CodeAnalysis.Differencing
Imports Microsoft.CodeAnalysis.EditAndContinue
Imports Microsoft.CodeAnalysis.EditAndContinue.Contracts
Imports Microsoft.CodeAnalysis.EditAndContinue.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue.UnitTests
<[UseExportProvider]>
Public Class VisualBasicEditAndContinueAnalyzerTests
Private Shared ReadOnly s_composition As TestComposition =
EditorTestCompositions.EditorFeatures
#Region "Helpers"
Private Shared Sub TestSpans(source As String, hasLabel As Func(Of SyntaxNode, Boolean))
Dim tree = SyntaxFactory.ParseSyntaxTree(ClearSource(source))
For Each expected In GetExpectedPositionsAndSpans(source)
Dim expectedSpan = expected.Value
Dim expectedText As String = source.Substring(expectedSpan.Start, expectedSpan.Length)
Dim node = tree.GetRoot().FindToken(expected.Key).Parent
While Not hasLabel(node)
node = node.Parent
End While
Dim actualSpan = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(node.Kind, node, EditKind.Update).Value
Dim actualText = source.Substring(actualSpan.Start, actualSpan.Length)
Assert.True(expectedSpan = actualSpan, vbCrLf &
"Expected span: '" & expectedText & "' " & expectedSpan.ToString() & vbCrLf &
"Actual span: '" & actualText & "' " & actualSpan.ToString())
Next
End Sub
Private Const s_startTag As String = "<span>"
Private Const s_endTag As String = "</span>"
Private Const s_startSpanMark As String = "[|"
Private Const s_endSpanMark As String = "|]"
Private Const s_positionMark As Char = "$"c
Private Shared Function ClearSource(source As String) As String
Return source.
Replace(s_startTag, New String(" "c, s_startTag.Length)).
Replace(s_endTag, New String(" "c, s_endTag.Length)).
Replace(s_startSpanMark, New String(" "c, s_startSpanMark.Length)).
Replace(s_endSpanMark, New String(" "c, s_startSpanMark.Length)).
Replace(s_positionMark, " "c)
End Function
Private Shared Iterator Function GetExpectedPositionsAndSpans(source As String) As IEnumerable(Of KeyValuePair(Of Integer, TextSpan))
Dim i As Integer = 0
While True
Dim start As Integer = source.IndexOf(s_startTag, i, StringComparison.Ordinal)
If start = -1 Then
Exit While
End If
start += s_startTag.Length
Dim [end] As Integer = source.IndexOf(s_endTag, start + 1, StringComparison.Ordinal)
Dim length = [end] - start
Dim position = source.IndexOf(s_positionMark, start, length)
Dim span As TextSpan
If position < 0 Then
position = start
span = New TextSpan(start, length)
Else
position += 1
span = TextSpan.FromBounds(source.IndexOf(s_startSpanMark, start, length, StringComparison.Ordinal) + s_startSpanMark.Length,
source.IndexOf(s_endSpanMark, start, length, StringComparison.Ordinal))
End If
Yield KeyValuePairUtil.Create(position, span)
i = [end] + 1
End While
End Function
Private Shared Sub TestErrorSpansAllKinds(hasLabel As Func(Of SyntaxKind, Boolean))
Dim unhandledKinds As List(Of SyntaxKind) = New List(Of SyntaxKind)()
For Each k In [Enum].GetValues(GetType(SyntaxKind)).Cast(Of SyntaxKind)().Where(hasLabel)
Dim span As TextSpan?
Try
span = VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl(k, Nothing, EditKind.Update)
#Disable Warning IDE0059 ' Unnecessary assignment of a value - https://github.com/dotnet/roslyn/issues/45896
Catch e1 As NullReferenceException
#Enable Warning IDE0059 ' Unnecessary assignment of a value
' expected, we passed null node
Continue For
End Try
' unexpected
If span Is Nothing Then
unhandledKinds.Add(k)
End If
Next
AssertEx.Equal(Array.Empty(Of SyntaxKind)(), unhandledKinds)
End Sub
Private Shared Async Function AnalyzeDocumentAsync(oldProject As Project, newDocument As Document, Optional activeStatementMap As ActiveStatementsMap = Nothing) As Task(Of DocumentAnalysisResults)
Dim analyzer = New VisualBasicEditAndContinueAnalyzer()
Dim baseActiveStatements = AsyncLazy.Create(If(activeStatementMap, ActiveStatementsMap.Empty))
Dim capabilities = AsyncLazy.Create(EditAndContinueTestHelpers.Net5RuntimeCapabilities)
Return Await analyzer.AnalyzeDocumentAsync(oldProject, baseActiveStatements, newDocument, ImmutableArray(Of LinePositionSpan).Empty, capabilities, CancellationToken.None)
End Function
#End Region
<Fact>
Public Sub ErrorSpans_TopLevel()
Dim source = "
<span>Option Strict Off</span>
<span>Imports Z = Goo.Bar</span>
<<span>Assembly: A(1,2,3,4)</span>, <span>B</span>>
<span>Namespace N.M</span>
End Namespace
<A, B>
Structure S(Of <span>T</span> As {New, Class, I})
Inherits B
End Structure
Structure S(Of <span>T</span> As {New, Class, I})
End Structure
Structure S(Of <span>T</span> As {New, Class, I})
End Structure
<A, B>
<span>Public MustInherit Partial Class C</span>
End Class
<span>Interface I</span>
Implements J, K, L
End Interface
<A>
<span>Enum E1</span>
End Enum
<span>Enum E2</span> As UShort
End Enum
<span>Public Enum E3</span>
Q
<A>R = 3
End Enum
<A>
<span>Public Delegate Sub D1(Of T As Struct)()</span>
<span>Delegate Function D2()</span> As C(Of T)
<span>Delegate Function D2</span> As C(Of T)
<span>Delegate Sub D2</span> As C(Of T)
<Attrib>
<span>Public MustInherit Class Z</span>
<span>Dim f0 As Integer</span>
<span>Dim WithEvents EClass As New EventClass</span>
<A><span>Dim f1 = 1</span>
<A><span>Dim f2 As Integer = 1</span>
Private <span>f3()</span>, <span>f4?</span>, <span>f5</span> As Integer, <span>f6</span> As New C()
<span>Public Shared ReadOnly f As Integer</span>
<A><span>Function M1()</span> As Integer
End Function
<span>Function M2()</span> As Integer Implements I.Goo
End Function
<span>Function M3()</span> As Integer Handles I.E
End Function
<span>Private Function M4(Of S, T)()</span> As Integer Handles I.E
End Function
<span>MustOverride Function M5</span>
Sub M6(<A><span>Optional p1 As Integer = 2131</span>,
<span>p2</span> As Integer,
<span>p3</span>,
<Out><span>ByRef p3</span>,
<span>ParamArray x() As Integer</span>)
End Sub
<A><span>Event E1</span> As A
<A><span>Private Event E1</span> As A
<A><span>Property P</span> As Integer
<A><span>Public MustOverride Custom Event E3</span> As A
<A><span>AddHandler(value As Action)</span>
End AddHandler
<A><span>RemoveHandler(value As Action)</span>
End RemoveHandler
<A><span>RaiseEvent</span>
End RaiseEvent
End Event
<A><span>Property P</span> As Integer
<A><span>Get</span>
End Get
<A><span>Private Set(value As Integer)</span>
End Set
End Property
<A><span>Public Shared Narrowing Operator CType(d As Z)</span> As Integer
End Operator
End Class
"
TestSpans(source, Function(node) SyntaxComparer.TopLevel.HasLabel(node))
End Sub
<Fact>
Public Sub ErrorSpans_StatementLevel_Update()
Dim source = "
Class C
Sub M()
<span>While expr</span>
<span>Continue While</span>
<span>Exit While</span>
End While
<span>Do</span>
<span>Continue Do</span>
<span>Exit Do</span>
Loop While expr
<span>Do</span>
Loop
<span>Do Until expr</span>
Loop
<span>Do While expr</span>
Loop
<span>For Each a In b</span>
<span>Continue For</span>
<span>Exit For</span>
Next
<span>For i = 1 To 10 Step 2</span>
Next
<span>Using expr</span>
End Using
<span>SyncLock expr</span>
End SyncLock
<span>With z</span>
<span>.M()</span>
End With
<span>label:</span>
<span>F()</span>
<span>Static a As Integer = 1</span>
<span>Dim b = 2</span>
<span>Const c = 4</span>
Dim <span>c</span>, <span>d</span> As New C()
<span>GoTo label</span>
<span>Stop</span>
<span>End</span>
<span>Exit Sub</span>
<span>Return</span>
<span>Return 1</span>
<span>Throw</span>
<span>Throw expr</span>
<span>Try</span>
<span>Exit Try</span>
<span>Catch</span>
End Try
<span>Try</span>
<span>Catch e As E</span>
End Try
<span>Try</span>
<span>Catch e As E When True</span>
End Try
<span>Try</span>
<span>Finally</span>
End Try
<span>If expr Then</span>
End If
<span>If expr</span>
<span>ElseIf expr</span>
<span>Else</span>
End If
<span>If True Then</span> M1() <span>Else</span> M2()
<span>Select expr</span>
<span>Case 1</span>
End Select
<span>Select expr</span>
<span>Case 1</span>
<span>GoTo 1</span>
End Select
<span>Select expr</span>
<span>Case 1</span>
<span>GoTo label</span>
<span>Case 4 To 9</span>
<span>Exit Select</span>
<span>Case = 2</span>
<span>Case < 2</span>
<span>Case > 2</span>
<span>Case Else</span>
<span>Return</span>
End Select
<span>On Error Resume Next</span>
<span>On Error Goto 0</span>
<span>On Error Goto -1</span>
<span>On Error GoTo label</span>
<span>Resume</span>
<span>Resume Next</span>
<span>AddHandler e, AddressOf M</span>
<span>RemoveHandler e, AddressOf M</span>
<span>RaiseEvent e()</span>
<span>Error 1</span>
<span>Mid(a, 1, 2) = """"</span>
<span>a = b</span>
<span>Call M()</span>
<span>Dim intArray(10, 10, 10) As Integer</span>
<span>ReDim Preserve intArray(10, 10, 20)</span>
<span>ReDim Preserve intArray(10, 10, 15)</span>
<span>ReDim intArray(10, 10, 10)</span>
<span>Erase intArray</span>
F(<span>Function(x)</span> x)
F(<span>Sub(x)</span> M())
F(<span>[|Aggregate|] z $In {1, 2, 3}</span> Into <span>Max(z)</span>)
F(<span>[|From|] z $In {1, 2, 3}</span>?
Order By <span>z Descending</span>, <span>z Ascending</span>, <span>z</span>
<span>[|Take While|] z $> 0</span>)
F(From z1 In {1, 2, 3}
<span>[|Join|] z2 $In {1, 2, 3}</span> On z1 Equals z2
<span>[|Select|] z1 $+ z2</span>)
F(From z1 In {1, 2, 3}
Join z2 In {1, 2, 3} On <span>$z1 [|Equals|] z2</span>
Select z1 + z2)
F(From z1 In {1, 2, 3}
Join z2 In {1, 2, 3} On <span>z1 [|Equals|] $z2</span>
Select z1 + z2)
F(From a In b <span>[|Let|] x = $expr</span> Select expr)
F(From a In b <span>[|Group|] $a1 By b2 Into z1</span> Select d1)
F(From a In b <span>[|Group|] a1 By $b2 Into z2</span> Select d2)
F(From a In b Group a1 By b2 Into <span>z3</span> Select d3)
F(From cust In A
<span>[|Group Join|] ord In $B On z4 Equals y4
Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 4)</span>
Select 1)
F(From cust In A
<span>Group Join ord In B On $z5 [|Equals|] y5
Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 3)</span>
Select 1)
F(From cust In A
<span>Group Join ord In B On z6 [|Equals|] $y6
Into CustomerOrders = Group, OrderTotal = Sum(ord.Total + 2)</span>
Select 1)
F(From cust In A
Group Join ord In B On z7 Equals y7
Into CustomerOrders = Group, OrderTotal = <span>Sum(ord.Total + 1)</span>
Select 1)
End Sub
End Class
"
TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel)
source = "
Class C
Iterator Function M() As IEnumerable(Of Integer)
<span>Yield 1</span>
End Function
End Class
"
TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel)
source = "
Class C
Async Function M() As Task(Of Integer)
<span>Await expr</span>
End Function
End Class
"
TestSpans(source, AddressOf SyntaxComparer.Statement.HasLabel)
End Sub
''' <summary>
''' Verifies that <see cref="VisualBasicEditAndContinueAnalyzer.TryGetDiagnosticSpanImpl"/> handles all <see cref="SyntaxKind"/> s.
''' </summary>
<Fact>
Public Sub ErrorSpansAllKinds()
TestErrorSpansAllKinds(Function(kind) SyntaxComparer.Statement.HasLabel(kind, ignoreVariableDeclarations:=False))
TestErrorSpansAllKinds(Function(kind) SyntaxComparer.TopLevel.HasLabel(kind, ignoreVariableDeclarations:=False))
End Sub
<Fact>
Public Async Function AnalyzeDocumentAsync_InsignificantChangesInMethodBody() As Task
Dim source1 = "
Class C
Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
"
Dim source2 = "
Class C
Sub Main()
System.Console.WriteLine(1)
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition)
Dim oldSolution = workspace.CurrentSolution
Dim oldProject = oldSolution.Projects.First()
Dim oldDocument = oldProject.Documents.Single()
Dim documentId = oldDocument.Id
Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2))
Dim oldText = Await oldDocument.GetTextAsync()
Dim oldSyntaxRoot = Await oldDocument.GetSyntaxRootAsync()
Dim newDocument = newSolution.GetDocument(documentId)
Dim newText = Await newDocument.GetTextAsync()
Dim newSyntaxRoot = Await newDocument.GetSyntaxRootAsync()
Dim oldStatementSource = "System.Console.WriteLine(1)"
Dim oldStatementPosition = source1.IndexOf(oldStatementSource, StringComparison.Ordinal)
Dim oldStatementTextSpan = New TextSpan(oldStatementPosition, oldStatementSource.Length)
Dim oldStatementSpan = oldText.Lines.GetLinePositionSpan(oldStatementTextSpan)
Dim oldStatementSyntax = oldSyntaxRoot.FindNode(oldStatementTextSpan)
Dim baseActiveStatements = New ActiveStatementsMap(
ImmutableDictionary.CreateRange(
{
KeyValuePairUtil.Create(newDocument.FilePath, ImmutableArray.Create(
New ActiveStatement(
ordinal:=0,
ActiveStatementFlags.LeafFrame,
New SourceFileSpan(newDocument.FilePath, oldStatementSpan),
instructionId:=Nothing)))
}),
ActiveStatementsMap.Empty.InstructionMap)
Dim result = Await AnalyzeDocumentAsync(oldProject, newDocument, baseActiveStatements)
Assert.True(result.HasChanges)
Dim syntaxMap = result.SemanticEdits(0).SyntaxMap
Assert.NotNull(syntaxMap)
Dim newStatementSpan = result.ActiveStatements(0).Span
Dim newStatementTextSpan = newText.Lines.GetTextSpan(newStatementSpan)
Dim newStatementSyntax = newSyntaxRoot.FindNode(newStatementTextSpan)
Dim oldStatementSyntaxMapped = syntaxMap(newStatementSyntax)
Assert.Same(oldStatementSyntax, oldStatementSyntaxMapped)
End Using
End Function
<Fact>
Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange1() As Task
Dim source = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(1 ' syntax error
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition)
Dim oldProject = workspace.CurrentSolution.Projects.Single()
Dim oldDocument = oldProject.Documents.Single()
Dim result = Await AnalyzeDocumentAsync(oldProject, oldDocument)
Assert.False(result.HasChanges)
Assert.False(result.HasChangesAndErrors)
Assert.False(result.HasChangesAndSyntaxErrors)
End Using
End Function
<Fact>
Public Async Function AnalyzeDocumentAsync_SyntaxError_NoChange2() As Task
Dim source1 = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(1 ' syntax error
End Sub
End Class
"
Dim source2 = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(1 ' syntax error
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition)
Dim oldProject = workspace.CurrentSolution.Projects.Single()
Dim oldDocument = oldProject.Documents.Single()
Dim documentId = oldDocument.Id
Dim oldSolution = workspace.CurrentSolution
Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2))
Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId))
Assert.False(result.HasChanges)
Assert.False(result.HasChangesAndErrors)
Assert.False(result.HasChangesAndSyntaxErrors)
End Using
End Function
<Fact>
Public Async Function AnalyzeDocumentAsync_SemanticError_NoChange() As Task
Dim source = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
Bar()
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source, composition:=s_composition)
Dim oldProject = workspace.CurrentSolution.Projects.Single()
Dim oldDocument = oldProject.Documents.Single()
Dim result = Await AnalyzeDocumentAsync(oldProject, oldDocument)
Assert.False(result.HasChanges)
Assert.False(result.HasChangesAndErrors)
Assert.False(result.HasChangesAndSyntaxErrors)
End Using
End Function
<Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")>
Public Async Function AnalyzeDocumentAsync_SemanticErrorInMethodBody_Change() As Task
Dim source1 = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(1)
Bar()
End Sub
End Class
"
Dim source2 = "
Class C
Public Shared Sub Main()
System.Console.WriteLine(2)
Bar()
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition)
Dim oldProject = workspace.CurrentSolution.Projects.Single()
Dim oldDocument = oldProject.Documents.Single()
Dim documentId = oldDocument.Id
Dim oldSolution = workspace.CurrentSolution
Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2))
Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId))
' no declaration errors (error in method body is only reported when emitting)
Assert.False(result.HasChangesAndErrors)
Assert.False(result.HasChangesAndSyntaxErrors)
End Using
End Function
<Fact, WorkItem(10683, "https://github.com/dotnet/roslyn/issues/10683")>
Public Async Function AnalyzeDocumentAsync_SemanticErrorInDeclaration_Change() As Task
Dim source1 = "
Class C
Public Shared Sub Main(x As Bar)
System.Console.WriteLine(1)
End Sub
End Class
"
Dim source2 = "
Class C
Public Shared Sub Main(x As Bar)
System.Console.WriteLine(2)
End Sub
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition)
Dim oldSolution = workspace.CurrentSolution
Dim oldProject = oldSolution.Projects.Single()
Dim documentId = oldProject.Documents.Single().Id
Dim newSolution = workspace.CurrentSolution.WithDocumentText(documentId, SourceText.From(source2))
Dim result = Await AnalyzeDocumentAsync(oldProject, newSolution.GetDocument(documentId))
Assert.True(result.HasChanges)
' No errors reported: EnC analyzer is resilient against semantic errors.
' They will be reported by 1) compiler diagnostic analyzer 2) when emitting delta - if still present.
Assert.False(result.HasChangesAndErrors)
Assert.False(result.HasChangesAndSyntaxErrors)
End Using
End Function
<Fact>
Public Async Function AnalyzeDocumentAsync_AddingNewFile() As Task
Dim source1 = "
Namespace N
Class C
Public Shared Sub Main()
End Sub
End Class
End Namespace
"
Dim source2 = "
Class D
End Class
"
Using workspace = TestWorkspace.CreateVisualBasic(source1, composition:=s_composition)
Dim oldSolution = workspace.CurrentSolution
Dim oldProject = oldSolution.Projects.Single()
Dim newDocId = DocumentId.CreateNewId(oldProject.Id)
Dim newSolution = oldSolution.AddDocument(newDocId, "goo.vb", SourceText.From(source2))
workspace.TryApplyChanges(newSolution)
Dim newProject = newSolution.Projects.Single()
Dim changes = newProject.GetChanges(oldProject)
Assert.Equal(2, newProject.Documents.Count())
Assert.Equal(0, changes.GetChangedDocuments().Count())
Assert.Equal(1, changes.GetAddedDocuments().Count())
Dim changedDocuments = changes.GetChangedDocuments().Concat(changes.GetAddedDocuments())
Dim result = New List(Of DocumentAnalysisResults)()
For Each changedDocumentId In changedDocuments
result.Add(Await AnalyzeDocumentAsync(oldProject, newProject.GetDocument(changedDocumentId)))
Next
Assert.True(result.IsSingle())
Assert.Empty(result.Single().RudeEditErrors)
End Using
End Function
End Class
End Namespace
|
mavasani/roslyn
|
src/EditorFeatures/VisualBasicTest/EditAndContinue/VisualBasicEditAndContinueAnalyzerTests.vb
|
Visual Basic
|
mit
| 24,267
|
' 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 Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeVariableTests
Inherits AbstractCodeVariableTests
#Region "GetStartPoint() tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint()
Dim code =
<Code>
Class C
Dim i$$ As Integer
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:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=9, absoluteOffset:=17, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint_Attribute()
Dim code =
<Code>
Class C
<System.CLSCompliant(True)>
Dim i$$ As Integer
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=9, absoluteOffset:=49, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=45, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=13, lineLength:=31)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint_EnumMember()
Dim code =
<Code>
Enum E
A$$
End Enum
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=5)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetStartPoint_EnumMember_Attribute()
Dim code =
<Code>
Enum E
<System.CLSCompliant(True)>
A$$
End Enum
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=44, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=12, lineLength:=31)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint()
Dim code =
<Code>
Class C
Dim i$$ As Integer
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=10, absoluteOffset:=18, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=21, absoluteOffset:=29, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint_Attribute()
Dim code =
<Code>
Class C
<System.CLSCompliant(True)>
Dim i$$ As Integer
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=40, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=10, absoluteOffset:=50, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=21, absoluteOffset:=61, lineLength:=20)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint_EnumMember()
Dim code =
<Code>
Enum E
A$$
End Enum
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=6, absoluteOffset:=13, lineLength:=5)))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub GetEndPoint_EnumMember_Attribute()
Dim code =
<Code>
Enum E
<System.CLSCompliant(True)>
A$$
End Enum
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=39, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=6, absoluteOffset:=45, lineLength:=5)))
End Sub
#End Region
#Region "Access tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access1()
Dim code =
<Code>
Class C
Dim $$x as Integer
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Access2()
Dim code =
<Code>
Class C
Private $$x as Integer
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 $$x as Integer
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 $$x as Integer
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 $$x as Integer
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 $$x as Integer
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>
Enum E
$$Foo
End Enum
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
#End Region
#Region "Comment tests"
<WorkItem(638909)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Comment1()
Dim code =
<Code>
Class C
' Foo
Dim $$i As Integer
End Class
</Code>
Dim result = " Foo"
TestComment(code, result)
End Sub
#End Region
#Region "ConstKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ConstKind1()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ConstKind2()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ConstKind3()
Dim code =
<Code>
Class C
Const $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ConstKind4()
Dim code =
<Code>
Class C
ReadOnly $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub ConstKind5()
Dim code =
<Code>
Class C
ReadOnly Const $$x As Integer
End Class
</Code>
TestConstKind(code, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
#End Region
#Region "InitExpression tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InitExpression1()
Dim code =
<Code>
Class C
Dim i$$ As Integer = 42
End Class
</Code>
TestInitExpression(code, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InitExpression2()
Dim code =
<Code>
Class C
Const $$i As Integer = 19 + 23
End Class
</Code>
TestInitExpression(code, "19 + 23")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub InitExpression3()
Dim code =
<Code>
Enum E
$$i = 19 + 23
End Enum
</Code>
TestInitExpression(code, "19 + 23")
End Sub
#End Region
#Region "IsConstant tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsConstant1()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
TestIsConstant(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsConstant2()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestIsConstant(code, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsConstant3()
Dim code =
<Code>
Class C
Const $$x As Integer = 0
End Class
</Code>
TestIsConstant(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsConstant4()
Dim code =
<Code>
Class C
ReadOnly $$x As Integer = 0
End Class
</Code>
TestIsConstant(code, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsConstant5()
Dim code =
<Code>
Class C
WithEvents $$x As Integer
End Class
</Code>
TestIsConstant(code, False)
End Sub
#End Region
#Region "IsShared tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared1()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
TestIsShared(code, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub IsShared2()
Dim code =
<Code>
Class C
Shared $$x As Integer
End Class
</Code>
TestIsShared(code, True)
End Sub
#End Region
#Region "Name tests"
<WorkItem(638224)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_EnumMember()
Dim code =
<Code>
Enum SomeEnum
A$$
End Enum
</Code>
TestName(code, "A")
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
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "F:N.C.x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_ClassName1()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C.x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_ClassName2()
Dim code =
<Code>
Namespace N
Class C(Of T)
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Private C(Of T).x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_ClassName3()
Dim code =
<Code>
Namespace N
Class C
Public ReadOnly $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "Public C.x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_ClassName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private C.x = 42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_FullName1()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C.x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_FullName2()
Dim code =
<Code>
Namespace N
Class C(Of T)
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "Private N.C(Of T).x")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_FullName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private N.C.x = 42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_NoName()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName, "Private ")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_NoName_InitExpression()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression, "Private = 42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_NoName_InitExpression_Type()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeNoName Or EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private As Integer = 42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_InitExpression_Type_ForAsNew()
' Amusingly, this will *crash* Dev10.
Dim code =
<Code>
Namespace N
Class C
Dim $$x As New System.Text.StringBuilder
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeInitExpression Or EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As System.Text.StringBuilder")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub Prototype_Type()
Dim code =
<Code>
Namespace N
Class C
Dim $$x As Integer = 42
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Private x As Integer")
End Sub
#End Region
#Region "Type tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub Type1()
Dim code =
<Code>
Class C
Dim $$a As Integer
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Integer",
.AsFullName = "System.Int32",
.CodeTypeFullName = "System.Int32",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefInt
})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub Type2()
Dim code =
<Code>
Class C
WithEvents $$a As Object
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Object",
.AsFullName = "System.Object",
.CodeTypeFullName = "System.Object",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject
})
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub Type3()
Dim code =
<Code>
Class C
Private $$a As New Object
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Object",
.AsFullName = "System.Object",
.CodeTypeFullName = "System.Object",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefObject
})
End Sub
#End Region
#Region "AddAttribute tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddAttribute1()
Dim code =
<Code>
Imports System
Class C
Dim $$foo As Integer
End Class
</Code>
Dim expected =
<Code><![CDATA[
Imports System
Class C
<Serializable()>
Dim foo As Integer
End Class
]]></Code>
TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Sub
<WorkItem(1087167)>
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub AddAttribute2()
Dim code =
<Code><![CDATA[
Imports System
Class C
<Serializable>
Dim $$foo As Integer
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Imports System
Class C
<Serializable>
<CLSCompliant(True)>
Dim foo As Integer
End Class
]]></Code>
TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1})
End Sub
#End Region
#Region "Set Access tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetEnumAccess1()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetEnumAccess2()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetEnumAccess3()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate, ThrowsArgumentException(Of EnvDTE.vsCMAccess)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess1()
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Public i As Integer
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 $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess3()
Dim code =
<Code>
Class C
Private $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess4()
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess5()
Dim code =
<Code>
Class C
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Protected Friend i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess6()
Dim code =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Public i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess7()
Dim code =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Protected Friend i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess8()
Dim code =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Public $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
Dim i As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess9()
Dim code =
<Code>
Class C
#Region "Foo"
Dim $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Public x As Integer
#End Region
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess10()
Dim code =
<Code>
Class C
#Region "Foo"
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Dim x As Integer
#End Region
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess11()
Dim code =
<Code>
Class C
#Region "Foo"
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Protected Friend x As Integer
#End Region
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess12()
Dim code =
<Code><![CDATA[
Class C
#Region "Foo"
<Bar>
Public $$x As Integer
#End Region
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
#Region "Foo"
<Bar>
Protected Friend x As Integer
#End Region
End Class
]]></Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess13()
Dim code =
<Code>
Class C
#Region "Foo"
' Comment comment comment
Public $$x As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
' Comment comment comment
Protected Friend x As Integer
#End Region
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess14()
Dim code =
<Code><![CDATA[
Class C
#Region "Foo"
''' <summary>
''' Comment comment comment
''' </summary>
Public $$x As Integer
#End Region
End Class
]]></Code>
Dim expected =
<Code><![CDATA[
Class C
#Region "Foo"
''' <summary>
''' Comment comment comment
''' </summary>
Protected Friend x As Integer
#End Region
End Class
]]></Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess15()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private WithEvents x As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPrivate Or EnvDTE.vsCMAccess.vsCMAccessWithEvents)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetAccess16()
Dim code =
<Code>
Class C
Private WithEvents $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Sub
#End Region
#Region "Set ConstKind tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind1()
Dim code =
<Code>
Enum
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum
Foo
End Enum
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind2()
Dim code =
<Code>
Enum
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum
Foo
End Enum
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind3()
Dim code =
<Code>
Enum
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum
Foo
End Enum
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst, ThrowsNotImplementedException(Of EnvDTE80.vsCMConstKind))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind4()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind5()
Dim code =
<Code>
Class C
Shared $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Shared x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind6()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindConst)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind7()
Dim code =
<Code>
Class C
Const $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind8()
Dim code =
<Code>
Class C
Dim $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
ReadOnly x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindReadOnly)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetConstKind9()
Dim code =
<Code>
Class C
ReadOnly $$x As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim x As Integer
End Class
</Code>
TestSetConstKind(code, expected, EnvDTE80.vsCMConstKind.vsCMConstKindNone)
End Sub
#End Region
#Region "Set InitExpression tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression1()
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer = 42
End Class
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression2()
Dim code =
<Code>
Class C
Dim $$i As Integer, j As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer = 42, j As Integer
End Class
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression3()
Dim code =
<Code>
Class C
Dim i As Integer, $$j As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer, j As Integer = 42
End Class
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression4()
' The result below is a bit silly, but that's what the legacy Code Model does.
Dim code =
<Code>
Class C
Dim $$o As New Object
End Class
</Code>
Dim expected =
<Code>
Class C
Dim o As New Object = 42
End Class
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression5()
Dim code =
<Code>
Class C
Const $$i As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer = 19 + 23
End Class
</Code>
TestSetInitExpression(code, expected, "19 + 23")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression6()
Dim code =
<Code>
Class C
Const $$i As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
TestSetInitExpression(code, expected, "")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression7()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo = 42
End Enum
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression8()
Dim code =
<Code>
Enum E
$$Foo = 0
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo = 42
End Enum
</Code>
TestSetInitExpression(code, expected, "42")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetInitExpression9()
Dim code =
<Code>
Enum E
$$Foo = 0
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetInitExpression(code, expected, Nothing)
End Sub
#End Region
#Region "Set IsConstant tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant1()
Dim code =
<Code>
Class C
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
TestSetIsConstant(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant2()
Dim code =
<Code>
Class C
Const $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetIsConstant(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant3()
Dim code =
<Code>
Class C
ReadOnly $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Const i As Integer
End Class
</Code>
TestSetIsConstant(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant4()
Dim code =
<Code>
Class C
ReadOnly $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetIsConstant(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant5()
Dim code =
<Code>
Module C
Dim $$i As Integer
End Module
</Code>
Dim expected =
<Code>
Module C
Const i As Integer
End Module
</Code>
TestSetIsConstant(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant6()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetIsConstant(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsConstant7()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetIsConstant(code, expected, False, ThrowsNotImplementedException(Of Boolean))
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
Dim $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Shared i As Integer
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 $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim i As Integer
End Class
</Code>
TestSetIsShared(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared3()
Dim code =
<Code>
Class C
Private $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private Shared i As Integer
End Class
</Code>
TestSetIsShared(code, expected, True)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared4()
Dim code =
<Code>
Class C
Private Shared $$i As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Private i As Integer
End Class
</Code>
TestSetIsShared(code, expected, False)
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared5()
Dim code =
<Code>
Module C
Dim $$i As Integer
End Module
</Code>
Dim expected =
<Code>
Module C
Dim i As Integer
End Module
</Code>
TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetIsShared6()
Dim code =
<Code>
Enum E
$$Foo
End Enum
</Code>
Dim expected =
<Code>
Enum E
Foo
End Enum
</Code>
TestSetIsShared(code, expected, True, ThrowsNotImplementedException(Of Boolean))
End Sub
#End Region
#Region "Set Name tests"
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetName1()
Dim code =
<Code>
Class C
Dim $$Foo As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim Bar As Integer
End Class
</Code>
TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetName2()
Dim code =
<Code>
Class C
#Region "Foo"
Dim $$Foo As Integer
#End Region
End Class
</Code>
Dim expected =
<Code>
Class C
#Region "Foo"
Dim Bar As Integer
#End Region
End Class
</Code>
TestSetName(code, expected, "Bar", NoThrow(Of String)())
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
Dim $$a As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim a As Double
End Class
</Code>
TestSetTypeProp(code, expected, "double")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub SetType2()
Dim code =
<Code>
Class C
Dim $$a, b As Integer
End Class
</Code>
Dim expected =
<Code>
Class C
Dim a, b As Double
End Class
</Code>
TestSetTypeProp(code, expected, "double")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetType3()
Dim code =
<Code>
Class C
Private $$a As New Object
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New String
End Class
</Code>
TestSetTypeProp(code, expected, "String")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetType4()
Dim code =
<Code>
Class C
Private $$a As New Object, x As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New String, x As Integer = 0
End Class
</Code>
TestSetTypeProp(code, expected, "String")
End Sub
<ConditionalFact(GetType(x86)), Trait(Traits.Feature, Traits.Features.CodeModel)>
Sub SetType5()
Dim code =
<Code>
Class C
Private a As New Object, x$$ As Integer = 0
End Class
</Code>
Dim expected =
<Code>
Class C
Private a As New Object, x As String = 0
End Class
</Code>
TestSetTypeProp(code, expected, "String")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
DavidKarlas/roslyn
|
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeVariableTests.vb
|
Visual Basic
|
apache-2.0
| 52,741
|
' Copyright (c) 2014, Outercurve Foundation.
' 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 Outercurve Foundation 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.
Imports System
Imports System.Diagnostics
Imports System.Collections
Imports System.Collections.Specialized
Imports System.IO
Imports System.Text
Imports Microsoft.Win32
Imports WebsitePanel.Server.Utils
Public Class hMailServer43
Inherits hMailServer
#Region "Public Properties"
Public ReadOnly Property AdminUsername() As String
Get
Return ProviderSettings("AdminUsername")
End Get
End Property
Public ReadOnly Property AdminPassword() As String
Get
Return ProviderSettings("AdminPassword")
End Get
End Property
#End Region
Protected Overrides ReadOnly Property hMailServer() As Object
Get
Dim svc As Object = MyBase.hMailServer
' Authenticate API
Dim account As Object = svc.Authenticate(AdminUsername, AdminPassword)
If account Is Nothing Then
Throw New Exception("Could not authenticate using administrator credentials provided")
End If
Return svc
End Get
End Property
Public Overrides Function IsInstalled() As Boolean
Dim displayName As String = ""
Dim version As String = ""
Dim key32bit As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\hMailServer_is1")
If (key32bit IsNot Nothing) Then
displayName = CStr(key32bit.GetValue("DisplayName"))
Dim split As String() = displayName.Split(New [Char]() {" "c})
version = split(1)
Else
Dim key64bit As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\hMailServer_is1")
If (key64bit IsNot Nothing) Then
displayName = CStr(key64bit.GetValue("DisplayName"))
Dim split As String() = displayName.Split(New [Char]() {" "c})
version = split(1)
Else
Return False
End If
End If
If [String].IsNullOrEmpty(version) = False Then
Dim split As String() = version.Split(New [Char]() {"."c})
Return (split(0).Equals("4")) And (Integer.Parse(split(1)) > 2)
Else
Return False
End If
End Function
End Class
|
simonegli8/Websitepanel
|
WebsitePanel/Sources/WebsitePanel.Providers.Mail.hMailServer43/hMailServer43.vb
|
Visual Basic
|
bsd-3-clause
| 3,892
|
' 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.PooledObjects
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend NotInheritable Class CompilationUnitContext
Inherits NamespaceBlockContext
Private _optionStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)
Private _importsStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)
Private _attributeStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)
Private _state As SyntaxKind
Friend Sub New(parser As Parser)
MyBase.New(SyntaxKind.CompilationUnit, Nothing, Nothing)
Me.Parser = parser
_statements = _parser._pool.Allocate(Of StatementSyntax)()
_state = SyntaxKind.OptionStatement
End Sub
Friend Overrides ReadOnly Property IsWithinAsyncMethodOrLambda As Boolean
Get
Return Parser.IsScript
End Get
End Property
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Do
Select Case _state
Case SyntaxKind.OptionStatement
If node.Kind = SyntaxKind.OptionStatement Then
Add(node)
Return Me
End If
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
_state = SyntaxKind.ImportsStatement
Case SyntaxKind.ImportsStatement
If node.Kind = SyntaxKind.ImportsStatement Then
Add(node)
Return Me
End If
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
_state = SyntaxKind.AttributesStatement
Case SyntaxKind.AttributesStatement
If node.Kind = SyntaxKind.AttributesStatement Then
Add(node)
Return Me
End If
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
_state = SyntaxKind.None
Case Else
' only allow executable statements in top-level script code
If _parser.IsScript Then
Dim newContext = TryProcessExecutableStatement(node)
If newContext IsNot Nothing Then
Return newContext
End If
End If
Return MyBase.ProcessSyntax(node)
End Select
Loop
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
If _parser.IsScript Then
Return TryLinkStatement(node, newContext)
Else
Return MyBase.TryLinkSyntax(node, newContext)
End If
End Function
Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Friend Function CreateCompilationUnit(optionalTerminator As PunctuationSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
haveRegionDirectives As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As CompilationUnitSyntax
Debug.Assert(optionalTerminator Is Nothing OrElse optionalTerminator.Kind = SyntaxKind.EndOfFileToken)
If _state <> SyntaxKind.None Then
Select Case _state
Case SyntaxKind.OptionStatement
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
Case SyntaxKind.ImportsStatement
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
Case SyntaxKind.AttributesStatement
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
End Select
_state = SyntaxKind.None
End If
Dim declarations = Body()
Dim result = SyntaxFactory.CompilationUnit(_optionStmts,
_importsStmts,
_attributeStmts,
declarations,
optionalTerminator)
Dim regionsAreAllowedEverywhere = Not haveRegionDirectives OrElse Parser.CheckFeatureAvailability(Feature.RegionsEverywhere)
If notClosedIfDirectives IsNot Nothing OrElse notClosedRegionDirectives IsNot Nothing OrElse notClosedExternalSourceDirective IsNot Nothing OrElse
Not regionsAreAllowedEverywhere Then
result = DiagnosticRewriter.Rewrite(result, notClosedIfDirectives, notClosedRegionDirectives, regionsAreAllowedEverywhere, notClosedExternalSourceDirective, Parser)
If notClosedIfDirectives IsNot Nothing Then
notClosedIfDirectives.Free()
End If
If notClosedRegionDirectives IsNot Nothing Then
notClosedRegionDirectives.Free()
End If
End If
FreeStatements()
Return result
End Function
Private Class DiagnosticRewriter
Inherits VisualBasicSyntaxRewriter
Private _notClosedIfDirectives As HashSet(Of IfDirectiveTriviaSyntax) = Nothing
Private _notClosedRegionDirectives As HashSet(Of RegionDirectiveTriviaSyntax) = Nothing
Private _notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax = Nothing
Private _regionsAreAllowedEverywhere As Boolean
Private _parser As Parser
Private _declarationBlocksBeingVisited As ArrayBuilder(Of VisualBasicSyntaxNode) ' CompilationUnitSyntax is treated as a declaration block for our purposes
Private _parentsOfRegionDirectivesAwaitingClosure As ArrayBuilder(Of VisualBasicSyntaxNode) ' Nodes are coming from _declrationBlocksBeingVisited
Private _tokenWithDirectivesBeingVisited As SyntaxToken
Private Sub New()
MyBase.New()
End Sub
Public Shared Function Rewrite(compilationUnit As CompilationUnitSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
regionsAreAllowedEverywhere As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax,
parser As Parser) As CompilationUnitSyntax
Dim rewriter As New DiagnosticRewriter()
If notClosedIfDirectives IsNot Nothing Then
rewriter._notClosedIfDirectives =
New HashSet(Of IfDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedIfDirectives
rewriter._notClosedIfDirectives.Add(node)
Next
End If
If notClosedRegionDirectives IsNot Nothing Then
rewriter._notClosedRegionDirectives =
New HashSet(Of RegionDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedRegionDirectives
rewriter._notClosedRegionDirectives.Add(node)
Next
End If
rewriter._parser = parser
rewriter._regionsAreAllowedEverywhere = regionsAreAllowedEverywhere
If Not regionsAreAllowedEverywhere Then
rewriter._declarationBlocksBeingVisited = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
rewriter._parentsOfRegionDirectivesAwaitingClosure = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
End If
rewriter._notClosedExternalSourceDirective = notClosedExternalSourceDirective
Dim result = DirectCast(rewriter.Visit(compilationUnit), CompilationUnitSyntax)
If Not regionsAreAllowedEverywhere Then
Debug.Assert(rewriter._declarationBlocksBeingVisited.Count = 0)
Debug.Assert(rewriter._parentsOfRegionDirectivesAwaitingClosure.Count = 0) ' We never add parents of not closed #Region directives into this stack.
rewriter._declarationBlocksBeingVisited.Free()
rewriter._parentsOfRegionDirectivesAwaitingClosure.Free()
End If
Return result
End Function
#If DEBUG Then
' NOTE: the logic is heavily relying on the fact that green nodes in
' NOTE: one single tree are not reused, the following code assert this
Private ReadOnly _processedNodesWithoutDuplication As HashSet(Of VisualBasicSyntaxNode) = New HashSet(Of VisualBasicSyntaxNode)(ReferenceEqualityComparer.Instance)
#End If
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitCompilationUnit(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitMethodBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitConstructorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitOperatorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitAccessorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitNamespaceBlock(node As NamespaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitNamespaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitClassBlock(node As ClassBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitClassBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitStructureBlock(node As StructureBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitStructureBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitModuleBlock(node As ModuleBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitModuleBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitInterfaceBlock(node As InterfaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitInterfaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEnumBlock(node As EnumBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEnumBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitPropertyBlock(node As PropertyBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitPropertyBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEventBlock(node As EventBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEventBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitIfDirectiveTrivia(node)
If Me._notClosedIfDirectives IsNot Nothing AndAlso Me._notClosedIfDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_LbExpectedEndIf)
End If
Return rewritten
End Function
Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitRegionDirectiveTrivia(node)
If Me._notClosedRegionDirectives IsNot Nothing AndAlso Me._notClosedRegionDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndRegion)
ElseIf Not _regionsAreAllowedEverywhere
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Private Function VerifyRegionPlacement(original As VisualBasicSyntaxNode, rewritten As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Dim containingBlock = _declarationBlocksBeingVisited.Peek()
' Ensure that the directive is inside the block, rather than is attached to it as a leading/trailing trivia
Debug.Assert(_declarationBlocksBeingVisited.Count > 1 OrElse containingBlock.Kind = SyntaxKind.CompilationUnit)
If _declarationBlocksBeingVisited.Count > 1 Then
If _tokenWithDirectivesBeingVisited Is containingBlock.GetFirstToken() Then
Dim leadingTrivia = _tokenWithDirectivesBeingVisited.GetLeadingTrivia()
If leadingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
ElseIf _tokenWithDirectivesBeingVisited Is containingBlock.GetLastToken() Then
Dim trailingTrivia = _tokenWithDirectivesBeingVisited.GetTrailingTrivia()
If trailingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
End If
End If
Dim reportAnError = Not IsValidContainingBlockForRegionInVB12(containingBlock)
If original.Kind = SyntaxKind.RegionDirectiveTrivia Then
_parentsOfRegionDirectivesAwaitingClosure.Push(containingBlock)
Else
Debug.Assert(original.Kind = SyntaxKind.EndRegionDirectiveTrivia)
If _parentsOfRegionDirectivesAwaitingClosure.Count > 0 Then
Dim regionBeginContainingBlock = _parentsOfRegionDirectivesAwaitingClosure.Pop()
If regionBeginContainingBlock IsNot containingBlock AndAlso IsValidContainingBlockForRegionInVB12(regionBeginContainingBlock) Then
reportAnError = True
End If
End If
End If
If reportAnError Then
rewritten = _parser.ReportFeatureUnavailable(Feature.RegionsEverywhere, rewritten)
End If
Return rewritten
End Function
Private Shared Function IsValidContainingBlockForRegionInVB12(containingBlock As VisualBasicSyntaxNode) As Boolean
Select Case containingBlock.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return False
End Select
Return True
End Function
Public Overrides Function VisitEndRegionDirectiveTrivia(node As EndRegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitEndRegionDirectiveTrivia(node)
If Not _regionsAreAllowedEverywhere Then
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Public Overrides Function VisitExternalSourceDirectiveTrivia(node As ExternalSourceDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitExternalSourceDirectiveTrivia(node)
If Me._notClosedExternalSourceDirective Is node Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndExternalSource)
End If
Return rewritten
End Function
Public Overrides Function Visit(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
If node Is Nothing OrElse Not node.ContainsDirectives Then
Return node
End If
Return node.Accept(Me)
End Function
Public Overrides Function VisitSyntaxToken(token As SyntaxToken) As SyntaxToken
If token Is Nothing OrElse Not token.ContainsDirectives Then
Return token
End If
Debug.Assert(_tokenWithDirectivesBeingVisited Is Nothing)
_tokenWithDirectivesBeingVisited = token
Dim leadingTrivia = token.GetLeadingTrivia()
Dim trailingTrivia = token.GetTrailingTrivia()
If leadingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia)).Node
If leadingTrivia IsNot rewritten Then
token = DirectCast(token.WithLeadingTrivia(rewritten), SyntaxToken)
End If
End If
If trailingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia)).Node
If trailingTrivia IsNot rewritten Then
token = DirectCast(token.WithTrailingTrivia(rewritten), SyntaxToken)
End If
End If
_tokenWithDirectivesBeingVisited = Nothing
Return token
End Function
End Class
End Class
End Namespace
|
jkotas/roslyn
|
src/Compilers/VisualBasic/Portable/Parser/BlockContexts/CompilationUnitContext.vb
|
Visual Basic
|
apache-2.0
| 25,923
|
' 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.ExtractMethod
Partial Public Class ExtractMethodTests
Public Class MethodNameGeneration
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestGetLiteralGeneratesSmartName() As Task
Dim code = <text>Public Class Class1
Sub MySub()
Dim a As Integer = [|10|]
End Sub
End Class</text>
Dim expected = <text>Public Class Class1
Sub MySub()
Dim a As Integer = GetA()
End Sub
Private Shared Function GetA() As Integer
Return 10
End Function
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestGetLiteralDoesNotGenerateSmartName() As Task
Dim code = <text>Public Class Class1
Sub MySub()
Dim a As Integer = [|10|] + 42
End Sub
End Class</text>
Dim expected = <text>Public Class Class1
Sub MySub()
Dim a As Integer = NewMethod() + 42
End Sub
Private Shared Function NewMethod() As Integer
Return 10
End Function
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestGetLiteralGeneratesSmartName2() As Task
Dim code = <text>Public Class Class1
Sub MySub()
Dim b As Integer = 5
Dim a As Integer = 10 + [|b|]
End Sub
End Class</text>
Dim expected = <text>Public Class Class1
Sub MySub()
Dim b As Integer = 5
Dim a As Integer = 10 + GetB(b)
End Sub
Private Shared Function GetB(b As Integer) As Integer
Return b
End Function
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestAppendingNumberedSuffixToGetMethods() As Task
Dim code = <text>Class A
Function Test1() As Integer
Dim x As Integer = GetX()
Console.Write([|x|])
Return x
End Function
Private Shared Function GetX() As Integer
Return 5
End Function
End Class</text>
Dim expected = <text>Class A
Function Test1() As Integer
Dim x As Integer = GetX()
Console.Write(GetX1(x))
Return x
End Function
Private Shared Function GetX1(x As Integer) As Integer
Return x
End Function
Private Shared Function GetX() As Integer
Return 5
End Function
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestAppendingNumberedSuffixToNewMethods() As Task
Dim code = <text>Class A
Function Test1() As Integer
Dim x As Integer = 5
[|Console.Write(5)|]
Return x
End Function
Private Shared Sub NewMethod()
End Sub
End Class</text>
Dim expected = <text>Class A
Function Test1() As Integer
Dim x As Integer = 5
NewMethod1()
Return x
End Function
Private Shared Sub NewMethod1()
Console.Write(5)
End Sub
Private Shared Sub NewMethod()
End Sub
End Class</text>
Await TestExtractMethodAsync(code, expected)
End Function
''' This is a special case in VB as it is case insensitive
''' Hence Get_FirstName() would conflict with the internal get_FirstName() that VB generates for the getter
<WorkItem(540483, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540483")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestPropertyGetter() As Task
Dim code = <text>Class Program
Private _FirstName As String
Property FirstName() As String
Get
Dim name As String
name = [|_FirstName|]
Return name
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
End Class</text>
Dim expected = <text>Class Program
Private _FirstName As String
Property FirstName() As String
Get
Dim name As String
name = GetFirstName()
Return name
End Get
Set(ByVal value As String)
_FirstName = value
End Set
End Property
Private Function GetFirstName() As String
Return _FirstName
End Function
End Class</text>
' changed test due to implicit function variable bug in VB
Await TestExtractMethodAsync(code, expected)
End Function
<WorkItem(530674, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530674")>
<Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)>
Public Async Function TestEscapedParameterName() As Task
Dim code = <text>Imports System.Linq
Module Program
Sub Goo()
Dim x = From [char] In ""
Select [|[char]|] ' Extract method
End Sub
End Module</text>
Dim expected = <text>Imports System.Linq
Module Program
Sub Goo()
Dim x = From [char] In ""
Select GetChar([char]) ' Extract method
End Sub
Private Function GetChar([char] As Char) As Char
Return [char]
End Function
End Module</text>
Await TestExtractMethodAsync(code, expected)
End Function
End Class
End Class
End Namespace
|
mmitche/roslyn
|
src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.MethodNameGeneration.vb
|
Visual Basic
|
apache-2.0
| 6,108
|
' 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.DocumentationComments
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Partial Friend Class ObjectCreationExpressionSignatureHelpProvider
Private Function GetDelegateTypeConstructors(objectCreationExpression As ObjectCreationExpressionSyntax,
semanticModel As SemanticModel,
symbolDisplayService As ISymbolDisplayService,
anonymousTypeDisplayService As IAnonymousTypeDisplayService,
documentationCommentFormattingService As IDocumentationCommentFormattingService,
delegateType As INamedTypeSymbol,
within As ISymbol,
cancellationToken As CancellationToken) As IList(Of SignatureHelpItem)
Dim invokeMethod = delegateType.DelegateInvokeMethod
If invokeMethod Is Nothing Then
Return Nothing
End If
Dim position = objectCreationExpression.SpanStart
Dim item = CreateItem(
invokeMethod, semanticModel, position,
symbolDisplayService, anonymousTypeDisplayService,
isVariadic:=False,
documentationFactory:=invokeMethod.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
prefixParts:=GetDelegateTypePreambleParts(invokeMethod, semanticModel, position),
separatorParts:=GetSeparatorParts(),
suffixParts:=GetDelegateTypePostambleParts(invokeMethod),
parameters:=GetDelegateTypeParameters(invokeMethod, semanticModel, position, cancellationToken))
Return SpecializedCollections.SingletonList(item)
End Function
Private Function GetDelegateTypePreambleParts(invokeMethod As IMethodSymbol, semanticModel As SemanticModel, position As Integer) As IList(Of SymbolDisplayPart)
Dim result = New List(Of SymbolDisplayPart)()
result.AddRange(invokeMethod.ContainingType.ToMinimalDisplayParts(semanticModel, position))
result.Add(Punctuation(SyntaxKind.OpenParenToken))
Return result
End Function
Private Function GetDelegateTypeParameters(invokeMethod As IMethodSymbol, semanticModel As SemanticModel, position As Integer, cancellationToken As CancellationToken) As IList(Of SignatureHelpSymbolParameter)
Const TargetName As String = "target"
Dim parts = New List(Of SymbolDisplayPart)()
If invokeMethod.ReturnsVoid Then
parts.Add(Keyword(SyntaxKind.SubKeyword))
Else
parts.Add(Keyword(SyntaxKind.FunctionKeyword))
End If
parts.Add(Space())
parts.Add(Punctuation(SyntaxKind.OpenParenToken))
Dim first = True
For Each parameter In invokeMethod.Parameters
If Not first Then
parts.Add(Punctuation(SyntaxKind.CommaToken))
parts.Add(Space())
End If
first = False
parts.AddRange(parameter.Type.ToMinimalDisplayParts(semanticModel, position))
Next
parts.Add(Punctuation(SyntaxKind.CloseParenToken))
If Not invokeMethod.ReturnsVoid Then
parts.Add(Space())
parts.Add(Keyword(SyntaxKind.AsKeyword))
parts.Add(Space())
parts.AddRange(invokeMethod.ReturnType.ToMinimalDisplayParts(semanticModel, position))
End If
Return {New SignatureHelpSymbolParameter(
TargetName,
isOptional:=False,
documentationFactory:=Nothing,
displayParts:=parts)}
End Function
Private Function GetDelegateTypePostambleParts(invokeMethod As IMethodSymbol) As IList(Of SymbolDisplayPart)
Return {Punctuation(SyntaxKind.CloseParenToken)}
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.DelegateType.vb
|
Visual Basic
|
apache-2.0
| 4,600
|
' 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.Formatting
Imports Microsoft.CodeAnalysis.Formatting.Rules
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Formatting
<ExportFormattingRule(ElasticTriviaFormattingRule.Name, LanguageNames.VisualBasic), [Shared]>
<ExtensionOrder(After:=StructuredTriviaFormattingRule.Name)>
Friend Class ElasticTriviaFormattingRule
Inherits BaseFormattingRule
Friend Const Name As String = "VisualBasic Elastic Trivia Formatting Rule"
Public Sub New()
End Sub
Public Overrides Sub AddSuppressOperations(list As List(Of SuppressOperation), node As SyntaxNode, lastToken As SyntaxToken, optionSet As OptionSet, nextOperation As NextAction(Of SuppressOperation))
nextOperation.Invoke(list)
End Sub
Public Overrides Function GetAdjustSpacesOperation(previousToken As SyntaxToken, currentToken As SyntaxToken, optionSet As OptionSet, nextOperation As Rules.NextOperation(Of AdjustSpacesOperation)) As AdjustSpacesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke()
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke()
If operation IsNot Nothing AndAlso operation.Option = AdjustSpacesOption.ForceSpaces Then
Return operation
End If
' remove blank lines between parameter lists and implements clauses
If currentToken.Kind = SyntaxKind.ImplementsKeyword AndAlso
(previousToken.GetAncestor(Of MethodStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing OrElse
previousToken.GetAncestor(Of EventStatementSyntax)() IsNot Nothing) Then
Return FormattingOperations.CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces)
End If
' handle comma separated lists in implements clauses
If previousToken.GetAncestor(Of ImplementsClauseSyntax)() IsNot Nothing AndAlso currentToken.Kind = SyntaxKind.CommaToken Then
Return FormattingOperations.CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces)
End If
Return operation
End Function
Public Overrides Function GetAdjustNewLinesOperation(previousToken As SyntaxToken, currentToken As SyntaxToken, optionSet As OptionSet, nextOperation As NextOperation(Of AdjustNewLinesOperation)) As AdjustNewLinesOperation
' if it doesn't have elastic trivia, pass it through
If Not CommonFormattingHelpers.HasAnyWhitespaceElasticTrivia(previousToken, currentToken) Then
Return nextOperation.Invoke()
End If
' if it has one, check whether there is a forced one
Dim operation = nextOperation.Invoke()
If operation IsNot Nothing AndAlso operation.Option = AdjustNewLinesOption.ForceLines Then
Return operation
End If
' put attributes in its own line if it is top level attribute
Dim attributeNode = TryCast(previousToken.Parent, AttributeListSyntax)
If attributeNode IsNot Nothing AndAlso TypeOf attributeNode.Parent Is StatementSyntax AndAlso
attributeNode.GreaterThanToken = previousToken AndAlso currentToken.Kind <> SyntaxKind.LessThanToken Then
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.ForceLines)
End If
If Not previousToken.IsLastTokenOfStatement() Then
Return operation
End If
' The previous token may end a statement, but it could be in a lambda inside parens.
If currentToken.Kind = SyntaxKind.CloseParenToken AndAlso
TypeOf currentToken.Parent Is ParenthesizedExpressionSyntax Then
Return operation
End If
If AfterLastInheritsOrImplements(previousToken, currentToken) Then
If Not TypeOf currentToken.Parent Is EndBlockStatementSyntax Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
End If
If AfterLastImportStatement(previousToken, currentToken) Then
Return FormattingOperations.CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.ForceLines)
End If
Dim lines = LineBreaksAfter(previousToken, currentToken)
If Not lines.HasValue Then
If TypeOf previousToken.Parent Is XmlNodeSyntax Then
' make sure next statement starts on its own line if previous statement ends with xml literals
Return FormattingOperations.CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(Math.Max(If(operation Is Nothing, 1, operation.Line), 0), AdjustNewLinesOption.PreserveLines)
End If
If lines = 0 Then
Return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines)
End If
Return CreateAdjustNewLinesOperation(lines.Value, AdjustNewLinesOption.ForceLines)
End Function
Private Function AfterLastImportStatement(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
' in between two imports
If nextToken.Kind = SyntaxKind.ImportsKeyword Then
Return False
End If
' current one is not import statement
If Not TypeOf token.Parent Is NameSyntax Then
Return False
End If
Dim [imports] = token.GetAncestor(Of ImportsStatementSyntax)()
If [imports] Is Nothing Then
Return False
End If
Return True
End Function
Private Function AfterLastInheritsOrImplements(token As SyntaxToken, nextToken As SyntaxToken) As Boolean
Dim inheritsOrImplements = token.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Dim nextInheritsOrImplements = nextToken.GetAncestor(Of InheritsOrImplementsStatementSyntax)()
Return inheritsOrImplements IsNot Nothing AndAlso nextInheritsOrImplements Is Nothing
End Function
Private Function IsBeginStatement(Of TStatement As StatementSyntax, TBlock As StatementSyntax)(node As StatementSyntax) As Boolean
Return TryCast(node, TStatement) IsNot Nothing AndAlso TryCast(node.Parent, TBlock) IsNot Nothing
End Function
Private Function IsEndBlockStatement(node As StatementSyntax) As Boolean
Return TryCast(node, EndBlockStatementSyntax) IsNot Nothing OrElse
TryCast(node, LoopStatementSyntax) IsNot Nothing OrElse
TryCast(node, NextStatementSyntax) IsNot Nothing
End Function
Private Function LineBreaksAfter(previousToken As SyntaxToken, currentToken As SyntaxToken) As Integer?
If currentToken.Kind = SyntaxKind.None OrElse
previousToken.Kind = SyntaxKind.None Then
Return 0
End If
Dim previousStatement = previousToken.GetAncestor(Of StatementSyntax)()
Dim currentStatement = currentToken.GetAncestor(Of StatementSyntax)()
If previousStatement Is Nothing OrElse currentStatement Is Nothing Then
Return Nothing
End If
If TopLevelStatement(previousStatement) AndAlso Not TopLevelStatement(currentStatement) Then
Return GetActualLines(previousToken, currentToken, 1)
End If
' Early out of accessors, we don't force more lines between them.
If previousStatement.Kind = SyntaxKind.EndSetStatement OrElse
previousStatement.Kind = SyntaxKind.EndGetStatement OrElse
previousStatement.Kind = SyntaxKind.EndAddHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRemoveHandlerStatement OrElse
previousStatement.Kind = SyntaxKind.EndRaiseEventStatement Then
Return Nothing
End If
' Blank line after an end block, unless it's followed by another end or an else
If IsEndBlockStatement(previousStatement) Then
If IsEndBlockStatement(currentStatement) OrElse
currentStatement.Kind = SyntaxKind.ElseIfStatement OrElse
currentStatement.Kind = SyntaxKind.ElseStatement Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
' Blank line _before_ a block, unless it's the first thing in a type.
If IsBeginStatement(Of MethodStatementSyntax, MethodBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SubNewStatementSyntax, ConstructorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of OperatorStatementSyntax, OperatorBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of PropertyStatementSyntax, PropertyBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EventStatementSyntax, EventBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TypeStatementSyntax, TypeBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of EnumStatementSyntax, EnumBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of NamespaceStatementSyntax, NamespaceBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of DoStatementSyntax, DoLoopBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of ForEachStatementSyntax, ForOrForEachBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of IfStatementSyntax, MultiLineIfBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SelectStatementSyntax, SelectBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of SyncLockStatementSyntax, SyncLockBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of TryStatementSyntax, TryBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of UsingStatementSyntax, UsingBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WhileStatementSyntax, WhileBlockSyntax)(currentStatement) OrElse
IsBeginStatement(Of WithStatementSyntax, WithBlockSyntax)(currentStatement) Then
If TypeOf previousStatement Is NamespaceStatementSyntax OrElse
TypeOf previousStatement Is TypeStatementSyntax Then
Return GetActualLines(previousToken, currentToken, 1)
Else
Return GetActualLines(previousToken, currentToken, 2, 1)
End If
End If
Return Nothing
End Function
Private Function GetActualLines(token1 As SyntaxToken, token2 As SyntaxToken, lines As Integer, Optional leadingBlankLines As Integer = 0) As Integer
If leadingBlankLines = 0 Then
Return Math.Max(lines, 0)
End If
' see whether first non whitespace trivia after previous member is comment or not
Dim list = token1.TrailingTrivia.Concat(token2.LeadingTrivia)
Dim firstNonWhitespaceTrivia = list.FirstOrDefault(Function(t) Not t.IsWhitespace())
If firstNonWhitespaceTrivia.IsKind(SyntaxKind.CommentTrivia, SyntaxKind.DocumentationCommentTrivia) Then
Dim totalLines = GetNumberOfLines(list)
Dim blankLines = GetNumberOfLines(list.TakeWhile(Function(t) t <> firstNonWhitespaceTrivia))
If totalLines < lines Then
Dim afterCommentWithBlank = (totalLines - blankLines) + leadingBlankLines
Return Math.Max(If(lines > afterCommentWithBlank, lines, afterCommentWithBlank), 0)
End If
If blankLines < leadingBlankLines Then
Return Math.Max(totalLines - blankLines + leadingBlankLines, 0)
End If
Return Math.Max(totalLines, 0)
End If
Return Math.Max(lines, 0)
End Function
Private Function GetNumberOfLines(list As IEnumerable(Of SyntaxTrivia)) As Integer
Return list.Sum(Function(t) t.ToFullString().Replace(vbCrLf, vbCr).OfType(Of Char).Count(Function(c) SyntaxFacts.IsNewLine(c)))
End Function
Private Function TopLevelStatement(statement As StatementSyntax) As Boolean
Return TypeOf statement Is MethodStatementSyntax OrElse
TypeOf statement Is SubNewStatementSyntax OrElse
TypeOf statement Is OperatorStatementSyntax OrElse
TypeOf statement Is PropertyStatementSyntax OrElse
TypeOf statement Is EventStatementSyntax OrElse
TypeOf statement Is TypeStatementSyntax OrElse
TypeOf statement Is EnumStatementSyntax OrElse
TypeOf statement Is NamespaceStatementSyntax
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Workspaces/VisualBasic/Portable/Formatting/Rules/ElasticTriviaFormattingRule.vb
|
Visual Basic
|
apache-2.0
| 13,946
|
Option Infer On
Imports System
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Namespace Examples
Friend Class Program
<STAThread>
Shared Sub Main(ByVal args() As String)
Dim application As SolidEdgeFramework.Application = Nothing
Dim partDocument As SolidEdgePart.PartDocument = Nothing
Dim models As SolidEdgePart.Models = Nothing
Dim model As SolidEdgePart.Model = Nothing
Dim drafts As SolidEdgePart.Drafts = Nothing
Dim draft As SolidEdgePart.Draft = Nothing
Try
' See "Handling 'Application is Busy' and 'Call was Rejected By Callee' errors" topic.
OleMessageFilter.Register()
' Attempt to connect to a running instance of Solid Edge.
application = DirectCast(Marshal.GetActiveObject("SolidEdge.Application"), SolidEdgeFramework.Application)
partDocument = TryCast(application.ActiveDocument, SolidEdgePart.PartDocument)
If partDocument IsNot Nothing Then
models = partDocument.Models
model = models.Item(1)
drafts = model.Drafts
For i As Integer = 1 To drafts.Count
draft = drafts.Item(i)
Dim attributeSets = CType(draft.AttributeSets, SolidEdgeFramework.AttributeSets)
Next i
End If
Catch ex As System.Exception
Console.WriteLine(ex)
Finally
OleMessageFilter.Unregister()
End Try
End Sub
End Class
End Namespace
|
SolidEdgeCommunity/docs
|
docfx_project/snippets/SolidEdgePart.Draft.AttributeSets.vb
|
Visual Basic
|
mit
| 1,699
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.