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 Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class GenericsTests
Inherits BasicTestBase
<WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")>
<WorkItem(543690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543690")>
<Fact()>
Public Sub WrongNumberOfGenericArgumentsTest()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation name="WrongNumberOfGenericArguments">
<file name="a.vb">
Namespace GenArity200
Public Class vbCls5 (Of T)
Structure vbStrA (Of X, Y)
Dim i As Integer
Public Readonly Property rp () As String
Get
Return "vbCls5 (Of T) vbStrA (Of X, Y)"
End Get
End Property
End Structure
End Class
Class Problem
Sub GenArity200()
Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer)
End Sub
End Class
End Namespace
</file>
</compilation>)
AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'vbCls5(Of UInteger()()).vbStrA(Of X, Y)'.
Dim Str14 As New vbCls5 (Of UInteger ()()).vbStrA (Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543706")>
<Fact()>
Public Sub TestNestedGenericTypeInference()
Dim vbCompilation = CreateVisualBasicCompilation("TestNestedGenericTypeInference",
<![CDATA[Imports System
Public Module Program
Sub goo(Of U, T)(ByVal x As cls1(Of U).cls2(Of T))
Console.WriteLine(GetType(U).ToString())
Console.WriteLine(GetType(T).ToString())
End Sub
Class cls1(Of X)
Class cls2(Of Y)
End Class
End Class
Sub Main()
Dim x = New cls1(Of Integer).cls2(Of Long)
goo(x)
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
CompileAndVerify(vbCompilation, expectedOutput:=<![CDATA[System.Int32
System.Int64]]>).VerifyDiagnostics()
End Sub
<WorkItem(543783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543783")>
<Fact()>
Public Sub ImportNestedGenericTypeWithErrors()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String)
Namespace GenImpClassOpenErrors
Module Module1
Public Class GenClassA(Of T)
Public Class GenClassB(Of U)
Public Class GenClassC(Of V)
End Class
End Class
End Class
End Module
End Namespace
]]></file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32042: Too few type arguments to 'Module1.GenClassA(Of String).GenClassB(Of U)'.
Imports GenImpClassOpenErrors.GenClassA(Of String).GenClassB.GenClassC(Of String)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>)
End Sub
<WorkItem(543850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543850")>
<Fact()>
Public Sub ConflictingNakedConstraint()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Module Program
Class c2
End Class
Class c3
End Class
Class C6(Of T As {c2, c3})
'COMPILEERROR: BC32110, "c3", BC32110, "c3"
Interface I1(Of S As {U, c3}, U As {c3, T})
End Interface
End Class
End Module
</file>
</compilation>)
compilation.AssertTheseDiagnostics(
<expected>
BC32047: Type parameter 'T' can only have one constraint that is a class.
Class C6(Of T As {c2, c3})
~~
BC32111: Indirect constraint 'Class c2' obtained from the type parameter constraint 'U' conflicts with the constraint 'Class c3'.
Interface I1(Of S As {U, c3}, U As {c3, T})
~
BC32110: Constraint 'Class c3' conflicts with the indirect constraint 'Class c2' obtained from the type parameter constraint 'T'.
Interface I1(Of S As {U, c3}, U As {c3, T})
~~
</expected>)
End Sub
<WorkItem(11887, "DevDiv_Projects/Roslyn")>
<Fact()>
Public Sub WideningNullableConversion()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub Gen1E(Of T, V As Structure)(ByVal c As Func(Of V?, T))
Dim k = New V
c(k)
End Sub
End Module
</file>
</compilation>
)
compilation.VerifyDiagnostics()
End Sub
<WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")>
<Fact()>
Public Sub NarrowingConversionNoReturn()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Namespace Program
Class C6
Public Shared Narrowing Operator CType(ByVal arg As C6) As Exception
Return Nothing
End Operator
End Class
End Namespace
</file>
</compilation>
)
compilation.VerifyDiagnostics()
End Sub
<WorkItem(543900, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543900")>
<Fact()>
Public Sub NarrowingConversionNoReturn2()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Namespace Program
Class c2
Public Shared Narrowing Operator CType(ByVal arg As c2) As Integer
Return Nothing
End Operator
End Class
End Namespace
</file>
</compilation>
)
compilation.AssertNoDiagnostics()
End Sub
<WorkItem(543902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543902")>
<Fact()>
Public Sub ConversionOperatorShouldBePublic()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Namespace Program
Class CScen5
Shared Narrowing Operator CType(ByVal src As CScen5b) As CScen5
str = "scen5"
Return New CScen5
End Operator
Public Shared str = ""
End Class
End Namespace
</file>
</compilation>
)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_UndefinedType1, "CScen5b").WithArguments("CScen5b"))
End Sub
<Fact(), WorkItem(529249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529249")>
Public Sub ArrayOfRuntimeArgumentHandle()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Module Program
Sub goo(ByRef x As RuntimeArgumentHandle())
ReDim x(100)
End Sub
End Module
</file>
</compilation>
)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "RuntimeArgumentHandle()").WithArguments("System.RuntimeArgumentHandle"))
End Sub
<WorkItem(543909, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543909")>
<Fact()>
Public Sub StructureContainsItself()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Imports System
Namespace Program
Structure s2
Dim list As Collections.Generic.List(Of s2)
'COMPILEERROR: BC30294, "Collections.Generic.List(Of s2).Enumerator"
Dim enumerator As Collections.Generic.List(Of s2).Enumerator
End Structure
End Namespace
</file>
</compilation>
)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RecordCycle2, "enumerator").WithArguments("s2",
vbCrLf &
" 's2' contains 'List(Of s2).Enumerator' (variable 'enumerator')." & vbCrLf &
" 'List(Of s2).Enumerator' contains 's2' (variable 'current')."))
End Sub
<WorkItem(543921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543921")>
<Fact()>
Public Sub GenericConstraintInheritanceWithEvent()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Namespace GenClass7105
Interface I1
Event e()
Property p1() As String
Sub rEvent()
End Interface
Class CI1
Implements I1
Private s1 As String
Public Event e() Implements I1.e
Public Sub rEvent() Implements I1.rEvent
RaiseEvent e()
End Sub
Public Property p1() As String Implements I1.p1
Get
Return s1
End Get
Set(ByVal value As String)
s1 = value
End Set
End Property
Sub eHandler() Handles Me.e
Me.s1 = Me.s1 & "eHandler"
End Sub
End Class
Class CI2
Inherits CI1
End Class
Class Cls1a(Of T1 As {I1, Class}, T2 As T1)
Public WithEvents x1 As T1
'This error is actually correct now as the Class Constraint Change which was made. Class can be a Class (OR INTERFACE) on a structure.
'This testcase has changed to reflect the new behavior and this constraint change will also be caught.
'COMPILEERROR: BC30413, "T2"
Public WithEvents x2 As T2
Public Function Test(ByVal i As Integer) As String
x2.p1 = "x2_"
Call x2.rEvent()
Return x2.p1
End Function
End Class
End Namespace
</file>
</compilation>
)
compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_WithEventsAsStruct, "x2"))
End Sub
<WorkItem(529287, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529287")>
<Fact()>
Public Sub ProtectedMemberGenericClass()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Public Class c1(Of T)
'COMPILEERROR: BC30508, "c1(Of Integer).c2"
Protected x As c1(Of Integer).c2
Protected Class c2
End Class
End Class
</file>
</compilation>
)
compilation.VerifyDiagnostics()
End Sub
<WorkItem(544122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544122")>
<Fact()>
Public Sub BoxAlreadyBoxed()
Dim compilation = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Scen4(Of T As U, U As Class)(ByVal p As T)
Dim x As T
x = TryCast(p, U)
If x Is Nothing Then
Console.WriteLine("fail")
End If
End Sub
Sub Main(args As String())
End Sub
End Module
</file>
</compilation>
)
End Sub
<WorkItem(531075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531075")>
<Fact()>
Public Sub Bug17530()
Dim vbCompilation = CreateVisualBasicCompilation("Bug17530",
<![CDATA[
Imports Tuple = System.Tuple
Public Module Program
Sub Main()
Dim x As Object = Nothing
Dim y = TryCast(x, Tuple(Of Integer, Integer, String))
End Sub
End Module
]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, globalImports:=GlobalImport.Parse({"System"})))
CompileAndVerify(vbCompilation).VerifyDiagnostics(
Diagnostic(ERRID.HDN_UnusedImportStatement, "Imports Tuple = System.Tuple"))
End Sub
End Class
End Namespace
|
paulvanbrenk/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Binding/GenericsTests.vb
|
Visual Basic
|
apache-2.0
| 12,662
|
' 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.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeFunctionTests
Inherits AbstractCodeFunctionTests
#Region "GetStartPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_MustOverride1()
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$M()
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=22, absoluteOffset:=42, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=24)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_MustOverride2()
Dim code =
<Code>
MustInherit Class C
<System.CLSCompliant(True)>
MustOverride Sub $$M()
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=74, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=57, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=25, lineLength:=31)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_DeclareFunction_WithoutAttribute()
Dim code =
<Code>
Public Class C1
Declare Function $$getUserName Lib "My1.dll" () As String
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=22, absoluteOffset:=38, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=59)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_DeclareFunction_WithAttribute()
Dim code =
<Code>
Public Class C1
<System.CLSCompliant(True)>
Declare Function $$getUserName Lib "My1.dll" () As String
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=22, absoluteOffset:=70, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_DeclareSub_WithoutAttribute()
Dim code =
<Code>
Public Class C1
Public Declare Sub $$MethodName Lib "My1.dll"
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=24, absoluteOffset:=40, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=47)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetStartPoint_DeclareSub_WithAttribute()
Dim code =
<Code>
Public Class C1
<System.CLSCompliant(True)>
Public Declare Sub $$MethodName Lib "My1.dll"
End Class
</Code>
TestGetStartPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=24, absoluteOffset:=72, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=5, absoluteOffset:=53, lineLength:=47)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=5, absoluteOffset:=21, lineLength:=31)))
End Sub
#End Region
#Region "GetEndPoint() tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_MustOverride1()
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$M()
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=23, absoluteOffset:=43, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=25, absoluteOffset:=45, lineLength:=24)))
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_MustOverride2()
Dim code =
<Code>
MustInherit Class C
<System.CLSCompliant(True)>
MustOverride Sub $$M()
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=52, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=52, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=23, absoluteOffset:=75, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=25, absoluteOffset:=77, lineLength:=24)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_DeclareFunction_WithoutAttribute()
Dim code =
<Code>
Public Class C1
Declare Function $$getUserName Lib "My1.dll" () As String
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=33, absoluteOffset:=49, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=60, absoluteOffset:=76, lineLength:=59)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_DeclareFunction_WithAttribute()
Dim code =
<Code>
Public Class C1
<System.CLSCompliant(True)>
Declare Function $$getUserName Lib "My1.dll" () As String
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=33, absoluteOffset:=81, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=60, absoluteOffset:=108, lineLength:=59)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_DeclareSub_WithoutAttribute()
Dim code =
<Code>
Public Class C1
Declare Sub $$getUserName Lib "My1.dll" ()
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
NullTextPoint),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=2, lineOffset:=28, absoluteOffset:=44, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=2, lineOffset:=45, absoluteOffset:=61, lineLength:=44)))
End Sub
<WorkItem(1839, "https://github.com/dotnet/roslyn/issues/1839")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGetEndPoint_DeclareSub_WithAttribute()
Dim code =
<Code>
Public Class C1
<System.CLSCompliant(True)>
Declare Sub $$getUserName Lib "My1.dll" ()
End Class
</Code>
TestGetEndPoint(code,
Part(EnvDTE.vsCMPart.vsCMPartAttributes,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter,
TextPoint(line:=2, lineOffset:=32, absoluteOffset:=48, lineLength:=31)),
Part(EnvDTE.vsCMPart.vsCMPartBody,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartHeader,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartName,
TextPoint(line:=3, lineOffset:=28, absoluteOffset:=76, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartNavigate,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartWhole,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)),
Part(EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
TextPoint(line:=3, lineOffset:=45, absoluteOffset:=93, lineLength:=44)))
End Sub
#End Region
#Region "Access tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess1()
Dim code =
<Code>
Class C
Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess2()
Dim code =
<Code>
Class C
Private Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPrivate)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess3()
Dim code =
<Code>
Class C
Protected Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProtected)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess4()
Dim code =
<Code>
Class C
Protected Friend Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess5()
Dim code =
<Code>
Class C
Friend Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessProject)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess6()
Dim code =
<Code>
Class C
Public Function $$F() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAccess7()
Dim code =
<Code>
Interface I
Function $$F() As Integer
End Interface
</Code>
TestAccess(code, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Sub
#End Region
#Region "Attribute Tests"
<WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPropertyGetAttribute_WithNoSet()
Dim code =
<Code>
Public Class Class1
Public Property Property1 As Integer
<Obsolete>
$$Get
Return 0
End Get
End Property
End Class
</Code>
TestAttributes(code, IsElement("Obsolete"))
End Sub
<WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPropertySetAttribute_WithNoGet()
Dim code =
<Code>
Public Class Class1
Public Property Property1 As Integer
<Obsolete>
$$Set(value As Integer)
End Set
End Property
End Class
</Code>
TestAttributes(code, IsElement("Obsolete"))
End Sub
<WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPropertySetAttribute_WithGet()
Dim code =
<Code>
Public Class Class1
Public Property Property1 As Integer
<Obsolete>
Get
Return 0
End Get
<Obsolete>
$$Set(value As Integer)
End Set
End Property
End Class
</Code>
TestAttributes(code, IsElement("Obsolete"))
End Sub
<WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPropertyGetAttribute_WithSet()
Dim code =
<Code>
Public Class Class1
Public Property Property1 As Integer
<Obsolete>
$$Get
Return 0
End Get
<Obsolete>
Set(value As Integer)
End Set
End Property
End Class
</Code>
TestAttributes(code, IsElement("Obsolete"))
End Sub
<WorkItem(2356, "https://github.com/dotnet/roslyn/issues/2356")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAttribute_1()
Dim code =
<Code>
Class Program
<Obsolete>
Sub F$$()
End Sub
End Class
</Code>
TestAttributes(code, IsElement("Obsolete"))
End Sub
#End Region
#Region "CanOverride tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride1()
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
TestCanOverride(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride2()
Dim code =
<Code>
Interface I
Sub $$Goo()
End Interface
</Code>
TestCanOverride(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride3()
Dim code =
<Code>
Class C
Protected Overridable Sub $$Goo()
End Sub
End Class
</Code>
TestCanOverride(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride4()
Dim code =
<Code>
Class C
Protected Sub $$Goo()
End Sub
End Class
</Code>
TestCanOverride(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride5()
Dim code =
<Code>
Class B
Protected Overridable Sub Goo()
End Sub
End Class
Class C
Inherits B
Protected Overrides Sub $$Goo()
End Sub
End Class
</Code>
TestCanOverride(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestCanOverride6()
Dim code =
<Code>
Class B
Protected Overridable Sub Goo()
End Sub
End Class
Class C
Inherits B
Protected NotOverridable Overrides Sub $$Goo()
End Sub
End Class
</Code>
TestCanOverride(code, False)
End Sub
#End Region
#Region "FunctionKind tests"
<WorkItem(1843, "https://github.com/dotnet/roslyn/issues/1843")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_Constructor()
Dim code =
<Code>
Public Class C1
Public Sub $$New()
End Sub
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionConstructor)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_Destructor()
Dim code =
<Code>
Public Class C1
Protected Overrides Sub $$Finalize()
MyBase.Finalize()
End Sub
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionDestructor)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_Sub()
Dim code =
<Code>
Public Class C1
Private Sub $$M()
End Sub
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionSub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_Function()
Dim code =
<Code>
Public Class C1
Private Function $$M() As Integer
End Sub
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_DeclareSub()
Dim code =
<Code>
Public Class C1
Private Declare Sub $$MethodB Lib "MyDll.dll" ()
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionSub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_DeclareFunction()
Dim code =
<Code>
Public Class C1
Private Declare Function $$MethodC Lib "MyDll.dll" () As Integer
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionFunction)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind__Operator()
Dim code =
<Code>
Imports System
Class C
Public Shared Operator $$+(x As C, y As C) As C
End Operator
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFunctionKind_Conversion()
Dim code =
<Code>
Imports System
Class C
Public Shared Operator Widening $$CType(x As Integer) As C
End Operator
End Class
</Code>
TestFunctionKind(code, EnvDTE.vsCMFunction.vsCMFunctionOperator)
End Sub
#End Region
#Region "MustImplement tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement1()
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
TestMustImplement(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement2()
Dim code =
<Code>
Interface I
Sub $$Goo()
End Interface
</Code>
TestMustImplement(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement3()
Dim code =
<Code>
Class C
Protected Overridable Sub $$Goo()
End Sub
End Class
</Code>
TestMustImplement(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement4()
Dim code =
<Code>
Class C
Protected Sub $$Goo()
End Sub
End Class
</Code>
TestMustImplement(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement5()
Dim code =
<Code>
Class B
Protected Overridable Sub Goo()
End Sub
End Class
Class C
Inherits B
Protected Overrides Sub $$Goo()
End Sub
End Class
</Code>
TestMustImplement(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestMustImplement6()
Dim code =
<Code>
Class B
Protected Overridable Sub Goo()
End Sub
End Class
Class C
Inherits B
Protected NotOverridable Overrides Sub $$Goo()
End Sub
End Class
</Code>
TestMustImplement(code, False)
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
Class C
MustOverride Sub $$Goo()
End Class
</Code>
TestName(code, "Goo")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_NoParens()
Dim code =
<Code>
Class C
Sub $$Goo
End Class
</Code>
TestName(code, "Goo")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_Constructor1()
Dim code =
<Code>
Class C
Sub $$New()
End Sub
End Class
</Code>
TestName(code, "New")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_Constructor2()
Dim code =
<Code>
Class C
Sub $$New()
End Class
</Code>
TestName(code, "New")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_Operator1()
Dim code =
<Code>
Class C
Shared Narrowing Operator $$CType(i As Integer) As C
End Operator
End Class
</Code>
TestName(code, "CType")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_Operator2()
Dim code =
<Code>
Class C
Shared Narrowing Operator $$CType(i As Integer) As C
End Class
</Code>
TestName(code, "CType")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName_Operator3()
Dim code =
<Code>
Class C
Shared Operator $$*(i As Integer, c As C) As C
End Operator
End Class
</Code>
TestName(code, "*")
End Sub
#End Region
#Region "Kind tests"
<WorkItem(2355, "https://github.com/dotnet/roslyn/issues/2355")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDeclareSubKind()
Dim code =
<Code>
Public Class Class1
Public Declare Sub $$f1 Lib "MyLib.dll" ()
End Class
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementDeclareDecl)
End Sub
<WorkItem(2355, "https://github.com/dotnet/roslyn/issues/2355")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDeclareFunctionKind()
Dim code =
<Code>
Public Class Class1
Public Declare Function f2$$ Lib "MyLib.dll" () As Integer
End Class
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementDeclareDecl)
End Sub
<WorkItem(2355, "https://github.com/dotnet/roslyn/issues/2355")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestSubKind()
Dim code =
<Code>
Public Class Class1
Public Sub F1$$()
End Sub
End Class
</Code>
TestKind(code, EnvDTE.vsCMElement.vsCMElementFunction)
End Sub
#End Region
#Region "OverrideKind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverrideKind_Abstract()
Dim code =
<Code>
MustInherit Class C
Protected MustOverride Sub $$Goo()
End Class
</Code>
TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverrideKind_Virtual()
Dim code =
<Code>
Class C
Protected Overridable Sub $$Goo()
End Sub
End Class
</Code>
TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverrideKind_Sealed()
Dim code =
<Code>
Class C
Protected NotOverridable Sub $$Goo()
End Sub
End Class
</Code>
TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverrideKind_Override()
Dim code =
<Code>
MustInherit Class B
Protected MustOverride Sub Goo()
End Class
Class C
Inherits B
Protected Overrides Sub $$Goo()
End Sub
End Class
</Code>
TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverrideKind_New()
Dim code =
<Code>
MustInherit Class B
Protected MustOverride Sub Goo()
End Class
Class C
Inherits B
Protected Shadows Sub $$Goo()
End Sub
End Class
</Code>
TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNew)
End Sub
#End Region
#Region "Prototype tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_UniqueSignature()
Dim code =
<Code>
Namespace N
Class C
Sub $$Goo()
End Sub
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeUniqueSignature, "M:N.C.Goo")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_FullName()
Dim code =
<Code>
Namespace N
Class C
Sub $$Goo()
End Sub
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeFullname, "N.C.Goo()")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_ClassName()
Dim code =
<Code>
Namespace N
Class C
Sub $$Goo()
End Sub
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeClassName, "C.Goo()")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_Type1()
Dim code =
<Code>
Namespace N
Class C
Sub $$Goo()
End Sub
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Goo()")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPrototype_Type2()
Dim code =
<Code>
Namespace N
Class C
Function $$Goo() As Integer
End Function
End Class
End Namespace
</Code>
TestPrototype(code, EnvDTE.vsCMPrototype.vsCMPrototypeType, "Goo() As Integer")
End Sub
#End Region
#Region "Type tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType1()
Dim code =
<Code>
Class C
Sub $$Goo()
End Sub
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "Void",
.AsFullName = "System.Void",
.CodeTypeFullName = "System.Void",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefVoid
})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType2()
Dim code =
<Code>
Class C
Function $$Goo$()
End Function
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "String",
.AsFullName = "System.String",
.CodeTypeFullName = "System.String",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString
})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType3()
Dim code =
<Code>
Class C
Function $$Goo() As String
End Function
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "String",
.AsFullName = "System.String",
.CodeTypeFullName = "System.String",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString
})
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestType4()
Dim code =
<Code>
MustInherit Class C
MustOverride Function $$Goo() As String
End Class
</Code>
TestTypeProp(code,
New CodeTypeRefData With {
.AsString = "String",
.AsFullName = "System.String",
.CodeTypeFullName = "System.String",
.TypeKind = EnvDTE.vsCMTypeRef.vsCMTypeRefString
})
End Sub
#End Region
#Region "AddAttribute tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Sub() As Task
Dim code =
<Code>
Imports System
Class C
Sub $$M()
End Sub
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Sub M()
End Sub
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Function() As Task
Dim code =
<Code>
Imports System
Class C
Function $$M() As integer
End Function
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Function M() As integer
End Function
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Sub_MustOverride() As Task
Dim code =
<Code>
Imports System
MustInherit Class C
MustOverride Sub $$M()
End Class
</Code>
Dim expected =
<Code>
Imports System
MustInherit Class C
<Serializable()>
MustOverride Sub M()
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Function_MustOverride() As Task
Dim code =
<Code>
Imports System
MustInherit Class C
MustOverride Function $$M() As integer
End Class
</Code>
Dim expected =
<Code>
Imports System
MustInherit Class C
<Serializable()>
MustOverride Function M() As integer
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_DeclareSub() As Task
Dim code =
<Code>
Imports System
Class C
Declare Sub $$M() Lib "MyDll.dll"
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Declare Sub M() Lib "MyDll.dll"
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_DeclareFunction() As Task
Dim code =
<Code>
Imports System
Class C
Declare Function $$M() Lib "MyDll.dll" As Integer
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Declare Function M() Lib "MyDll.dll" As Integer
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Constructor() As Task
Dim code =
<Code>
Imports System
Class C
Sub $$New()
End Sub
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Sub New()
End Sub
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Operator() As Task
Dim code =
<Code>
Imports System
Class C
Public Shared Operator $$+(x As C, y As C) As C
End Operator
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Public Shared Operator +(x As C, y As C) As C
End Operator
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Conversion() As Task
Dim code =
<Code>
Imports System
Class C
Public Shared Operator Widening $$CType(x As Integer) As C
End Operator
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
<Serializable()>
Public Shared Operator Widening CType(x As Integer) As C
End Operator
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Sub_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Sub $$M()
End Sub
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Sub M()
End Sub
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Function_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Function $$M() As integer
End Function
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Function M() As integer
End Function
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Sub_MustOverride_BelowDocComment() As Task
Dim code =
<Code>
Imports System
MustInherit Class C
''' <summary></summary>
MustOverride Sub $$M()
End Class
</Code>
Dim expected =
<Code>
Imports System
MustInherit Class C
''' <summary></summary>
<Serializable()>
MustOverride Sub M()
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Function_MustOverride_BelowDocComment() As Task
Dim code =
<Code>
Imports System
MustInherit Class C
''' <summary></summary>
MustOverride Function $$M() As integer
End Class
</Code>
Dim expected =
<Code>
Imports System
MustInherit Class C
''' <summary></summary>
<Serializable()>
MustOverride Function M() As integer
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_DeclareSub_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Declare Sub $$M() Lib "MyDll.dll"
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Declare Sub M() Lib "MyDll.dll"
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_DeclareFunction_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Declare Function $$M() Lib "MyDll.dll" As Integer
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Declare Function M() Lib "MyDll.dll" As Integer
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Constructor_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Sub $$New()
End Sub
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Sub New()
End Sub
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Operator_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Public Shared Operator $$+(x As C, y As C) As C
End Operator
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Public Shared Operator +(x As C, y As C) As C
End Operator
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_Conversion_BelowDocComment() As Task
Dim code =
<Code>
Imports System
Class C
''' <summary></summary>
Public Shared Operator Widening $$CType(x As Integer) As C
End Operator
End Class
</Code>
Dim expected =
<Code>
Imports System
Class C
''' <summary></summary>
<Serializable()>
Public Shared Operator Widening CType(x As Integer) As C
End Operator
End Class
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
#End Region
#Region "AddParameter tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter1() As Task
Dim code =
<Code>
Class C
Sub $$M()
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(a As Integer)
End Sub
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "a", .Type = "Integer"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter2() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(b As String, a As Integer)
End Sub
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter3() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer, b As String)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(a As Integer, c As Boolean, b As String)
End Sub
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "c", .Type = "System.Boolean", .Position = 1})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter4() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(a As Integer, b As String)
End Sub
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String", .Position = -1})
End Function
<WorkItem(1873, "https://github.com/dotnet/roslyn/issues/1873")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter_DeclareFunction() As Task
Dim code =
<Code>
Public Class C1
Declare Function $$getUserName Lib "My1.dll" (a As Integer) As String
End Class
</Code>
Dim expected =
<Code>
Public Class C1
Declare Function getUserName Lib "My1.dll" (a As Integer, b As String) As String
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String", .Position = -1})
End Function
<WorkItem(1873, "https://github.com/dotnet/roslyn/issues/1873")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddParameter_DeclareSub() As Task
Dim code =
<Code>
Public Class C1
Declare Sub $$getUserName Lib "My1.dll" (a As Integer)
End Class
</Code>
Dim expected =
<Code>
Public Class C1
Declare Sub getUserName Lib "My1.dll" (a As Integer, b As String)
End Class
</Code>
Await TestAddParameter(code, expected, New ParameterData With {.Name = "b", .Type = "String", .Position = -1})
End Function
#End Region
#Region "RemoveParameter tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveParameter1() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M()
End Sub
End Class
</Code>
Await TestRemoveChild(code, expected, "a")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveParameter2() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer, b As String)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(a As Integer)
End Sub
End Class
</Code>
Await TestRemoveChild(code, expected, "b")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveParameter3() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer, b As String)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(b As String)
End Sub
End Class
</Code>
Await TestRemoveChild(code, expected, "a")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveParameter4() As Task
Dim code =
<Code>
Class C
Sub $$M(a As Integer, b As String, c As Integer)
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub M(a As Integer, c As Integer)
End Sub
End Class
</Code>
Await TestRemoveChild(code, expected, "b")
End Function
#End Region
#Region "Set Access tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess1() As Task
Dim code =
<Code>
Class C
Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Public Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess2() As Task
Dim code =
<Code>
Class C
Public Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Friend Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProject)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess3() As Task
Dim code =
<Code>
Class C
Protected Friend Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Public Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess4() As Task
Dim code =
<Code>
Class C
Public Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Protected Friend Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess5() As Task
Dim code =
<Code>
Class C
Public Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessDefault)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess6() As Task
Dim code =
<Code>
Interface C
Function $$Goo() As Integer
End Class
</Code>
Dim expected =
<Code>
Interface C
Function Goo() As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected, ThrowsArgumentException(Of EnvDTE.vsCMAccess)())
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetAccess7() As Task
Dim code =
<Code>
Interface C
Function $$Goo() As Integer
End Class
</Code>
Dim expected =
<Code>
Interface C
Function Goo() As Integer
End Class
</Code>
Await TestSetAccess(code, expected, EnvDTE.vsCMAccess.vsCMAccessPublic)
End Function
#End Region
#Region "Set CanOverride tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetCanOverride1() As Task
Dim code =
<Code>
MustInherit Class C
Overridable Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Overridable Sub Goo()
End Sub
End Class
</Code>
Await TestSetCanOverride(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetCanOverride2() As Task
Dim code =
<Code>
MustInherit Class C
Overridable Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Sub Goo()
End Sub
End Class
</Code>
Await TestSetCanOverride(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetCanOverride3() As Task
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Overridable Sub Goo()
End Sub
End Class
</Code>
Await TestSetCanOverride(code, expected, True)
End Function
#End Region
#Region "Set MustImplement tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetMustImplement1() As Task
Dim code =
<Code>
MustInherit Class C
Overridable Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
MustOverride Sub Goo()
End Class
</Code>
Await TestSetMustImplement(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetMustImplement2() As Task
Dim code =
<Code>
MustInherit Class C
Overridable Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Sub Goo()
End Sub
End Class
</Code>
Await TestSetMustImplement(code, expected, False)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetMustImplement3() As Task
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
MustOverride Sub Goo()
End Class
</Code>
Await TestSetMustImplement(code, expected, True)
End Function
#End Region
#Region "Set IsShared tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared1() As Task
Dim code =
<Code>
Class C
Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Shared Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetIsShared(code, expected, True)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetIsShared2() As Task
Dim code =
<Code>
Class C
Shared Function $$Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Function Goo() As Integer
Throw New NotImplementedException()
End Function
End Class
</Code>
Await TestSetIsShared(code, expected, False)
End Function
#End Region
#Region "Set Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName1() As Task
Dim code =
<Code>
Class C
Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub Bar()
End Sub
End Class
</Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
#End Region
#Region "Set OverrideKind tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetOverrideKind1() As Task
Dim code =
<Code>
MustInherit Class C
Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Sub Goo()
End Sub
End Class
</Code>
Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetOverrideKind2() As Task
Dim code =
<Code>
MustInherit Class C
Sub $$Goo()
End Sub
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
MustOverride Sub Goo()
End Class
</Code>
Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetOverrideKind3() As Task
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
Sub Goo()
End Sub
End Class
</Code>
Await TestSetOverrideKind(code, expected, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone)
End Function
#End Region
#Region "Set Type tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType1() As Task
Dim code =
<Code>
Class C
Sub $$Goo()
Dim i As Integer
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub Goo()
Dim i As Integer
End Sub
End Class
</Code>
Await TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType2() As Task
Dim code =
<Code>
Class C
Sub $$Goo()
Dim i As Integer
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Function Goo() As Integer
Dim i As Integer
End Function
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType3() As Task
Dim code =
<Code>
Class C
Function $$Goo() As System.Int32
Dim i As Integer
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Function Goo() As String
Dim i As Integer
End Function
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.String")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType4() As Task
Dim code =
<Code>
Class C
Function $$Goo() As System.Int32
Dim i As Integer
End Function
End Class
</Code>
Dim expected =
<Code>
Class C
Sub Goo()
Dim i As Integer
End Sub
End Class
</Code>
Await TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType5() As Task
Dim code =
<Code>
MustInherit Class C
MustOverride Function $$Goo() As System.Int32
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
MustOverride Sub Goo()
End Class
</Code>
Await TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef))
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType6() As Task
Dim code =
<Code>
MustInherit Class C
MustOverride Sub $$Goo()
End Class
</Code>
Dim expected =
<Code>
MustInherit Class C
MustOverride Function Goo() As Integer
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType7() As Task
Dim code =
<Code>
Class C
Sub $$New()
End Sub
End Class
</Code>
Dim expected =
<Code>
Class C
Sub New()
End Sub
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType8() As Task
Dim code =
<Code>
Class C
Shared Narrowing Operator $$CType(i As Integer) As C
End Operator
End Class
</Code>
Dim expected =
<Code>
Class C
Shared Narrowing Operator CType(i As Integer) As C
End Operator
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
<WorkItem(1873, "https://github.com/dotnet/roslyn/issues/1873")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType_DeclareFunction() As Task
Dim code =
<Code>
Public Class C1
Declare Function $$getUserName Lib "My1.dll" (a As Integer) As String
End Class
</Code>
Dim expected =
<Code>
Public Class C1
Declare Function getUserName Lib "My1.dll" (a As Integer) As Integer
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
<WorkItem(1873, "https://github.com/dotnet/roslyn/issues/1873")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType_DeclareFunctionToSub() As Task
Dim code =
<Code>
Public Class C1
Declare Function $$getUserName Lib "My1.dll" (a As Integer) As String
End Class
</Code>
Dim expected =
<Code>
Public Class C1
Declare Sub getUserName Lib "My1.dll" (a As Integer)
End Class
</Code>
Await TestSetTypeProp(code, expected, CType(Nothing, EnvDTE.CodeTypeRef))
End Function
<WorkItem(1873, "https://github.com/dotnet/roslyn/issues/1873")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetType_DeclareSubToFunction() As Task
Dim code =
<Code>
Public Class C1
Declare Sub $$getUserName Lib "My1.dll" (a As Integer)
End Class
</Code>
Dim expected =
<Code>
Public Class C1
Declare Function getUserName Lib "My1.dll" (a As Integer) As Integer
End Class
</Code>
Await TestSetTypeProp(code, expected, "System.Int32")
End Function
#End Region
#Region "PartialMethodExtender"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsPartial1()
Dim code =
<Code>
Partial Public Class Class2
Public Sub $$M(i As Integer)
End Sub
Partial Private Sub M()
End Sub
Private Sub M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsPartial(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsPartial2()
Dim code =
<Code>
Partial Public Class Class2
Public Sub M(i As Integer)
End Sub
Partial Private Sub $$M()
End Sub
Private Sub M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsPartial(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsPartial3()
Dim code =
<Code>
Partial Public Class Class2
Public Sub M(i As Integer)
End Sub
Partial Private Sub M()
End Sub
Private Sub $$M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsPartial(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsDeclaration1()
Dim code =
<Code>
Partial Public Class Class2
Public Sub $$M(i As Integer)
End Sub
Partial Private Sub M()
End Sub
Private Sub M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsDeclaration(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsDeclaration2()
Dim code =
<Code>
Partial Public Class Class2
Public Sub M(i As Integer)
End Sub
Partial Private Sub $$M()
End Sub
Private Sub M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsDeclaration(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestPartialMethodExtender_IsDeclaration3()
Dim code =
<Code>
Partial Public Class Class2
Public Sub M(i As Integer)
End Sub
Partial Private Sub M()
End Sub
Private Sub $$M()
End Sub
End Class
</Code>
TestPartialMethodExtender_IsDeclaration(code, False)
End Sub
#End Region
#Region "Overloads Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsOverloaded1()
Dim code =
<Code>
Class C
Sub $$Goo(x As C)
End Sub
End Class
</Code>
TestIsOverloaded(code, False)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestIsOverloaded2()
Dim code =
<Code>
Class C
Sub Goo()
End Sub
Sub $$Goo(x As C)
End Sub
End Class
</Code>
TestIsOverloaded(code, True)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverloads1()
Dim code =
<Code>
Class C
Sub $$Goo()
End Sub
Sub Goo(x As C)
End Sub
End Class
</Code>
TestOverloadsUniqueSignatures(code, "M:C.Goo", "M:C.Goo(C)")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverloads2()
Dim code =
<Code>
Class C
Sub $$Goo()
End Sub
End Class
</Code>
TestOverloadsUniqueSignatures(code, "M:C.Goo")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestOverloads3()
Dim code =
<Code>
Class C
Shared Operator $$*(i As Integer, c As C) As C
End Operator
End Class
</Code>
TestOverloadsUniqueSignatures(code, "M:C.op_Multiply(System.Int32,C)")
End Sub
#End Region
#Region "Parameter name tests"
<WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParameterNameWithEscapeCharacters()
Dim code =
<Code>
Class C
Sub $$M1([integer] As Integer)
End Sub
End Class
</Code>
TestAllParameterNames(code, "[integer]")
End Sub
<WorkItem(1147885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1147885")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParameterNameWithEscapeCharacters_2()
Dim code =
<Code>
Class C
Sub $$M1([integer] As Integer, [string] as String)
End Sub
End Class
</Code>
TestAllParameterNames(code, "[integer]", "[string]")
End Sub
#End Region
Private Function GetPartialMethodExtender(codeElement As EnvDTE80.CodeFunction2) As IVBPartialMethodExtender
Return CType(codeElement.Extender(ExtenderNames.VBPartialMethodExtender), IVBPartialMethodExtender)
End Function
Protected Overrides Function PartialMethodExtender_GetIsPartial(codeElement As EnvDTE80.CodeFunction2) As Boolean
Return GetPartialMethodExtender(codeElement).IsPartial
End Function
Protected Overrides Function PartialMethodExtender_GetIsDeclaration(codeElement As EnvDTE80.CodeFunction2) As Boolean
Return GetPartialMethodExtender(codeElement).IsDeclaration
End Function
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
|
AlekseyTs/roslyn
|
src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeFunctionTests.vb
|
Visual Basic
|
mit
| 79,179
|
' 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.Collections.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Partial Friend Class DocumentationCommentCompiler
Inherits VisualBasicSymbolVisitor
''' <summary>
''' Walks a DocumentationCommentTriviaSyntax, binding the semantically meaningful parts
''' to produce diagnostics and to replace source crefs with documentation comment IDs.
''' </summary>
Private Class DocumentationCommentWalker
Inherits VisualBasicSyntaxWalker
Private ReadOnly _symbol As Symbol
Private ReadOnly _syntaxTree As SyntaxTree
Private ReadOnly _wellKnownElementNodes As Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax))
Private ReadOnly _reportDiagnostics As Boolean
Private ReadOnly _writer As TextWriter
Private ReadOnly _diagnostics As DiagnosticBag
Private Sub New(symbol As Symbol,
syntaxTree As SyntaxTree,
wellKnownElementNodes As Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax)),
writer As TextWriter,
diagnostics As DiagnosticBag)
MyBase.New(SyntaxWalkerDepth.Token)
Debug.Assert(symbol IsNot Nothing)
Debug.Assert(syntaxTree IsNot Nothing)
Debug.Assert(diagnostics IsNot Nothing)
Me._symbol = symbol
Me._syntaxTree = syntaxTree
Me._wellKnownElementNodes = wellKnownElementNodes
Me._writer = writer
Me._diagnostics = diagnostics
Me._reportDiagnostics = syntaxTree.ReportDocumentationCommentDiagnostics()
End Sub
Private Sub CaptureWellKnownTagNode(node As XmlNodeSyntax, name As XmlNodeSyntax)
Debug.Assert(node IsNot Nothing)
Debug.Assert(name IsNot Nothing)
If Me._wellKnownElementNodes Is Nothing Then
Return
End If
If name.Kind <> SyntaxKind.XmlName Then
Return
End If
Dim xmlName = DirectCast(name, XmlNameSyntax).LocalName.ValueText
Dim tag As WellKnownTag = GetWellKnownTag(xmlName)
If (tag And WellKnownTag.AllCollectable) = 0 Then
Return
End If
Dim builder As ArrayBuilder(Of XmlNodeSyntax) = Nothing
If Not Me._wellKnownElementNodes.TryGetValue(tag, builder) Then
builder = ArrayBuilder(Of XmlNodeSyntax).GetInstance()
Me._wellKnownElementNodes.Add(tag, builder)
End If
builder.Add(node)
End Sub
Public Overrides Sub VisitXmlEmptyElement(node As XmlEmptyElementSyntax)
CaptureWellKnownTagNode(node, node.Name)
MyBase.VisitXmlEmptyElement(node)
End Sub
Public Overrides Sub VisitXmlElement(node As XmlElementSyntax)
CaptureWellKnownTagNode(node, node.StartTag.Name)
MyBase.VisitXmlElement(node)
End Sub
Private Sub WriteHeaderAndVisit(symbol As Symbol, trivia As DocumentationCommentTriviaSyntax)
Me._writer.Write("<member name=""")
Me._writer.Write(symbol.GetDocumentationCommentId())
Me._writer.WriteLine(""">")
Visit(trivia)
Me._writer.WriteLine("</member>")
End Sub
''' <summary>
''' Given a DocumentationCommentTriviaSyntax, return the full text, but with
''' documentation comment IDs substituted into crefs.
''' </summary>
Friend Shared Function GetSubstitutedText(symbol As Symbol,
trivia As DocumentationCommentTriviaSyntax,
wellKnownElementNodes As Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax)),
diagnostics As DiagnosticBag) As String
Dim pooled As PooledStringBuilder = PooledStringBuilder.GetInstance()
Using writer As New StringWriter(pooled.Builder)
Dim walker = New DocumentationCommentWalker(symbol, trivia.SyntaxTree, wellKnownElementNodes, writer, diagnostics)
walker.WriteHeaderAndVisit(symbol, trivia)
End Using
Return pooled.ToStringAndFree()
End Function
Private ReadOnly Property Compilation As VisualBasicCompilation
Get
Return Me._symbol.DeclaringCompilation
End Get
End Property
Private ReadOnly Property [Module] As SourceModuleSymbol
Get
Return DirectCast(Me.Compilation.SourceModule, SourceModuleSymbol)
End Get
End Property
Public Overrides Sub DefaultVisit(node As SyntaxNode)
Dim kind As SyntaxKind = node.Kind()
If kind = SyntaxKind.XmlCrefAttribute Then
Dim crefAttr = DirectCast(node, XmlCrefAttributeSyntax)
' Write [cref="]
Visit(crefAttr.Name)
VisitToken(crefAttr.EqualsToken)
VisitToken(crefAttr.StartQuoteToken)
Dim reference As CrefReferenceSyntax = crefAttr.Reference
Debug.Assert(Not reference.ContainsDiagnostics)
Dim crefBinder = CreateDocumentationCommentBinderForSymbol(Me.Module, Me._symbol, Me._syntaxTree, DocumentationCommentBinder.BinderType.Cref)
Dim useSiteDiagnostics As HashSet(Of DiagnosticInfo) = Nothing
Dim diagnostics = DiagnosticBag.GetInstance
Dim result As ImmutableArray(Of Symbol) = crefBinder.BindInsideCrefAttributeValue(reference, preserveAliases:=False, diagnosticBag:=diagnostics, useSiteDiagnostics:=useSiteDiagnostics)
Dim errorLocations = diagnostics.ToReadOnlyAndFree().SelectAsArray(Function(x) x.Location).WhereAsArray(Function(x) x IsNot Nothing)
If Not useSiteDiagnostics.IsNullOrEmpty AndAlso Me._reportDiagnostics Then
ProcessErrorLocations(node, errorLocations, useSiteDiagnostics, Nothing)
End If
If result.IsEmpty Then
' We were not able to find anything by this name,
' generate diagnostic and use errorneous
ProcessErrorLocations(crefAttr, errorLocations, Nothing, ERRID.WRN_XMLDocCrefAttributeNotFound1)
ElseIf result.Length > 1 AndAlso reference.Signature IsNot Nothing Then
' In strict mode we don't allow ambiguities
ProcessErrorLocations(crefAttr, errorLocations, Nothing, ERRID.WRN_XMLDocCrefAttributeNotFound1)
Else
' Dev11 seems to ignore any ambiguity and use the first symbol it finds,
' we have to repro this behavior
Dim compilation As VisualBasicCompilation = Me.Compilation
' Some symbols found may not support doc-comment-ids and we just filter those out.
' From the rest of the symbols we take the symbol with 'smallest' documentation
' comment id: we want to ensure that when we compile the same compilation several
' times we deterministically use/write the same documentation id each time, and it
' does not matter much which one it is. So instead of doing sofisticated location
' based sorting we just choose the lexically smallest documentation id.
Dim smallestSymbolCommentId As String = Nothing
Dim errid As ERRID = ERRID.WRN_XMLDocCrefAttributeNotFound1
For Each symbol In result
If symbol.Kind = SymbolKind.TypeParameter Then
errid = ERRID.WRN_XMLDocCrefToTypeParameter
Continue For
End If
Dim candidateId As String = symbol.OriginalDefinition.GetDocumentationCommentId()
If candidateId IsNot Nothing AndAlso (smallestSymbolCommentId Is Nothing OrElse String.CompareOrdinal(smallestSymbolCommentId, candidateId) > 0) Then
smallestSymbolCommentId = candidateId
End If
Next
If smallestSymbolCommentId Is Nothing Then
' some symbols were found, but none of them has id
ProcessErrorLocations(crefAttr, errorLocations, Nothing, errid)
ElseIf Me._writer IsNot Nothing Then
' Write [<id>]
Me._writer.Write(smallestSymbolCommentId)
End If
End If
' Write ["]
VisitToken(crefAttr.EndQuoteToken)
' We are done with this node
Return
ElseIf kind = SyntaxKind.XmlAttribute Then
Dim attr = DirectCast(node, XmlAttributeSyntax)
If Not attr.ContainsDiagnostics Then
' Check name: this may be either 'cref' or 'name' in 'param',
' 'paramref', 'typeparam' or 'typeparamref' well-known tags
Dim attrName = DirectCast(attr.Name, XmlNameSyntax)
If DocumentationCommentXmlNames.AttributeEquals(attrName.LocalName.ValueText,
DocumentationCommentXmlNames.CrefAttributeName) Then
' If this is 'cref=', this node can be created for two reasons:
' (a) the value is represented in a form "X:SOME-ID-STRING", or
' (b) the value between '"' is not a valid NameSyntax
'
' in both cases we want just to put the result into documentation XML,
' but in the second case we also generate a diagnostic and add '!:' in from
' of the value indicating wrong id
'
' Other value types should have produced diagnostic on the syntax node
Dim str = DirectCast(attr.Value, XmlStringSyntax)
Dim strValue = Binder.GetXmlString(str.TextTokens)
Dim needError As Boolean = strValue.Length < 2 OrElse strValue(0) = ":"c OrElse strValue(1) <> ":"c
' Write [cref="]
Visit(attr.Name)
VisitToken(attr.EqualsToken)
VisitToken(str.StartQuoteToken)
If needError AndAlso Me._reportDiagnostics Then
Me._diagnostics.Add(ERRID.WRN_XMLDocCrefAttributeNotFound1, node.GetLocation(), strValue.Trim())
End If
If needError AndAlso Me._writer IsNot Nothing Then
Me._writer.Write("!:")
End If
' Write [<attr-value>]
For Each tk In str.TextTokens
VisitToken(tk)
Next
' Write ["]
VisitToken(str.EndQuoteToken)
' We are done with this node
Return
End If
' Otherview go to default visitor
End If
' Otherview go to default visitor
End If
MyBase.DefaultVisit(node)
End Sub
Private Sub ProcessErrorLocations(node As SyntaxNode, errorLocations As ImmutableArray(Of Location), useSiteDiagnostics As HashSet(Of DiagnosticInfo), errid As Nullable(Of ERRID))
Dim crefAttr = TryCast(node, XmlCrefAttributeSyntax)
If crefAttr IsNot Nothing AndAlso errid.HasValue Then
If errorLocations.Length = 0 Then
ProcessBadNameInCrefAttribute(crefAttr, crefAttr.GetLocation, errid.Value)
Else
For Each location In errorLocations
ProcessBadNameInCrefAttribute(crefAttr, location, errid.Value)
Next
End If
ElseIf errorLocations.Length = 0 AndAlso useSiteDiagnostics IsNot Nothing Then
Me._diagnostics.Add(node, useSiteDiagnostics)
ElseIf useSiteDiagnostics IsNot Nothing Then
For Each location In errorLocations
Me._diagnostics.Add(location, useSiteDiagnostics)
Next
End If
End Sub
Private Sub ProcessBadNameInCrefAttribute(crefAttribute As XmlCrefAttributeSyntax, errorLocation As Location, errid As ERRID)
' Write [!:<name>]
If Me._writer IsNot Nothing Then
Me._writer.Write("!:")
End If
Dim reference As VisualBasicSyntaxNode = crefAttribute.Reference
Visit(reference) ' This will write the name to XML
If Me._reportDiagnostics Then
Dim location = If(errorLocation, reference.GetLocation)
Me._diagnostics.Add(errid, location, reference.ToFullString().TrimEnd(Nothing))
End If
End Sub
Public Overrides Sub VisitToken(token As SyntaxToken)
If Me._writer IsNot Nothing Then
token.WriteTo(Me._writer)
End If
MyBase.VisitToken(token)
End Sub
End Class
End Class
End Class
End Namespace
|
furesoft/roslyn
|
src/Compilers/VisualBasic/Portable/Compilation/DocumentationComments/DocumentationCommentWalker.vb
|
Visual Basic
|
apache-2.0
| 16,134
|
' 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 TypeOfKeywordRecommenderTests
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NoneInClassDeclarationTest() As Task
Await VerifyRecommendationsMissingAsync(<ClassDeclaration>|</ClassDeclaration>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfNotInStatementTest() As Task
Await VerifyRecommendationsMissingAsync(<MethodBody>|</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterReturnTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Return |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterArgument1Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Foo(|</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterArgument2Test() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Foo(bar, |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterBinaryExpressionTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Foo(bar + |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterNotTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Foo(Not |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterTypeOfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If TypeOf |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterDoWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do While |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterDoUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Do Until |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterLoopWhileTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop While |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterLoopUntilTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>
Do
Loop Until |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>If |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterElseIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>ElseIf |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterElseSpaceIfTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Else If |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterErrorTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Error |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterThrowTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Throw |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterInitializerTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = |</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterArrayInitializerSquiggleTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {|</MethodBody>, "TypeOf")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function TypeOfAfterArrayInitializerCommaTest() As Task
Await VerifyRecommendationsContainAsync(<MethodBody>Dim x = {0, |</MethodBody>, "TypeOf")
End Function
<WorkItem(543270, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543270")>
<Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Async Function NotInDelegateCreationTest() As Task
Dim code =
<File>
Module Program
Sub Main(args As String())
Dim f1 As New Foo2( |
End Sub
Delegate Sub Foo2()
Function Bar2() As Object
Return Nothing
End Function
End Module
</File>
Await VerifyRecommendationsMissingAsync(code, "TypeOf")
End Function
End Class
End Namespace
|
amcasey/roslyn
|
src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/TypeOfKeywordRecommenderTests.vb
|
Visual Basic
|
apache-2.0
| 6,095
|
Imports System
Imports Aspose.Cells
Imports Aspose.Cells.Drawing
Namespace Articles
Public Class CheckHiddenExternalLinks
Public Shared Sub Run()
' ExStart:CheckHiddenExternalLinks
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
' Loads the workbook which contains hidden external links
Dim workbook As New Workbook(dataDir & Convert.ToString("sample.xlsx"))
' Access the external link collection of the workbook
Dim links As ExternalLinkCollection = workbook.Worksheets.ExternalLinks
' Print all the external links and check there IsVisible property
For i As Integer = 0 To links.Count - 1
Console.WriteLine("Data Source: " & links(i).DataSource)
Console.WriteLine("Is Referred: " & links(i).IsReferred)
Console.WriteLine("Is Visible: " & links(i).IsVisible)
Console.WriteLine()
Next
' ExEnd:CheckHiddenExternalLinks
End Sub
End Class
End Namespace
|
maria-shahid-aspose/Aspose.Cells-for-.NET
|
Examples/VisualBasic/Articles/CheckHiddenExternalLinks.vb
|
Visual Basic
|
mit
| 1,177
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class JobCreationBox
Inherits System.Windows.Forms.UserControl
'UserControl overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container()
Me.Label1 = New System.Windows.Forms.Label()
Me.ClientTextBox = New System.Windows.Forms.TextBox()
Me.Label2 = New System.Windows.Forms.Label()
Me.Label3 = New System.Windows.Forms.Label()
Me.StartDateTimePicker = New System.Windows.Forms.DateTimePicker()
Me.Label4 = New System.Windows.Forms.Label()
Me.NotesTextBox = New System.Windows.Forms.TextBox()
Me.RateTextBox = New System.Windows.Forms.TextBox()
Me.ClientErrorProvider = New System.Windows.Forms.ErrorProvider(Me.components)
Me.RateErrorProvider = New System.Windows.Forms.ErrorProvider(Me.components)
CType(Me.ClientErrorProvider, System.ComponentModel.ISupportInitialize).BeginInit()
CType(Me.RateErrorProvider, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.Location = New System.Drawing.Point(25, 4)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(33, 13)
Me.Label1.TabIndex = 0
Me.Label1.Text = "&Client"
'
'ClientTextBox
'
Me.ClientTextBox.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.ClientTextBox.Location = New System.Drawing.Point(4, 21)
Me.ClientTextBox.Name = "ClientTextBox"
Me.ClientTextBox.Size = New System.Drawing.Size(166, 20)
Me.ClientTextBox.TabIndex = 1
'
'Label2
'
Me.Label2.AutoSize = True
Me.Label2.Location = New System.Drawing.Point(16, 48)
Me.Label2.Name = "Label2"
Me.Label2.Size = New System.Drawing.Size(30, 13)
Me.Label2.TabIndex = 2
Me.Label2.Text = "&Rate"
'
'Label3
'
Me.Label3.AutoSize = True
Me.Label3.Location = New System.Drawing.Point(19, 91)
Me.Label3.Name = "Label3"
Me.Label3.Size = New System.Drawing.Size(55, 13)
Me.Label3.TabIndex = 4
Me.Label3.Text = "&Start Date"
'
'StartDateTimePicker
'
Me.StartDateTimePicker.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.StartDateTimePicker.Location = New System.Drawing.Point(4, 108)
Me.StartDateTimePicker.Name = "StartDateTimePicker"
Me.StartDateTimePicker.Size = New System.Drawing.Size(183, 20)
Me.StartDateTimePicker.TabIndex = 5
'
'Label4
'
Me.Label4.AutoSize = True
Me.Label4.Location = New System.Drawing.Point(22, 135)
Me.Label4.Name = "Label4"
Me.Label4.Size = New System.Drawing.Size(35, 13)
Me.Label4.TabIndex = 6
Me.Label4.Text = "&Notes"
'
'NotesTextBox
'
Me.NotesTextBox.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.NotesTextBox.Location = New System.Drawing.Point(4, 151)
Me.NotesTextBox.Multiline = True
Me.NotesTextBox.Name = "NotesTextBox"
Me.NotesTextBox.Size = New System.Drawing.Size(188, 30)
Me.NotesTextBox.TabIndex = 7
'
'RateTextBox
'
Me.RateTextBox.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) _
Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.RateTextBox.Location = New System.Drawing.Point(4, 68)
Me.RateTextBox.Name = "RateTextBox"
Me.RateTextBox.Size = New System.Drawing.Size(166, 20)
Me.RateTextBox.TabIndex = 3
'
'ClientErrorProvider
'
Me.ClientErrorProvider.ContainerControl = Me
'
'RateErrorProvider
'
Me.RateErrorProvider.ContainerControl = Me
'
'JobCreationBox
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.Controls.Add(Me.RateTextBox)
Me.Controls.Add(Me.NotesTextBox)
Me.Controls.Add(Me.Label4)
Me.Controls.Add(Me.StartDateTimePicker)
Me.Controls.Add(Me.Label3)
Me.Controls.Add(Me.Label2)
Me.Controls.Add(Me.ClientTextBox)
Me.Controls.Add(Me.Label1)
Me.Name = "JobCreationBox"
Me.Size = New System.Drawing.Size(195, 184)
CType(Me.ClientErrorProvider, System.ComponentModel.ISupportInitialize).EndInit()
CType(Me.RateErrorProvider, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents ClientTextBox As System.Windows.Forms.TextBox
Friend WithEvents Label2 As System.Windows.Forms.Label
Friend WithEvents Label3 As System.Windows.Forms.Label
Friend WithEvents StartDateTimePicker As System.Windows.Forms.DateTimePicker
Friend WithEvents Label4 As System.Windows.Forms.Label
Friend WithEvents NotesTextBox As System.Windows.Forms.TextBox
Friend WithEvents RateTextBox As System.Windows.Forms.TextBox
Friend WithEvents ClientErrorProvider As System.Windows.Forms.ErrorProvider
Friend WithEvents RateErrorProvider As System.Windows.Forms.ErrorProvider
End Class
|
winny-/CPS-240
|
Assignments/FP Freelance Time Tracker/FP Freelance Time Tracker/JobCreationBox.Designer.vb
|
Visual Basic
|
mit
| 6,739
|
Public Class Trends
Private token As OauthTokens
Friend Sub New(ByVal t As OauthTokens)
token = t
End Sub
''' <summary>
''' Get trends of selected place
''' </summary>
''' <param name="parameter">Parameters</param>
Public Function Place(ByVal parameter As RequestParam) As ResponseObject(Of TrendsPlaceObjectList)
If IsNothing(parameter) Then
Throw New ArgumentException("parameter")
End If
Return New ResponseObject(Of TrendsPlaceObjectList)(TwitterAccess.GETAccess(EndPoints.Trends_Place, token, parameter))
End Function
''' <summary>
''' Get trends of available
''' </summary>
Public Function Available() As ResponseObject(Of TrendsObjectList)
Return New ResponseObject(Of TrendsObjectList)(TwitterAccess.GETAccess(EndPoints.Trends_Available, token))
End Function
''' <summary>
''' Get trends of closest
''' </summary>
''' <param name="parameter">Parameters</param>
Public Function Closest(ByVal parameter As RequestParam) As ResponseObject(Of TrendsObjectList)
If IsNothing(parameter) Then
Throw New ArgumentException("parameter")
End If
Return New ResponseObject(Of TrendsObjectList)(TwitterAccess.GETAccess(EndPoints.Trends_Closest, token, parameter))
End Function
End Class
|
szr2000/FistTwit
|
FistTwit/Methods/Trends.vb
|
Visual Basic
|
mit
| 1,355
|
Public Class JhSerializer
Public MustInherit Class JhsValue
End Class
Public Class JhsObject
Inherits JhsValue
Implements IEnumerable(Of KeyValuePair(Of String, JhsValue))
Public ReadOnly Members As New Dictionary(Of String, JhsValue) 'It appears that this collection type does preserve adding order - so no need to make our own
Public Sub Add(memberKey As String, value As Boolean)
Members.Add(memberKey, New JhsBoolean(value))
End Sub
Public Sub Add(memberKey As String, value As Int64)
Members.Add(memberKey, New JhsInteger(value))
End Sub
Public Sub Add(memberKey As String, value As Double)
Members.Add(memberKey, New JhsFloat(value))
End Sub
Public Sub Add(memberKey As String, value As String)
Members.Add(memberKey, New JhsString(value))
End Sub
Public Sub Add(memberKey As String, value As DateTime)
Members.Add(memberKey, New JhsDateTime(value))
End Sub
Public Sub Add(memberKey As String, value As Byte())
Members.Add(memberKey, New JhsBinary(value))
End Sub
Public Sub Add(memberKey As String, value As JhsValue)
Members.Add(memberKey, value)
End Sub
Public Function GetBool(memberKey As String) As Boolean
Return DirectCast(Members(memberKey), JhsBoolean).Value
End Function
Public Function GetBool(memberKey As String, [default] As Boolean) As Boolean
If Not Members.ContainsKey(memberKey) Then Return [default]
Return DirectCast(Members(memberKey), JhsBoolean).Value
End Function
Public Function GetInt64(memberKey As String) As Int64
Return DirectCast(Members(memberKey), JhsInteger).Value
End Function
Public Function GetInt64(memberKey As String, [default] As Int64) As Int64
If Not Members.ContainsKey(memberKey) Then Return [default]
Return DirectCast(Members(memberKey), JhsInteger).Value
End Function
Public Function GetInt(memberKey As String) As Integer
Return CInt(DirectCast(Members(memberKey), JhsInteger).Value)
End Function
Public Function GetInt(memberKey As String, [default] As Integer) As Integer
If Not Members.ContainsKey(memberKey) Then Return [default]
Return CInt(DirectCast(Members(memberKey), JhsInteger).Value)
End Function
Public Function GetDouble(memberKey As String) As Double
Return DirectCast(Members(memberKey), JhsFloat).Value
End Function
Public Function GetDouble(memberKey As String, [default] As Double) As Double
If Not Members.ContainsKey(memberKey) Then Return [default]
Return DirectCast(Members(memberKey), JhsFloat).Value
End Function
Public Function GetString(memberKey As String) As String
Return DirectCast(Members(memberKey), JhsString).Value
End Function
Public Function GetString(memberKey As String, [default] As String) As String
If Not Members.ContainsKey(memberKey) Then Return [default]
Return DirectCast(Members(memberKey), JhsString).Value
End Function
Public Function GetDateTime(memberKey As String) As DateTime
Dim v = Members(memberKey)
If TypeOf v Is JhsDateTime Then Return DirectCast(v, JhsDateTime).Value
Dim s = DirectCast(v, JhsString).Value
If s.Length <> 19 Then Throw New ArgumentException("Invalid date time value - length not 19")
If s(4) <> "-"c OrElse _
s(7) <> "-"c OrElse _
s(10) <> "T"c OrElse _
s(13) <> ":"c OrElse _
s(16) <> ":"c Then Throw New ArgumentException("Invalid date time value")
Return New DateTime(Integer.Parse(s.Substring(0, 4)),
Integer.Parse(s.Substring(5, 2)),
Integer.Parse(s.Substring(8, 2)),
Integer.Parse(s.Substring(11, 2)),
Integer.Parse(s.Substring(14, 2)),
Integer.Parse(s.Substring(17, 2)))
End Function
Public Function GetDateTime(memberKey As String, [default] As DateTime) As DateTime
If Not Members.ContainsKey(memberKey) Then Return [default]
Return GetDateTime(memberKey)
End Function
Friend Function GetBinary(memberKey As String) As Byte()
Dim v = Members(memberKey)
If TypeOf v Is JhsBinary Then Return DirectCast(v, JhsBinary).Value
Return System.Convert.FromBase64String(DirectCast(v, JhsString).Value)
End Function
Friend Function GetBinary(memberKey As String, [default] As Byte()) As Byte()
If Not Members.ContainsKey(memberKey) Then Return [default]
Return GetBinary(memberKey)
End Function
Public Function GetArray(memberKey As String) As JhsArray
Return DirectCast(Members(memberKey), JhsArray)
End Function
Public Function GetObject(memberKey As String) As JhsObject
Return DirectCast(Members(memberKey), JhsObject)
End Function
Public Function GetEnumerator() As IEnumerator(Of KeyValuePair(Of String, JhsValue)) Implements IEnumerable(Of KeyValuePair(Of String, JhsValue)).GetEnumerator
Return Members.GetEnumerator
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Members.GetEnumerator
End Function
End Class
Public Class JhsArray
Inherits JhsValue
Implements IList(Of JhsValue)
Public ReadOnly Elements As New List(Of JhsValue)
Public ReadOnly Property Count As Integer Implements ICollection(Of JhsValue).Count
Get
Return Elements.Count
End Get
End Property
Public ReadOnly Property IsReadOnly As Boolean Implements ICollection(Of JhsValue).IsReadOnly
Get
Return False
End Get
End Property
Default Public Property Item(index As Integer) As JhsValue Implements IList(Of JhsValue).Item
Get
Return Elements(index)
End Get
Set(value As JhsValue)
Elements(index) = value
End Set
End Property
Public Sub Clear() Implements ICollection(Of JhsValue).Clear
Elements.Clear()
End Sub
Public Sub CopyTo(array() As JhsValue, arrayIndex As Integer) Implements ICollection(Of JhsValue).CopyTo
Elements.CopyTo(array, arrayIndex)
End Sub
Public Sub Insert(index As Integer, item As JhsValue) Implements IList(Of JhsValue).Insert
Elements.Insert(index, item)
End Sub
Public Sub RemoveAt(index As Integer) Implements IList(Of JhsValue).RemoveAt
Elements.RemoveAt(index)
End Sub
Public Sub Add(item As JhsValue) Implements ICollection(Of JhsValue).Add
Elements.Add(item)
End Sub
Public Function Contains(item As JhsValue) As Boolean Implements ICollection(Of JhsValue).Contains
Return Elements.Contains(item)
End Function
Public Function GetEnumerator() As IEnumerator(Of JhsValue) Implements IEnumerable(Of JhsValue).GetEnumerator
Return Elements.GetEnumerator
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return Elements.GetEnumerator
End Function
Public Function IndexOf(item As JhsValue) As Integer Implements IList(Of JhsValue).IndexOf
Return Elements.IndexOf(item)
End Function
Public Function Remove(item As JhsValue) As Boolean Implements ICollection(Of JhsValue).Remove
Return Elements.Remove(item)
End Function
End Class
Public Class JhsString
Inherits JhsValue
Public ReadOnly Value As String
Public Sub New(ByVal value As String)
Me.Value = value
End Sub
End Class
Public Class JhsDateTime
Inherits JhsValue
Public ReadOnly Value As DateTime
Sub New(value As DateTime)
Me.Value = value
End Sub
End Class
Friend Class JhsBinary
Inherits JhsValue
Friend ReadOnly Value As Byte()
Sub New(value As Byte())
Me.Value = value
End Sub
End Class
Public Class JhsInteger
Inherits JhsValue
Public ReadOnly Value As Int64
Public Sub New(ByVal value As Int64)
Me.Value = value
End Sub
End Class
Public Class JhsFloat
Inherits JhsValue
Public ReadOnly Value As Double
Public Sub New(ByVal value As Double)
Me.Value = value
End Sub
End Class
Public Class JhsBoolean
Inherits JhsValue
Public ReadOnly Value As Boolean
Sub New(ByVal value As Boolean)
Me.Value = value
End Sub
End Class
Public Class JhsNull
Inherits JhsValue
Private Sub New()
End Sub
Public Shared ReadOnly Value As New JhsNull
End Class
End Class
|
jesperhoy/GitHubBackup
|
GitHubBackup/JHSerializer.vb
|
Visual Basic
|
mit
| 8,586
|
Namespace Connect.Modules.Kickstart
Public Enum ActionMode
Participate
Fund
EditProject
Create
EditIdea
BecomeLead
End Enum
End Namespace
|
DNN-Connect/kickstart
|
Components/Shared/Enums.vb
|
Visual Basic
|
mit
| 200
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class FrmCambioCondicionesContrato
'''<summary>
'''Control RadCodeBlock1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadCodeBlock1 As Global.Telerik.Web.UI.RadCodeBlock
'''<summary>
'''Control form1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''Control RadScriptManager1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadScriptManager1 As Global.Telerik.Web.UI.RadScriptManager
'''<summary>
'''Control btnCancelar.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents btnCancelar As Global.System.Web.UI.WebControls.ImageButton
'''<summary>
'''Control btnAceptar.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents btnAceptar As Global.System.Web.UI.WebControls.ImageButton
'''<summary>
'''Control UpdatePanel3.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents UpdatePanel3 As Global.System.Web.UI.UpdatePanel
'''<summary>
'''Control txtCondicionCambio.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtCondicionCambio As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control txtIdCondicion.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtIdCondicion As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control cbxAdenda.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents cbxAdenda As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''Control txtNroAdemda.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtNroAdemda As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control cbxFecha.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents cbxFecha As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''Control rpFechaFinContrato.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents rpFechaFinContrato As Global.Telerik.Web.UI.RadDatePicker
'''<summary>
'''Control txtUltFechaCamCond.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtUltFechaCamCond As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control cbxSueldo.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents cbxSueldo As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''Control txtSueldo.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtSueldo As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control lblFechaCambio.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents lblFechaCambio As Global.System.Web.UI.WebControls.Label
'''<summary>
'''Control UpdatePanel4.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents UpdatePanel4 As Global.System.Web.UI.UpdatePanel
'''<summary>
'''Control RadComboBox1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents RadComboBox1 As Global.Telerik.Web.UI.RadComboBox
'''<summary>
'''Control ObjectDataSource1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ObjectDataSource1 As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control txtIdArea.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents txtIdArea As Global.System.Web.UI.WebControls.TextBox
'''<summary>
'''Control cbxPosicion.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents cbxPosicion As Global.System.Web.UI.WebControls.CheckBox
'''<summary>
'''Control UpdatePanel2.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents UpdatePanel2 As Global.System.Web.UI.UpdatePanel
'''<summary>
'''Control ddlPosicion.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ddlPosicion As Global.System.Web.UI.WebControls.DropDownList
'''<summary>
'''Control ObjectDataSource2.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents ObjectDataSource2 As Global.System.Web.UI.WebControls.ObjectDataSource
'''<summary>
'''Control rpFechaAplica.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents rpFechaAplica As Global.Telerik.Web.UI.RadDatePicker
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/RRHH/Formulario/FrmCambioCondicionesContrato.aspx.designer.vb
|
Visual Basic
|
mit
| 9,022
|
' 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.Tasks
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.ReferenceHighlighting
Public Class CSharpReferenceHighlightingTests
Inherits AbstractReferenceHighlightingTests
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestVerifyNoHighlightsWhenOptionDisabled() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $$Goo
{
Goo f;
}
</Document>
</Project>
</Workspace>,
optionIsEnabled:=False)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestVerifyHighlightsForClass() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Definition:$$Goo|}
{
}
</Document>
</Project>
</Workspace>)
End Function
<WpfFact>
<Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestVerifyHighlightsForScriptReference() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
<ParseOptions Kind="Script"/>
void M()
{
}
{|Reference:$$Script|}.M();
</Document>
</Project>
</Workspace>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestVerifyHighlightsForCSharpClassWithConstructor() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Definition:$$Goo|}
{
{|Definition:Goo|}()
{
{|Reference:var|} x = new {|Reference:Goo|}();
}
}
</Document>
</Project>
</Workspace>)
End Function
<WorkItem(538721, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538721")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestVerifyHighlightsForCSharpClassWithSynthesizedConstructor() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Definition:Goo|}
{
void Blah()
{
var x = new {|Reference:$$Goo|}();
}
}
</Document>
</Project>
</Workspace>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
<WorkItem(528436, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528436")>
Public Async Function TestVerifyHighlightsOnCloseAngleOfGeneric() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
class {|Definition:Program|}
{
static void Main(string[] args)
{
new List<{|Reference:Program$$|}>();
}
}]]>
</Document>
</Project>
</Workspace>)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
<WorkItem(570809, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570809")>
Public Async Function TestVerifyNoHighlightsOnAsyncLambda() As Task
Await VerifyHighlightsAsync(
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public delegate Task del();
del ft = $$async () =>
{
return await Task.Yield();
};
}]]>
</Document>
</Project>
</Workspace>)
End Function
<WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAlias1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace X
{
using {|Definition:Q|} = System.IO;
Class B
{
public void M()
{
$${|Reference:Q|}.Directory.Exists("");
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAlias2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace X
{
using $${|Definition:Q|} = System.IO;
Class B
{
public void M()
{
{|Reference:Q|}.Directory.Exists("");
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(543768, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543768")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAlias3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
namespace X
{
using Q = System.$${|Reference:IO|};
Class B
{
public void M()
{
{|Reference:Q|}.Directory.Exists("");
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(552000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552000")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAlias4() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = System.Action;
namespace N
{
using $${|Definition:C|} = A<C>; // select C
class A<T> { }
class B : {|Reference:C|} { }
}]]>
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightThroughVar1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void F()
{
$${|Reference:var|} i = 1;
{|Reference:int|} j = 0;
double d;
{|Reference:int|} k = 1;
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightThroughVar2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void F()
{
{|Reference:var|} i = 1;
$${|Reference:int|} j = 0;
double d;
{|Reference:int|} k = 1;
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(542830, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542830")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightThroughVar3() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
class C
{
void F()
{
$${|Reference:var|} i = new {|Reference:List|}<string>();
int j = 0;
double d;
{|Reference:var|} k = new {|Reference:List|}<int>();
}
}
]]></Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestUsingAliasAndTypeWithSameName1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using {|Definition:$$X|} = System;
class X { }
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(545648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545648")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestUsingAliasAndTypeWithSameName2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using X = System;
class {|Definition:$$X|} { }
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAccessor1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
string P
{
$$get
{
return P;
}
set
{
P = "";
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(567959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567959")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestAccessor2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
string P
{
get
{
return P;
}
$$set
{
P = "";
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(604466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/604466")>
<WpfFact(Skip:="604466"), Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestThisShouldNotHighlightTypeName() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
t$$his.M();
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(531620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531620")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightDynamicallyBoundMethod() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class A
{
class B
{
public void {|Definition:Boo|}(int d) { } //Line 1
public void Boo(dynamic d) { } //Line 2
public void Boo(string d) { } //Line 3
}
void Aoo()
{
B b = new B();
dynamic d = 1.5f;
b.{|Reference:Boo|}(1); //Line 4
b.$${|Reference:Boo|}(d); //Line 5
b.Boo("d"); //Line 6
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WorkItem(531624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531624")>
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightParameterizedPropertyParameter() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
int this[int $${|Definition:i|}]
{
get
{
return this[{|Reference:i|}];
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestInterpolatedString1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var $${|Definition:a|} = "Hello";
var b = "World";
var c = $"{ {|Reference:a|} }, {b}!";
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestInterpolatedString2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var a = "Hello";
var $${|Definition:b|} = "World";
var c = $"{a}, { {|Reference:b|} }!";
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestWrittenReference() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
var $${|Definition:b|} = "Hello";
{|WrittenReference:b|} = "World";
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestWrittenReference2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
int {|Definition:$$y|};
int x = {|WrittenReference:y|} = 7;
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestPatternMatchingType1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
object o = null;
if (o is C $${|Definition:c|})
{
var d = {|Reference:c|};
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestPatternMatchingType2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void M()
{
object o = null;
if (o is C {|Definition:c|})
{
var d = $${|Reference:c|};
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestPatternMatchingTypeScoping1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Class1 { }
class Class2 { }
class C
{
void M()
{
object o = null;
if (o is Class1 {|Definition:c|})
{
var d = $${|Reference:c|};
}
else if (o is Class2 c)
{
var d = c;
}
el
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestPatternMatchingTypeScoping2() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Class1 { }
class Class2 { }
class C
{
void M()
{
object o = null;
if (o is Class1 c)
{
var d = c;
}
else if (o is Class2 {|Definition:c|})
{
var d = $${|Reference:c|};
}
el
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestRegexReference1() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Text.RegularExpressions;
class C
{
void Goo()
{
var r = new Regex(@"{|Reference:(a)|}\0{|Reference:\$$1|}");
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightParamAndCommentsCursorOnDefinition() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
/// < summary >
/// < paramref name="{|Reference:x|}"/ >
/// < /summary >
/// < param name="{|Reference:x|}" > < /param >
public int this[int $${|Definition:x|}]
{
get
{
return 0;
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightParamAndCommentsCursorOnReference() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
/// < summary >
/// < paramref name="$${|Reference:x|}"/ >
/// < /summary >
/// < param name="{|Reference:x|}" > < /param >
public int this[int {|Definition:x|}]
{
get
{
return 0;
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ReferenceHighlighting)>
Public Async Function TestHighlightParamAndCommentsDefinitionNestedBetweenReferences() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
/// < summary >
/// < paramref name="$${|Reference:x|}"/ >
/// < /summary >
/// < param name="{|Reference:x|}" > < /param >
public int this[int {|Definition:x|}]
{
get
{
return {|Reference:x|};
}
}
}
</Document>
</Project>
</Workspace>
Await VerifyHighlightsAsync(input)
End Function
End Class
End Namespace
|
diryboy/roslyn
|
src/EditorFeatures/Test2/ReferenceHighlighting/CSharpReferenceHighlightingTests.vb
|
Visual Basic
|
mit
| 22,653
|
Imports System
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Windows.Forms
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()>
Public Class Hashes
Inherits System.Windows.Forms.Form
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If components IsNot Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
Private components As System.ComponentModel.IContainer
Private Sub InitializeComponent()
Me.grpMD5 = New System.Windows.Forms.GroupBox()
Me.btnMD5Copy = New System.Windows.Forms.Button()
Me.lblMD5 = New System.Windows.Forms.TextBox()
Me.btnMD5 = New System.Windows.Forms.Button()
Me.grpSHA1 = New System.Windows.Forms.GroupBox()
Me.btnSHA1Copy = New System.Windows.Forms.Button()
Me.lblSHA1 = New System.Windows.Forms.TextBox()
Me.btnSHA1 = New System.Windows.Forms.Button()
Me.grpSHA256 = New System.Windows.Forms.GroupBox()
Me.btnSHA256Copy = New System.Windows.Forms.Button()
Me.lblSHA256 = New System.Windows.Forms.TextBox()
Me.btnSHA256 = New System.Windows.Forms.Button()
Me.btnAllCopy = New System.Windows.Forms.Button()
Me.btnAllCalculate = New System.Windows.Forms.Button()
Me.btnClose = New System.Windows.Forms.Button()
Me.pbCalculateProgress = New wyDay.Controls.Windows7ProgressBar()
Me.bwCalcHashes = New System.ComponentModel.BackgroundWorker()
Me.grpSHA512 = New System.Windows.Forms.GroupBox()
Me.btnSHA512Copy = New System.Windows.Forms.Button()
Me.lblSHA512 = New System.Windows.Forms.TextBox()
Me.btnSHA512 = New System.Windows.Forms.Button()
Me.btnAllCancel = New System.Windows.Forms.Button()
Me.grpMD5.SuspendLayout()
Me.grpSHA1.SuspendLayout()
Me.grpSHA256.SuspendLayout()
Me.grpSHA512.SuspendLayout()
Me.SuspendLayout()
'grpMD5
Me.grpMD5.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.grpMD5.Controls.Add(Me.btnMD5Copy)
Me.grpMD5.Controls.Add(Me.lblMD5)
Me.grpMD5.Controls.Add(Me.btnMD5)
Me.grpMD5.Location = New System.Drawing.Point(3, 4)
Me.grpMD5.Name = "grpMD5"
Me.grpMD5.Size = New System.Drawing.Size(510, 50)
Me.grpMD5.TabIndex = 0
Me.grpMD5.TabStop = False
Me.grpMD5.Text = "MD5"
'btnMD5Copy
Me.btnMD5Copy.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnMD5Copy.Location = New System.Drawing.Point(460, 19)
Me.btnMD5Copy.Name = "btnMD5Copy"
Me.btnMD5Copy.Size = New System.Drawing.Size(44, 23)
Me.btnMD5Copy.TabIndex = 2
Me.btnMD5Copy.Text = "Copy"
Me.btnMD5Copy.UseVisualStyleBackColor = True
'lblMD5
Me.lblMD5.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.lblMD5.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.lblMD5.Location = New System.Drawing.Point(87, 24)
Me.lblMD5.Name = "lblMD5"
Me.lblMD5.ReadOnly = True
Me.lblMD5.Size = New System.Drawing.Size(367, 13)
Me.lblMD5.TabIndex = 1
Me.lblMD5.Text = "Click ""Calculate"""
'btnMD5
Me.btnMD5.Location = New System.Drawing.Point(6, 19)
Me.btnMD5.Name = "btnMD5"
Me.btnMD5.Size = New System.Drawing.Size(75, 23)
Me.btnMD5.TabIndex = 0
Me.btnMD5.Text = "Calculate..."
Me.btnMD5.UseVisualStyleBackColor = True
'grpSHA1
Me.grpSHA1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.grpSHA1.Controls.Add(Me.btnSHA1Copy)
Me.grpSHA1.Controls.Add(Me.lblSHA1)
Me.grpSHA1.Controls.Add(Me.btnSHA1)
Me.grpSHA1.Location = New System.Drawing.Point(3, 60)
Me.grpSHA1.Name = "grpSHA1"
Me.grpSHA1.Size = New System.Drawing.Size(510, 50)
Me.grpSHA1.TabIndex = 1
Me.grpSHA1.TabStop = False
Me.grpSHA1.Text = "SHA-1"
'btnSHA1Copy
Me.btnSHA1Copy.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnSHA1Copy.Location = New System.Drawing.Point(460, 19)
Me.btnSHA1Copy.Name = "btnSHA1Copy"
Me.btnSHA1Copy.Size = New System.Drawing.Size(44, 23)
Me.btnSHA1Copy.TabIndex = 2
Me.btnSHA1Copy.Text = "Copy"
Me.btnSHA1Copy.UseVisualStyleBackColor = True
'lblSHA1
Me.lblSHA1.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.lblSHA1.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.lblSHA1.Location = New System.Drawing.Point(87, 24)
Me.lblSHA1.Name = "lblSHA1"
Me.lblSHA1.ReadOnly = True
Me.lblSHA1.Size = New System.Drawing.Size(367, 13)
Me.lblSHA1.TabIndex = 1
Me.lblSHA1.Text = "Click ""Calculate"""
'btnSHA1
Me.btnSHA1.Location = New System.Drawing.Point(6, 19)
Me.btnSHA1.Name = "btnSHA1"
Me.btnSHA1.Size = New System.Drawing.Size(75, 23)
Me.btnSHA1.TabIndex = 0
Me.btnSHA1.Text = "Calculate..."
Me.btnSHA1.UseVisualStyleBackColor = True
'grpSHA256
Me.grpSHA256.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.grpSHA256.Controls.Add(Me.btnSHA256Copy)
Me.grpSHA256.Controls.Add(Me.lblSHA256)
Me.grpSHA256.Controls.Add(Me.btnSHA256)
Me.grpSHA256.Location = New System.Drawing.Point(3, 116)
Me.grpSHA256.Name = "grpSHA256"
Me.grpSHA256.Size = New System.Drawing.Size(510, 50)
Me.grpSHA256.TabIndex = 2
Me.grpSHA256.TabStop = False
Me.grpSHA256.Text = "SHA-256"
'btnSHA256Copy
Me.btnSHA256Copy.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnSHA256Copy.Location = New System.Drawing.Point(460, 19)
Me.btnSHA256Copy.Name = "btnSHA256Copy"
Me.btnSHA256Copy.Size = New System.Drawing.Size(44, 23)
Me.btnSHA256Copy.TabIndex = 2
Me.btnSHA256Copy.Text = "Copy"
Me.btnSHA256Copy.UseVisualStyleBackColor = True
'lblSHA256
Me.lblSHA256.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.lblSHA256.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.lblSHA256.Location = New System.Drawing.Point(87, 24)
Me.lblSHA256.Name = "lblSHA256"
Me.lblSHA256.ReadOnly = True
Me.lblSHA256.Size = New System.Drawing.Size(367, 13)
Me.lblSHA256.TabIndex = 1
Me.lblSHA256.Text = "Click ""Calculate"""
'btnSHA256
Me.btnSHA256.Location = New System.Drawing.Point(6, 19)
Me.btnSHA256.Name = "btnSHA256"
Me.btnSHA256.Size = New System.Drawing.Size(75, 23)
Me.btnSHA256.TabIndex = 0
Me.btnSHA256.Text = "Calculate..."
Me.btnSHA256.UseVisualStyleBackColor = True
'btnAllCopy
Me.btnAllCopy.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnAllCopy.Location = New System.Drawing.Point(265, 257)
Me.btnAllCopy.Name = "btnAllCopy"
Me.btnAllCopy.Size = New System.Drawing.Size(116, 23)
Me.btnAllCopy.TabIndex = 7
Me.btnAllCopy.Text = "Copy All"
Me.btnAllCopy.UseVisualStyleBackColor = True
'btnAllCalculate
Me.btnAllCalculate.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.btnAllCalculate.Location = New System.Drawing.Point(12, 257)
Me.btnAllCalculate.Name = "btnAllCalculate"
Me.btnAllCalculate.Size = New System.Drawing.Size(116, 23)
Me.btnAllCalculate.TabIndex = 5
Me.btnAllCalculate.Text = "Calculate All..."
Me.btnAllCalculate.UseVisualStyleBackColor = True
'btnClose
Me.btnClose.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK
Me.btnClose.Location = New System.Drawing.Point(387, 257)
Me.btnClose.Name = "btnClose"
Me.btnClose.Size = New System.Drawing.Size(116, 23)
Me.btnClose.TabIndex = 8
Me.btnClose.Text = "Close"
Me.btnClose.UseVisualStyleBackColor = True
'pbCalculateProgress
Me.pbCalculateProgress.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.pbCalculateProgress.ContainerControl = Me
Me.pbCalculateProgress.Location = New System.Drawing.Point(9, 228)
Me.pbCalculateProgress.Name = "pbCalculateProgress"
Me.pbCalculateProgress.ShowInTaskbar = True
Me.pbCalculateProgress.Size = New System.Drawing.Size(498, 23)
Me.pbCalculateProgress.TabIndex = 4
'bwCalcHashes
Me.bwCalcHashes.WorkerReportsProgress = True
Me.bwCalcHashes.WorkerSupportsCancellation = True
'grpSHA512
Me.grpSHA512.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.grpSHA512.Controls.Add(Me.btnSHA512Copy)
Me.grpSHA512.Controls.Add(Me.lblSHA512)
Me.grpSHA512.Controls.Add(Me.btnSHA512)
Me.grpSHA512.Location = New System.Drawing.Point(3, 172)
Me.grpSHA512.Name = "grpSHA512"
Me.grpSHA512.Size = New System.Drawing.Size(510, 50)
Me.grpSHA512.TabIndex = 3
Me.grpSHA512.TabStop = False
Me.grpSHA512.Text = "SHA-512"
'btnSHA512Copy
Me.btnSHA512Copy.Anchor = CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.btnSHA512Copy.Location = New System.Drawing.Point(460, 19)
Me.btnSHA512Copy.Name = "btnSHA512Copy"
Me.btnSHA512Copy.Size = New System.Drawing.Size(44, 23)
Me.btnSHA512Copy.TabIndex = 2
Me.btnSHA512Copy.Text = "Copy"
Me.btnSHA512Copy.UseVisualStyleBackColor = True
'lblSHA512
Me.lblSHA512.Anchor = CType(((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Left) Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
Me.lblSHA512.BorderStyle = System.Windows.Forms.BorderStyle.None
Me.lblSHA512.Location = New System.Drawing.Point(87, 24)
Me.lblSHA512.Name = "lblSHA512"
Me.lblSHA512.ReadOnly = True
Me.lblSHA512.Size = New System.Drawing.Size(367, 13)
Me.lblSHA512.TabIndex = 1
Me.lblSHA512.Text = "Click ""Calculate"""
'btnSHA512
Me.btnSHA512.Location = New System.Drawing.Point(6, 19)
Me.btnSHA512.Name = "btnSHA512"
Me.btnSHA512.Size = New System.Drawing.Size(75, 23)
Me.btnSHA512.TabIndex = 0
Me.btnSHA512.Text = "Calculate..."
Me.btnSHA512.UseVisualStyleBackColor = True
'btnAllCancel
Me.btnAllCancel.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Left), System.Windows.Forms.AnchorStyles)
Me.btnAllCancel.Enabled = False
Me.btnAllCancel.Location = New System.Drawing.Point(134, 257)
Me.btnAllCancel.Name = "btnAllCancel"
Me.btnAllCancel.Size = New System.Drawing.Size(125, 23)
Me.btnAllCancel.TabIndex = 6
Me.btnAllCancel.Text = "Cancel All"
Me.btnAllCancel.UseVisualStyleBackColor = True
'Hashes
Me.AcceptButton = Me.btnAllCalculate
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.CancelButton = Me.btnClose
Me.ClientSize = New System.Drawing.Size(515, 293)
Me.Controls.Add(Me.btnAllCancel)
Me.Controls.Add(Me.grpSHA512)
Me.Controls.Add(Me.pbCalculateProgress)
Me.Controls.Add(Me.btnClose)
Me.Controls.Add(Me.btnAllCopy)
Me.Controls.Add(Me.grpSHA256)
Me.Controls.Add(Me.btnAllCalculate)
Me.Controls.Add(Me.grpSHA1)
Me.Controls.Add(Me.grpMD5)
Me.Icon = My.Resources.hashx64
Me.Name = "Hashes"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent
'Me.Location = New System.Drawing.Size((My.Computer.Screen.WorkingArea.Width/2) - 257.5, (My.Computer.Screen.WorkingArea.Height/2) - 146.5)
Me.Text = "Generate Hashes: <filename>"
Me.grpMD5.ResumeLayout(False)
Me.grpMD5.PerformLayout()
Me.grpSHA1.ResumeLayout(False)
Me.grpSHA1.PerformLayout()
Me.grpSHA256.ResumeLayout(False)
Me.grpSHA256.PerformLayout()
Me.grpSHA512.ResumeLayout(False)
Me.grpSHA512.PerformLayout()
Me.ResumeLayout(False)
End Sub
Private WithEvents btnAllCancel As System.Windows.Forms.Button
Private WithEvents btnSHA512 As System.Windows.Forms.Button
Private lblSHA512 As System.Windows.Forms.TextBox
Private WithEvents btnSHA512Copy As System.Windows.Forms.Button
Private grpSHA512 As System.Windows.Forms.GroupBox
Private WithEvents bwCalcHashes As System.ComponentModel.BackgroundWorker
Private pbCalculateProgress As wyDay.Controls.Windows7ProgressBar
Private WithEvents btnClose As System.Windows.Forms.Button
Private WithEvents btnAllCalculate As System.Windows.Forms.Button
Private WithEvents btnAllCopy As System.Windows.Forms.Button
Private WithEvents btnSHA256 As System.Windows.Forms.Button
Private lblSHA256 As System.Windows.Forms.TextBox
Private WithEvents btnSHA256Copy As System.Windows.Forms.Button
Private grpSHA256 As System.Windows.Forms.GroupBox
Private WithEvents btnSHA1 As System.Windows.Forms.Button
Private lblSHA1 As System.Windows.Forms.TextBox
Private WithEvents btnSHA1Copy As System.Windows.Forms.Button
Private grpSHA1 As System.Windows.Forms.GroupBox
Private WithEvents btnMD5 As System.Windows.Forms.Button
Private lblMD5 As System.Windows.Forms.TextBox
Private WithEvents btnMD5Copy As System.Windows.Forms.Button
Private grpMD5 As System.Windows.Forms.GroupBox
''' End Designer code
Dim hashQueue As String
''' <summary>Removes a hash type string from the queue. WARNING: cannot remove the first hash in queue - but that is currently being hashed anyway.</summary>
''' <param name="type">The hash type to remove</param>
Sub ClearHashFromQueue(type As String) ' given queue of `MD5 SHA1` and argument of `SHA1` will result in `MD5` - this is _
If hashQueue.Contains(type) Then ' to remove the space \/
hashQueue = hashQueue.Remove(hashQueue.IndexOf(type) - 1) & hashQueue.Substring(hashQueue.IndexOf(type) + type.Length)
End If
End Sub
Sub SetAllToQueue()
btnMD5.Text = "Queue"
btnSHA1.Text = "Queue"
btnSHA256.Text = "Queue"
btnSHA512.Text = "Queue"
End Sub
Sub Hashes_VisibleChanged() Handles Me.VisibleChanged
If Me.Visible Then
Me.CenterToParent()
End If
End Sub
' Starting & stopping
Sub btnMD5_Click() Handles btnMD5.Click
Select Case btnMD5.Text
Case "Calculate..."
hashQueue = "MD5"
SetAllToQueue()
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
Case "Cancel"
bwCalcHashes.CancelAsync()
Case "Queue"
hashQueue &= " MD5"
btnMD5.Text = "Unqueue"
Case "Unqueue"
ClearHashFromQueue("MD5")
btnMD5.Text = "Queue"
End Select
End Sub
Sub btnSHA1_Click() Handles btnSHA1.Click
Select Case btnSHA1.Text
Case "Calculate..."
hashQueue = "SHA1"
SetAllToQueue()
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
Case "Cancel"
bwCalcHashes.CancelAsync()
Case "Queue"
hashQueue &= " SHA1"
btnSHA1.Text = "Unqueue"
Case "Unqueue"
ClearHashFromQueue("SHA1")
btnSHA1.Text = "Queue"
End Select
End Sub
Sub btnSHA256_Click() Handles btnSHA256.Click
Select Case btnSHA256.Text
Case "Calculate..."
hashQueue = "SHA256"
SetAllToQueue()
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
Case "Cancel"
bwCalcHashes.CancelAsync()
Case "Queue"
hashQueue &= " SHA256"
btnSHA256.Text = "Unqueue"
Case "Unqueue"
ClearHashFromQueue("SHA256")
btnSHA256.Text = "Queue"
End Select
End Sub
Sub btnSHA512_Click() Handles btnSHA512.Click
Select Case btnSHA512.Text
Case "Calculate..."
hashQueue = "SHA512"
SetAllToQueue()
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
Case "Cancel"
bwCalcHashes.CancelAsync()
Case "Queue"
hashQueue &= " SHA512"
btnSHA512.Text = "Unqueue"
Case "Unqueue"
ClearHashFromQueue("SHA512")
btnSHA512.Text = "Queue"
End Select
End Sub
Sub btnAllCalculate_Click() Handles btnAllCalculate.Click
hashQueue = "MD5 SHA1 SHA256 SHA512"
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
btnSHA1.Text = "Unqueue"
btnSHA256.Text = "Unqueue"
btnSHA512.Text = "Unqueue"
End Sub
Sub btnAllCancel_Click() Handles btnAllCancel.Click
If hashQueue.StartsWith("MD5") Then
hashQueue = "MD5"
ElseIf hashQueue.StartsWith("SHA1") Then
hashQueue = "SHA1"
ElseIf hashQueue.StartsWith("SHA256") Then
hashQueue = "SHA256"
ElseIf hashQueue.StartsWith("SHA512") Then
hashQueue = "SHA512"
Else
Exit Sub
End If
bwCalcHashes.CancelAsync()
Do Until bwCalcHashes.CancellationPending
bwCalcHashes.CancelAsync()
Loop
btnAllCancel.Enabled = False
End Sub
Sub btnClose_Click() Handles btnClose.Click
Me.Hide()
End Sub
' Copying output
Sub btnMD5Copy_Click() Handles btnMD5Copy.Click
WalkmanLib.SafeSetText(lblMD5.Text, "default")
End Sub
Sub btnSHA1Copy_Click() Handles btnSHA1Copy.Click
WalkmanLib.SafeSetText(lblSHA1.Text, "default")
End Sub
Sub btnSHA256Copy_Click() Handles btnSHA256Copy.Click
WalkmanLib.SafeSetText(lblSHA256.Text, "default")
End Sub
Sub btnSHA512Copy_Click() Handles btnSHA512Copy.Click
WalkmanLib.SafeSetText(lblSHA512.Text, "default")
End Sub
Sub btnAllCopy_Click() Handles btnAllCopy.Click
Dim ToCopy As String
ToCopy = "MD5: " & CheckGenerated(lblMD5.Text) & Environment.NewLine
ToCopy &= "SHA1: " & CheckGenerated(lblSHA1.Text) & Environment.NewLine
ToCopy &= "SHA256: " & CheckGenerated(lblSHA256.Text) & Environment.NewLine
ToCopy &= "SHA512: " & CheckGenerated(lblSHA512.Text)
WalkmanLib.SafeSetText(ToCopy)
End Sub
Function CheckGenerated(status As String) As String
If status = "Click ""Calculate""" Then
Return "Not generated"
ElseIf status = "Operation was cancelled" Then
Return "Not generated"
Else
Return status
End If
End Function
' Original code, thanks to http://us.informatiweb.net/programmation/36--generate-hashes-md5-sha-1-and-sha-256-of-a-file.html
' Code that reports progress, thanks to http://www.infinitec.de/post/2007/06/09/Displaying-progress-updates-when-hashing-large-files.aspx
Dim hashHex As String
Dim hashObject As HashAlgorithm
Dim buffer As Byte()
Dim bytesRead As Integer
Dim totalBytesRead As Long = 0
Sub bwCalcHashes_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwCalcHashes.DoWork
Dim FilePropertiesStream As FileStream = Nothing
Try
' Set up GUI
btnAllCalculate.Enabled = False
btnAllCancel.Enabled = True
bwCalcHashes.ReportProgress(0)
HashGeneratorOutput("Creating hash object...")
If hashQueue.StartsWith("MD5") Then
hashObject = MD5.Create
btnMD5.Text = "Cancel"
ElseIf hashQueue.StartsWith("SHA1") Then
hashObject = SHA1.Create
btnSHA1.Text = "Cancel"
ElseIf hashQueue.StartsWith("SHA256") Then
hashObject = SHA256.Create
btnSHA256.Text = "Cancel"
ElseIf hashQueue.StartsWith("SHA384") Then
hashObject = SHA384.Create
ElseIf hashQueue.StartsWith("SHA512") Then
hashObject = SHA512.Create
btnSHA512.Text = "Cancel"
End If
HashGeneratorOutput("Opening file...")
FilePropertiesStream = File.OpenRead(e.Argument.ToString)
HashGeneratorOutput("Setting file position...")
FilePropertiesStream.Position = 0
HashGeneratorOutput("Setting up variables...")
buffer = New Byte(4095) {}
bytesRead = FilePropertiesStream.Read(buffer, 0, buffer.Length)
totalBytesRead = bytesRead
HashGeneratorOutput("Generating hash byte array...")
Dim lastProgressPercent As Integer = 0
Dim currentProgressPercent As Integer
Do While bytesRead <> 0
hashObject.TransformBlock(buffer, 0, bytesRead, buffer, 0)
buffer = New Byte(4095) {}
bytesRead = FilePropertiesStream.Read(buffer, 0, buffer.Length)
totalBytesRead += bytesRead
If bwCalcHashes.CancellationPending Then Throw New OperationCanceledException("Operation was cancelled")
currentProgressPercent = CInt(Math.Truncate(CDbl(totalBytesRead) * 100 / FilePropertiesStream.Length))
If currentProgressPercent > lastProgressPercent Then
bwCalcHashes.ReportProgress(currentProgressPercent)
lastProgressPercent = currentProgressPercent
End If
Loop
hashObject.TransformFinalBlock(buffer, 0, bytesRead)
HashGeneratorOutput("Converting hash byte array to hexadecimal...")
buffer = hashObject.Hash
hashHex = ""
For i = 0 To buffer.Length - 1
hashHex += buffer(i).ToString("X2")
Next i
HashGeneratorOutput("Closing streams...")
FilePropertiesStream.Close()
hashObject.Clear()
HashGeneratorOutput(hashHex.ToLower)
bwCalcHashes.ReportProgress(100)
Catch ex As OperationCanceledException
HashGeneratorOutput("Closing streams...")
If Not FilePropertiesStream Is Nothing Then
FilePropertiesStream.Close()
End If
hashObject.Clear()
HashGeneratorOutput(ex.Message)
bwCalcHashes.ReportProgress(0)
Catch ex As Exception
Operations.MessageBox(ex.ToString, icon:=MessageBoxIcon.Exclamation)
HashGeneratorOutput("Click ""Calculate""")
bwCalcHashes.ReportProgress(0)
End Try
End Sub
Sub bwCalcHashes_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bwCalcHashes.ProgressChanged
pbCalculateProgress.Value = e.ProgressPercentage
End Sub
Sub bwCalcHashes_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwCalcHashes.RunWorkerCompleted
If hashQueue.Contains(" ") Then
If hashQueue.StartsWith("MD5") Then
btnMD5.Text = "Queue"
ElseIf hashQueue.StartsWith("SHA1") Then
btnSHA1.Text = "Queue"
ElseIf hashQueue.StartsWith("SHA256") Then
btnSHA256.Text = "Queue"
ElseIf hashQueue.StartsWith("SHA512") Then
btnSHA512.Text = "Queue"
End If
hashQueue = hashQueue.Substring(hashQueue.IndexOf(" ") + 1)
bwCalcHashes.RunWorkerAsync(PropertiesDotNet.lblLocation.Text)
Else
btnAllCalculate.Enabled = True
btnAllCancel.Enabled = False
btnMD5.Text = "Calculate..."
btnSHA1.Text = "Calculate..."
btnSHA256.Text = "Calculate..."
btnSHA512.Text = "Calculate..."
End If
End Sub
''' <summary>Set the correct labels text to the status, depending on the hashQueue</summary>
''' <param name="status">The text to set the label to.</param>
Sub HashGeneratorOutput(status As String)
If hashQueue.StartsWith("MD5") Then
lblMD5.Text = status
ElseIf hashQueue.StartsWith("SHA1") Then
lblSHA1.Text = status
ElseIf hashQueue.StartsWith("SHA256") Then
lblSHA256.Text = status
ElseIf hashQueue.StartsWith("SHA512") Then
lblSHA512.Text = status
End If
End Sub
End Class
|
Walkman100/PropertiesDotNet
|
Hashes.vb
|
Visual Basic
|
mit
| 26,827
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("CustomAction1")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("CustomAction1")>
<Assembly: AssemblyCopyright("Copyright © 2014")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("9a5ac578-68b1-41c7-8cc8-b2ae8c71e0ac")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
Eonic/EonicWeb5
|
Assemblies/ProteanCMS.Installer.Actions/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,144
|
'21:22:30
'30.09.2013
'Autor: LargoWinch
Public Class L_L2Server
Public code As String
Public DefaultAddress() As Byte
Public thread As ServerThread
Public info As String
Public id As Byte
Public Function GetIP(ByVal client As L_LoginClient) As Byte()
If DefaultAddress Is Nothing Then
Dim ip As String = "0.0.0.0"
If thread IsNot Nothing Then
ip = thread.wan
End If
DefaultAddress = New Byte(3) {}
Dim w() As String = ip.Split("."c)
DefaultAddress(0) = Byte.Parse(w(0))
DefaultAddress(1) = Byte.Parse(w(1))
DefaultAddress(2) = Byte.Parse(w(2))
DefaultAddress(3) = Byte.Parse(w(3))
End If
' If thread IsNot Nothing Then
' End If
Return DefaultAddress
End Function
Public ReadOnly Property connected() As Byte
Get
Return If(thread IsNot Nothing, (If(thread.connected, CByte(1), CByte(0))), CByte(0))
End Get
End Property
Public ReadOnly Property CurPlayers() As Short
Get
Return If(thread IsNot Nothing, thread.curp, CShort(Fix(0)))
End Get
End Property
Public ReadOnly Property MaxPlayers() As Short
Get
Return If(thread IsNot Nothing, thread.maxp, CShort(Fix(0)))
End Get
End Property
Public ReadOnly Property Port() As Integer
Get
Return If(thread IsNot Nothing, thread.port, 0)
End Get
End Property
Public ReadOnly Property testMode() As Boolean
Get
Return If(thread IsNot Nothing, thread.testMode, False)
End Get
End Property
Public ReadOnly Property gmonly() As Boolean
Get
Return If(thread IsNot Nothing, thread.gmonly, False)
End Get
End Property
End Class
|
LargoWinch/LegacyEmu
|
LoginServer/Login_Server/LoginServer/model/L_L2Server.vb
|
Visual Basic
|
apache-2.0
| 1,887
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
' アセンブリに関連付けられている情報を変更するには、
' これらの属性値を変更してください。
' アセンブリ属性の値を確認します。
<Assembly: AssemblyTitle("RPN Complex Software Calculator")>
<Assembly: AssemblyDescription("RPN電卓")>
<Assembly: AssemblyCompany("MihailJP")>
<Assembly: AssemblyProduct("rpncalc")>
<Assembly: AssemblyCopyright("Copyright © MihailJP 2011-2012")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'このプロジェクトが COM に公開される場合、次の GUID がタイプ ライブラリの ID になります。
<Assembly: Guid("21edc53b-aad4-44fa-9395-46adfb91f96b")>
' アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
' 既定値にすることができます:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("0.5.0.0")>
<Assembly: AssemblyFileVersion("0.5.0.0")>
|
MihailJP/RPN-Complex-Software-Calculator
|
rpncalc/My Project/AssemblyInfo.vb
|
Visual Basic
|
bsd-2-clause
| 1,379
|
' 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.Xml.Linq
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Emit
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class PropertyTests
Inherits BasicTestBase
#Region "Basic Test cases"
' Allow assigning to property name in Get accessor.
<Fact>
Public Sub AssignToPropertyNameInGet()
Dim source =
<compilation>
<file name="c.vb">
Class C
ReadOnly Property P
Get
P = Nothing
End Get
End Property
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
' Properties with setter implemented by getter: not supported.
<Fact>
Public Sub GetUsedAsSet()
Dim customIL = <![CDATA[
.class public A
{
.method public static bool get_s() { ldnull throw }
.method public instance int32 get_i() { ldnull throw }
.property bool P()
{
.get bool A::get_s()
.set bool A::get_s()
}
.property int32 Q()
{
.get instance int32 A::get_i()
.set instance int32 A::get_i()
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class B
Shared Sub M(x As A)
N(A.P)
N(x.Q)
End Sub
Shared Sub N(o)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30643: Property 'A.P' is of an unsupported type.
N(A.P)
~
BC30643: Property 'A.Q' is of an unsupported type.
N(x.Q)
~
</expected>)
End Sub
' Property and accessor signatures have mismatched parameter counts: not
' supported. (Note: Native compiler allows these properties but provides
' errors when trying to use cases where either the accessor or
' property signature has zero parameters and the other has non-zero.)
<Fact>
Public Sub PropertyParameterCountMismatch()
Dim customIL = <![CDATA[
.class public A
{
.method public instance bool get_0() { ldnull throw }
.method public instance void set_0(bool val) { ret }
.method public instance bool get_1(int32 index) { ldnull throw }
.method public instance void set_1(int32 index, bool val) { ret }
.method public instance bool get_2(int32 x, int32 y) { ldnull throw }
.method public instance void set_2(int32 x, int32 y, bool val) { ret }
.property bool P()
{
.get instance bool A::get_1(int32 index)
.set instance void A::set_1(int32 index, bool val)
}
.property bool Q(int32 index)
{
.get instance bool A::get_2(int32 x, int32 y)
.set instance void A::set_2(int32 x, int32 y, bool val)
}
.property bool R(int32 x, int32 y)
{
.get instance bool A::get_0()
.set instance void A::set_0(bool val)
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Shared Sub M(x As A)
Dim y As Boolean
y = x.P
y = x.Q(0)
y = x.R(0, 1)
x.P = y
x.Q(0) = y
x.R(0, 1) = y
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30643: Property 'A.P' is of an unsupported type.
y = x.P
~
BC30643: Property 'A.Q(x As Integer)' is of an unsupported type.
y = x.Q(0)
~
BC30643: Property 'A.R(val As Integer, Param As Integer)' is of an unsupported type.
y = x.R(0, 1)
~
BC30643: Property 'A.P' is of an unsupported type.
x.P = y
~
BC30643: Property 'A.Q(x As Integer)' is of an unsupported type.
x.Q(0) = y
~
BC30643: Property 'A.R(val As Integer, Param As Integer)' is of an unsupported type.
x.R(0, 1) = y
~
</expected>)
End Sub
' Properties with one static and one instance accessor.
' Dev11 uses the accessor to determine whether access
' is through instance or type name. Roslyn does not
' support such properties. Breaking change.
<WorkItem(528159, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528159")>
<Fact()>
Public Sub MismatchedStaticInstanceAccessors()
Dim customIL = <![CDATA[
.class public A
{
.method public static int32 get_s() { ldc.i4.0 ret }
.method public static void set_s(int32 val) { ret }
.method public instance int32 get_i() { ldc.i4.0 ret }
.method public instance void set_i(int32 val) { ret }
.property int32 P()
{
.get int32 A::get_s()
.set instance void A::set_i(int32 val)
}
.property int32 Q()
{
.get instance int32 A::get_i()
.set void A::set_s(int32 val)
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Shared Sub M(x As A)
x.P = x.Q
A.Q = A.P
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
compilation.AssertTheseDiagnostics(
<expected>
BC30643: Property 'A.P' is of an unsupported type.
x.P = x.Q
~
BC30643: Property 'A.Q' is of an unsupported type.
x.P = x.Q
~
BC30643: Property 'A.Q' is of an unsupported type.
A.Q = A.P
~
BC30643: Property 'A.P' is of an unsupported type.
A.Q = A.P
~
</expected>)
End Sub
' Property with type that does not match accessors.
' Expression type should be determined from accessor.
<WorkItem(528160, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528160")>
<Fact()>
Public Sub WrongPropertyType()
Dim customIL = <![CDATA[
.class public A
{
.method public instance int32 get() { ldc.i4.0 ret }
.method public instance void set(int32 val) { ret }
.property string P()
{
.get instance int32 A::get()
.set instance void A::set(int32 val)
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Shared Sub M(x As A)
Dim y As Integer = x.P
x.P = y
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
CompilationUtils.AssertNoErrors(compilation)
End Sub
' Property with void type. (IDE with native compiler crashes.)
<Fact>
Public Sub VoidPropertyType()
Dim customIL = <![CDATA[
.class public A
{
.method public instance int32 get() { ldc.i4.0 ret }
.method public instance void set(int32 val) { ret }
.property void P()
{
.get instance int32 A::get()
.set instance void A::set(int32 val)
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class C
Shared Sub M(x As A)
Dim y As Integer = x.P
x.P = y
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
compilation.AssertNoErrors()
End Sub
' Property and getter with void type. Dev10 treats this as a valid
' property. Would it be better to treat the property as invalid?
<Fact>
Public Sub VoidPropertyAndAccessorType()
Dim customIL = <![CDATA[
.class public A
{
.method public static void get_P() { ret }
.property void P() { .get void A::get_P() }
.method public instance void get_Q() { ret }
.property void Q() { .get instance void A::get_Q() }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Class B
Shared Sub M(x As A)
N(A.P)
N(x.Q)
End Sub
Shared Sub N(o)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30491: Expression does not produce a value.
N(A.P)
~~~
BC30491: Expression does not produce a value.
N(x.Q)
~~~
</expected>)
End Sub
' Properties where the property and accessor signatures differ by
' modopt only should be supported (as in the native compiler).
<Fact>
Public Sub SignaturesDifferByModOptsOnly()
Dim ilSource = <![CDATA[
.class public A { }
.class public B { }
.class public C
{
.method public instance int32 get_noopt()
{
ldc.i4.0
ret
}
.method public instance int32 modopt(A) get_returnopt()
{
ldc.i4.0
ret
}
.method public instance void set_noopt(int32 val)
{
ret
}
.method public instance void set_argopt(int32 modopt(A) val)
{
ret
}
.method public instance void modopt(A) set_returnopt(int32 val)
{
ret
}
// Modifier on property but not accessors.
.property int32 modopt(A) P1()
{
.get instance int32 C::get_noopt()
.set instance void C::set_noopt(int32)
}
// Modifier on accessors but not property.
.property int32 P2()
{
.get instance int32 modopt(A) C::get_returnopt()
.set instance void C::set_argopt(int32 modopt(A))
}
// Modifier on getter only.
.property int32 P3()
{
.get instance int32 modopt(A) C::get_returnopt()
.set instance void C::set_noopt(int32)
}
// Modifier on setter only.
.property int32 P4()
{
.get instance int32 C::get_noopt()
.set instance void C::set_argopt(int32 modopt(A))
}
// Modifier on setter return type.
.property int32 P5()
{
.get instance int32 C::get_noopt()
.set instance void modopt(A) C::set_returnopt(int32)
}
// Modifier on property and different modifier on accessors.
.property int32 modopt(B) P6()
{
.get instance int32 modopt(A) C::get_returnopt()
.set instance void C::set_argopt(int32 modopt(A))
}
}
]]>.Value
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Class D
Shared Sub M(c As C)
c.P1 = c.P1
c.P2 = c.P2
c.P3 = c.P3
c.P4 = c.P4
c.P5 = c.P5
c.P6 = c.P6
End Sub
End Class
]]>
</file>
</compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub PropertyGetAndSet()
Dim source =
<compilation>
<file name="c.vb">
Module M
Sub Main()
Dim x As C = New C()
x.P = 2
C.Q = "q"
System.Console.Write("{0}, {1}", x.P, C.Q)
End Sub
End Module
Class C
Private _p
Property P
Get
Return _p
End Get
Set(value)
_p = value
End Set
End Property
Private Shared _q
Shared Property Q
Get
Return _q
End Get
Set(value)
_q = value
End Set
End Property
End Class
</file>
</compilation>
Dim compilationVerifier = CompileAndVerify(source, expectedOutput:="2, q")
compilationVerifier.VerifyIL("M.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 3
.locals init (C V_0) //x
IL_0000: newobj "Sub C..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.2
IL_0008: box "Integer"
IL_000d: callvirt "Sub C.set_P(Object)"
IL_0012: ldstr "q"
IL_0017: call "Sub C.set_Q(Object)"
IL_001c: ldstr "{0}, {1}"
IL_0021: ldloc.0
IL_0022: callvirt "Function C.get_P() As Object"
IL_0027: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_002c: call "Function C.get_Q() As Object"
IL_0031: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0036: call "Sub System.Console.Write(String, Object, Object)"
IL_003b: ret
}
]]>)
End Sub
<Fact>
Public Sub PropertyAutoGetAndSet()
Dim source =
<compilation>
<file name="c.vb">
Module M
Sub Main()
Dim x As C = New C()
x.P = 2
C.Q = "q"
System.Console.Write("{0}, {1}", x.P, C.Q)
End Sub
End Module
Class C
Property P
Shared Property Q
End Class
</file>
</compilation>
Dim compilationVerifier = CompileAndVerify(source, expectedOutput:="2, q")
compilationVerifier.VerifyIL("M.Main",
<![CDATA[
{
// Code size 60 (0x3c)
.maxstack 3
.locals init (C V_0) //x
IL_0000: newobj "Sub C..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.2
IL_0008: box "Integer"
IL_000d: callvirt "Sub C.set_P(Object)"
IL_0012: ldstr "q"
IL_0017: call "Sub C.set_Q(Object)"
IL_001c: ldstr "{0}, {1}"
IL_0021: ldloc.0
IL_0022: callvirt "Function C.get_P() As Object"
IL_0027: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_002c: call "Function C.get_Q() As Object"
IL_0031: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0036: call "Sub System.Console.Write(String, Object, Object)"
IL_003b: ret
}
]]>)
compilationVerifier.VerifyIL("C.get_P",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld "C._P As Object"
IL_0006: ret
}
]]>)
compilationVerifier.VerifyIL("C.set_P",
<![CDATA[
{
// Code size 13 (0xd)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0007: stfld "C._P As Object"
IL_000c: ret
}
]]>)
compilationVerifier.VerifyIL("C.get_Q",
<![CDATA[
{
// Code size 6 (0x6)
.maxstack 1
IL_0000: ldsfld "C._Q As Object"
IL_0005: ret
}
]]>)
compilationVerifier.VerifyIL("C.set_Q",
<![CDATA[
{
// Code size 12 (0xc)
.maxstack 1
IL_0000: ldarg.0
IL_0001: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0006: stsfld "C._Q As Object"
IL_000b: ret
}
]]>)
End Sub
#End Region
#Region "Code Gen"
' All property overload metadata should have a name that matches the casing the of the first declared overload
<WorkItem(539893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539893")>
<Fact()>
Public Sub PropertiesILCaseSensitivity()
Dim source =
<compilation>
<file name="a.vb">
Public Class TestClass
Property P As Integer
Property p(i As Integer) As Integer
Get
Return Nothing
End Get
Set(value As Integer)
End Set
End Property
Overridable Property P(i As String) As Integer
Get
Return Nothing
End Get
Set(value As Integer)
End Set
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source, OutputKind.DynamicallyLinkedLibrary)
Dim referenceBytes = New IO.MemoryStream()
compilation.Emit(referenceBytes)
Dim symbols = MetadataTestHelpers.GetSymbolsForReferences({referenceBytes.GetBuffer()}).Single()
Dim testClassSymbol = symbols.Modules.First().GlobalNamespace.GetMembers("TestClass").OfType(Of NamedTypeSymbol).Single()
Dim propertySymbols = testClassSymbol.GetMembers("P").OfType(Of PropertySymbol)()
Dim propertyGettersSymbols = testClassSymbol.GetMembers("get_P").OfType(Of MethodSymbol)()
Assert.Equal(propertySymbols.Count(Function(psymb) psymb.Name.Equals("P")), 3)
Assert.Equal(propertyGettersSymbols.Count(Function(msymb) msymb.Name.Equals("get_p")), 1)
Assert.Equal(propertyGettersSymbols.Count(Function(msymb) msymb.Name.Equals("get_P")), 2)
End Sub
#End Region
#Region "Properties Parameters"
' Set method with no explicit parameter.
<Fact>
Public Sub SetParameterImplicit()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">
Class C
Private _p As Object
Property P
Get
Return _p
End Get
Set
_p = value
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
' Set method with parameter name different from default.
<Fact>
Public Sub SetParameterNonDefaultName()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="c.vb">
Class C
Private _p As Object
Property P
Get
Return _p
End Get
Set(v)
_p = v
End Set
End Property
End Class
</file>
</compilation>)
CompilationUtils.AssertNoErrors(compilation)
End Sub
' Set method must specify type if property type is not Object.
<Fact>
Public Sub SetParameterExplicitTypeForNonObjectProperty()
CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Class C
Private _p As Integer
Property P As Integer
Get
Return _p
End Get
Set(value)
_p = value
End Set
End Property
End Class
</file>
</compilation>).
VerifyDiagnostics(
Diagnostic(ERRID.ERR_SetValueNotPropertyType, "value"))
End Sub
<Fact>
Public Sub PropertyMembers()
Dim sources = <compilation>
<file name="c.vb">
Interface I
Property P
ReadOnly Property Q
WriteOnly Property R
End Interface
MustInherit Class A
MustOverride Property P
MustOverride ReadOnly Property Q
MustOverride WriteOnly Property R
End Class
Class B
Property P
ReadOnly Property Q
Get
Return Nothing
End Get
End Property
WriteOnly Property R
Set
End Set
End Property
End Class
</file>
</compilation>
Dim validator = Function(isFromSource As Boolean) _
Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("I").Single()
VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=False)
VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False)
VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False)
type = [module].GlobalNamespace.GetTypeMembers("A").Single()
VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=False)
VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False)
VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False)
type = [module].GlobalNamespace.GetTypeMembers("B").Single()
VerifyProperty(type, "P", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=True, hasField:=True)
VerifyProperty(type, "Q", Accessibility.Public, isFromSource, hasGet:=True, hasSet:=False, hasField:=False)
VerifyProperty(type, "R", Accessibility.Public, isFromSource, hasGet:=False, hasSet:=True, hasField:=False)
End Sub
CompileAndVerify(sources, sourceSymbolValidator:=validator(True), symbolValidator:=validator(False))
End Sub
Private Sub VerifyProperty(type As NamedTypeSymbol, name As String, declaredAccessibility As Accessibility, isFromSource As Boolean, hasGet As Boolean, hasSet As Boolean, hasField As Boolean)
Dim [property] = TryCast(type.GetMembers(name).SingleOrDefault(), PropertySymbol)
Assert.NotNull([property])
Assert.Equal([property].DeclaredAccessibility, declaredAccessibility)
Dim accessor = [property].GetMethod
If hasGet Then
Assert.NotNull(accessor)
Assert.Equal(accessor.DeclaredAccessibility, declaredAccessibility)
Else
Assert.Null(accessor)
End If
accessor = [property].SetMethod
If hasSet Then
Assert.NotNull(accessor)
Assert.Equal(accessor.DeclaredAccessibility, declaredAccessibility)
Else
Assert.Null(accessor)
End If
Dim field = DirectCast(type.GetMembers("_" + name).SingleOrDefault(), FieldSymbol)
If isFromSource AndAlso hasField Then
Assert.NotNull(field)
Assert.Equal(field.DeclaredAccessibility, Accessibility.Private)
Else
Assert.Null(field)
End If
End Sub
<Fact>
Public Sub PropertyGetAndSetWithParameters()
Dim sources = <compilation>
<file name="c.vb">
Module Module1
Sub Main()
Dim x As C = New C()
x.P(1) = 2
System.Console.Write("{0}, {1}", x.P(1), x.P(x.P(1)))
End Sub
End Module
Class C
Private _p As Object
Property P(ByVal i As Integer) As Object
Get
If (i = 1) Then
Return _p
End If
Return 0
End Get
Set(ByVal value As Object)
If (i = 1) Then
_p = value
End If
End Set
End Property
End Class
</file>
</compilation>
Dim validator = Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("C").Single()
Dim [property] = type.GetMembers("P").OfType(Of PropertySymbol)().SingleOrDefault()
Assert.NotNull([property])
VerifyPropertiesParametersCount([property], 1)
Assert.Equal(SpecialType.System_Object, [property].Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, [property].Parameters(0).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, [property].GetMethod.Parameters(0).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, [property].SetMethod.Parameters(0).Type.SpecialType)
Assert.Equal(SpecialType.System_Object, [property].SetMethod.Parameters(1).Type.SpecialType)
Assert.Equal([property].SetMethod.Parameters(1).Name, "value")
End Sub
CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator, expectedOutput:="2, 0")
End Sub
<Fact()>
Public Sub PropertyGetAndSetWithParametersOverridesAndGeneric()
Dim sources = <compilation>
<file name="c.vb">
Public MustInherit Class TestClass(Of T)
End Class
Public Class TestClass2
Inherits TestClass(Of String)
Public Overloads Property P1(pr1 As String, Optional pr2 As String = "") As Integer
Get
Return Nothing
End Get
Set(value As Integer)
End Set
End Property
Public Overloads Property P1(pr1 As Integer, pr2 As String, ParamArray parray() As Double) As Integer
Get
Return Nothing
End Get
Set(value As Integer)
End Set
End Property
Public Overloads Property P2(pr1 As Integer, pr2 As String) As Integer
Get
Return Nothing
End Get
Set
End Set
End Property
Public Overloads Property P2(pr1 As String, Optional pr2 As String = Nothing) As String
Get
Return Nothing
End Get
Set
End Set
End Property
End Class
</file>
</compilation>
Dim validator = Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("TestClass2").Single()
Dim P1s = type.GetMembers("P1").OfType(Of PropertySymbol)().OrderBy(Function(symb) symb.GetMethod.Parameters.Length)
Dim P2s = type.GetMembers("P2").OfType(Of PropertySymbol)().OrderBy(Function(symb) symb.GetMethod.ReturnType.Name)
Assert.NotNull(P1s)
Assert.NotNull(P2s)
Assert.NotEmpty(P1s)
Assert.NotEmpty(P2s)
VerifyPropertiesParametersCount(P1s.ElementAt(0), 2)
VerifyPropertiesParametersCount(P1s.ElementAt(1), 3)
Assert.True(P1s.ElementAt(0).Parameters(1).IsOptional)
Assert.Equal(P1s.ElementAt(0).Parameters(1).ExplicitDefaultValue, String.Empty)
Assert.True(P1s.ElementAt(1).Parameters(2).IsParamArray)
VerifyPropertiesParametersCount(P2s.ElementAt(0), 2)
VerifyPropertiesParametersCount(P2s.ElementAt(1), 2)
Assert.Equal(SpecialType.System_String, P2s.ElementAt(1).Type.SpecialType)
End Sub
CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<Fact>
Public Sub SetWithParametersGetObjectValue()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Class C
Sub Invoke(arg, value)
P(arg) = value
End Sub
Property P(arg As Object) As Object
Get
Return Nothing
End Get
Set(ByVal value As Object)
End Set
End Property
End Class
</file>
</compilation>)
compilationVerifier.VerifyIL("C.Invoke",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 3
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0007: ldarg.2
IL_0008: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000d: call "Sub C.set_P(Object, Object)"
IL_0012: ret
}
]]>)
End Sub
<Fact>
Public Sub DictionaryMemberAccess()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System
Imports System.Collections.Generic
Class C
Private _P As Dictionary(Of String, String)
Default Property P(key As String) As String
Get
Return _P(key)
End Get
Set(value As String)
_P(key) = value
End Set
End Property
Sub New()
_P = New Dictionary(Of String, String)
End Sub
Shared Sub Main()
Dim x As C = New C()
x("A") = "value"
x!B = x!A.ToUpper()
Console.WriteLine("A={0}, B={1}", x("A"), x("B"))
End Sub
End Class
</file>
</compilation>,
expectedOutput:="A=value, B=VALUE")
End Sub
<Fact>
Public Sub DictionaryMemberAccessPassByRef()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System
Imports System.Collections.Generic
Class A
Private _P As Dictionary(Of String, String)
Default Property P(key As String) As String
Get
Return _P(key)
End Get
Set(value As String)
_P(key) = value
End Set
End Property
Sub New()
_P = New Dictionary(Of String, String)
End Sub
End Class
Class B
Private _Q As Dictionary(Of String, A)
Default ReadOnly Property Q(key As String) As A
Get
Return _Q(key)
End Get
End Property
Sub New(key As String, value As A)
_Q = New Dictionary(Of String, A)
_Q(key) = value
End Sub
End Class
Class C
Shared Sub Main()
Dim value As A = New A()
value("B") = "value"
Dim x As B = New B("A", value)
Console.WriteLine("Before: {0}", x!A!B)
M(x!A!B)
Console.WriteLine("After: {0}", x!A!B)
End Sub
Shared Sub M(ByRef s As String)
s = s.ToUpper()
End Sub
End Class
</file>
</compilation>,
expectedOutput:=<![CDATA[
Before: value
After: VALUE
]]>)
End Sub
<Fact>
Public Sub DictionaryMemberAccessWithTypeCharacter()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Option Infer Off
Imports System.Collections.Generic
Module M
Sub Main()
M()
End Sub
Sub M()
Dim d As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
d!x% = 1
d!y = 2
Dim x = d!x
Dim y = d!y%
System.Console.WriteLine("{0}, {1}", x, y)
End Sub
End Module
</file>
</compilation>,
expectedOutput:="1, 2")
compilationVerifier.VerifyIL("M.M",
<![CDATA[
{
// Code size 85 (0x55)
.maxstack 4
.locals init (Object V_0, //x
Object V_1) //y
IL_0000: newobj "Sub System.Collections.Generic.Dictionary(Of String, Integer)..ctor()"
IL_0005: dup
IL_0006: ldstr "x"
IL_000b: ldc.i4.1
IL_000c: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Integer).set_Item(String, Integer)"
IL_0011: dup
IL_0012: ldstr "y"
IL_0017: ldc.i4.2
IL_0018: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Integer).set_Item(String, Integer)"
IL_001d: dup
IL_001e: ldstr "x"
IL_0023: callvirt "Function System.Collections.Generic.Dictionary(Of String, Integer).get_Item(String) As Integer"
IL_0028: box "Integer"
IL_002d: stloc.0
IL_002e: ldstr "y"
IL_0033: callvirt "Function System.Collections.Generic.Dictionary(Of String, Integer).get_Item(String) As Integer"
IL_0038: box "Integer"
IL_003d: stloc.1
IL_003e: ldstr "{0}, {1}"
IL_0043: ldloc.0
IL_0044: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0049: ldloc.1
IL_004a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_004f: call "Sub System.Console.WriteLine(String, Object, Object)"
IL_0054: ret
}
]]>)
End Sub
#End Region
#Region "Auto Properties"
<Fact>
Public Sub AutoPropertyInitializer()
Dim source =
<compilation>
<file name="c.vb">
Module M
Sub Main()
' touch something shared from A or derived classes to force the shared constructors always to run.
' otherwise beforefieldinit causes different results while running under the debugger.
Dim ignored = A.Dummy
M(New ADerived())
M(New ADerived())
M(New BDerived())
M(New BDerived())
End Sub
Sub M(ByVal o)
End Sub
End Module
Class ABase
Sub New()
C.Message("ABase..ctor")
End Sub
End Class
Class A
Inherits ABase
Shared Property P = New C("Shared Property A.P")
Public Shared F = New C("Shared Field A.F")
Public G = New C("Instance Field A.G")
Overridable Property Q = New C("Instance Property A.Q")
Public Shared Dummy As Integer = 23
End Class
Class ADerived
Inherits A
Public Overrides Property Q As Object
Get
Return Nothing
End Get
Set(ByVal value As Object)
C.Message("A.Q.set")
End Set
End Property
End Class
Class BBase
Sub New()
C.Message("BBase..ctor")
End Sub
End Class
Class B
Inherits BBase
Public Shared F = New C("Shared Field B.F")
Shared Property P = New C("Shared Property B.P")
Overridable Property Q = New C("Instance Property B.Q")
Public G = New C("Instance Field B.G")
Shared Sub New()
C.Message("B..cctor")
End Sub
Sub New()
C.Message("B..ctor")
End Sub
End Class
Class BDerived
Inherits B
Public Overrides Property Q As Object
Get
Return Nothing
End Get
Set(ByVal value As Object)
C.Message("B.Q.set")
End Set
End Property
End Class
Class C
Public Sub New(ByVal s As String)
Message(s)
End Sub
Shared Sub Message(ByVal s As String)
System.Console.WriteLine("{0}", s)
End Sub
End Class
</file>
</compilation>
' if a debugger is attached, the beforefieldinit attribute is ignored and the shared constructors
' are executed although no shared fields have been accessed. This causes the test to fail under a debugger.
' Therefore I've added an access to a shared field of class A, because accessing a field of type ADerived
' would not trigger the base type initializers.
Dim compilationVerifier = CompileAndVerify(source,
expectedOutput:=<![CDATA[
Shared Property A.P
Shared Field A.F
ABase..ctor
Instance Field A.G
Instance Property A.Q
A.Q.set
ABase..ctor
Instance Field A.G
Instance Property A.Q
A.Q.set
Shared Field B.F
Shared Property B.P
B..cctor
BBase..ctor
Instance Property B.Q
B.Q.set
Instance Field B.G
B..ctor
BBase..ctor
Instance Property B.Q
B.Q.set
Instance Field B.G
B..ctor
]]>)
compilationVerifier.VerifyIL("A..ctor",
<![CDATA[
{
// Code size 39 (0x27)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub ABase..ctor()"
IL_0006: ldarg.0
IL_0007: ldstr "Instance Field A.G"
IL_000c: newobj "Sub C..ctor(String)"
IL_0011: stfld "A.G As Object"
IL_0016: ldarg.0
IL_0017: ldstr "Instance Property A.Q"
IL_001c: newobj "Sub C..ctor(String)"
IL_0021: callvirt "Sub A.set_Q(Object)"
IL_0026: ret
}
]]>)
compilationVerifier.VerifyIL("B..ctor",
<![CDATA[
{
// Code size 49 (0x31)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub BBase..ctor()"
IL_0006: ldarg.0
IL_0007: ldstr "Instance Property B.Q"
IL_000c: newobj "Sub C..ctor(String)"
IL_0011: callvirt "Sub B.set_Q(Object)"
IL_0016: ldarg.0
IL_0017: ldstr "Instance Field B.G"
IL_001c: newobj "Sub C..ctor(String)"
IL_0021: stfld "B.G As Object"
IL_0026: ldstr "B..ctor"
IL_002b: call "Sub C.Message(String)"
IL_0030: ret
}
]]>)
End Sub
<Fact>
Public Sub OverrideAutoPropertyInitializer()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Module M1
Sub Main()
Dim c As C = New C()
c.P = 3
End Sub
End Module
Class A
Overridable Property P As Integer = 1
End Class
Class B
Inherits A
Overrides Property P As Integer = 2
End Class
Class C
Inherits B
Overrides Property P As Integer
Get
Return 0
End Get
Set(value As Integer)
System.Console.Write("{0}, ", value)
End Set
End Property
End Class
</file>
</compilation>, expectedOutput:="1, 2, 3, ")
compilationVerifier.VerifyIL("B..ctor",
<![CDATA[
{
// Code size 14 (0xe)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub A..ctor()"
IL_0006: ldarg.0
IL_0007: ldc.i4.2
IL_0008: callvirt "Sub B.set_P(Integer)"
IL_000d: ret
}
]]>)
End Sub
<Fact>
Public Sub AutoProperties()
Dim validator = Function(isFromSource As Boolean) _
Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("C").Single()
VerifyAutoProperty(type, "P", Accessibility.Protected, isFromSource)
VerifyAutoProperty(type, "Q", Accessibility.Friend, isFromSource)
End Sub
CompileAndVerify(
<compilation>
<file name="c.vb">
Class C
Protected Property P
Friend Shared Property Q
End Class
</file>
</compilation>,
sourceSymbolValidator:=validator(True),
symbolValidator:=validator(False),
options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal))
End Sub
<Fact>
Public Sub AutoPropertiesComplexTypeInitializer()
CompileAndVerify(
<compilation>
<file name="c.vb">
Module M1
Sub Main()
Dim c As C = New C()
c.P2.P1 = 2
System.Console.WriteLine(String.Join(",", c.P2.P1, String.Join(",", c.P3)))
End Sub
End Module
Class A
Property P1 As Integer = 1
Overridable Property P2 As A
Property P3() As String() = New String() {"A", "B", "C"}
End Class
Class C
Inherits A
Overrides Property P2 As New A()
End Class
</file>
</compilation>, expectedOutput:="2,A,B,C")
End Sub
<Fact>
Public Sub AutoPropertiesAsNewInitializer()
Dim source =
<compilation>
<file name="c.vb">
imports system
Class C1
Public field As Integer
Public Sub New(p As Integer)
field = p
End Sub
End Class
Class C2
Public Property P1 As New C1(23)
Public Shared Sub Main()
Dim c as new C2()
console.writeline(c.P1.field)
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=<![CDATA[
23
]]>)
End Sub
<WorkItem(542749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542749")>
<Fact>
Public Sub ValueInAutoAndDefaultProperties()
Dim source =
<compilation>
<file name="pp.vb">
Imports system
Class C
Public Property AP As String
Structure S
Default Public Property DefP(p As String) As String
Get
Return p
End Get
Set
End Set
End Property
End Structure
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source)
Dim type01 = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single()
Dim type02 = type01.GetTypeMembers("S").Single()
Dim autoProp = DirectCast(type01.GetMembers("AP").SingleOrDefault(), PropertySymbol)
Dim deftProp = DirectCast(type02.GetMembers("DefP").SingleOrDefault(), PropertySymbol)
' All accessor's parameters should be Synthesized if it's NOT in source
Assert.NotNull(autoProp.SetMethod)
For Each p In autoProp.SetMethod.Parameters
Assert.True(p.IsImplicitlyDeclared)
Assert.True(p.IsFromCompilation(compilation))
Next
Assert.NotNull(deftProp.SetMethod)
For Each p In deftProp.SetMethod.Parameters
Assert.True(p.IsImplicitlyDeclared)
If p.Name.ToLower() <> "value" Then
' accessor's parameter should point to same location as the parameter's of parent property
Assert.False(p.Locations.IsEmpty)
End If
Next
End Sub
<Fact>
Public Sub ReadOnlyAutoProperties()
Dim verifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System.Console
Module Program
Sub Main()
Dim collection As New MyCollection()
Write(collection.Capacity)
Write(collection.Capacity = MyCollection.DefaultCapacity)
collection = New MyCollection(15)
Write(collection.Capacity)
collection.DoubleCapacity()
Write(collection.Capacity)
End Sub
End Module
Class MyCollection
Public Shared ReadOnly Property DefaultCapacity As Integer = 5
Public ReadOnly Property Capacity As Integer = DefaultCapacity
Public Sub New()
Write(_Capacity)
End Sub
Public Sub New(capacity As Integer)
Write(_Capacity)
_Capacity = capacity
End Sub
Public Sub DoubleCapacity()
_Capacity *= 2
End Sub
End Class
</file>
</compilation>,
sourceSymbolValidator:=Sub(m As ModuleSymbol)
Dim myCollectionType = m.GlobalNamespace.GetTypeMember("MyCollection")
Dim defaultCapacityProperty = CType(myCollectionType.GetMember("DefaultCapacity"), PropertySymbol)
Assert.True(defaultCapacityProperty.IsReadOnly)
Assert.False(defaultCapacityProperty.IsWriteOnly)
Assert.True(defaultCapacityProperty.IsShared)
Assert.NotNull(defaultCapacityProperty.GetMethod)
Assert.Null(defaultCapacityProperty.SetMethod)
Dim backingField = CType(myCollectionType.GetMember("_DefaultCapacity"), FieldSymbol)
Assert.NotNull(defaultCapacityProperty.AssociatedField)
Assert.Same(defaultCapacityProperty.AssociatedField, backingField)
End Sub,
expectedOutput:="55True51530")
verifier.VerifyIL("MyCollection..cctor()",
<![CDATA[
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.5
IL_0001: stsfld "MyCollection._DefaultCapacity As Integer"
IL_0006: ret
}
]]>)
verifier.VerifyIL("MyCollection..ctor()",
<![CDATA[
{
// Code size 29 (0x1d)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: call "Function MyCollection.get_DefaultCapacity() As Integer"
IL_000c: stfld "MyCollection._Capacity As Integer"
IL_0011: ldarg.0
IL_0012: ldfld "MyCollection._Capacity As Integer"
IL_0017: call "Sub System.Console.Write(Integer)"
IL_001c: ret
}
]]>)
End Sub
<Fact>
Public Sub WriteOnlyAutoProperties()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Imports System.Console
Module Program
Sub Main()
Dim collection As New MyCollection()
collection.Capacity = 10
collection.WriteCapacity()
MyCollection.DefaultCapacity = 15
MyCollection.WriteDefaultCapacity()
End Sub
End Module
Class MyCollection
Public Shared WriteOnly Property DefaultCapacity As Integer = 5
Public WriteOnly Property Capacity As Integer = _DefaultCapacity
Shared Sub New()
WriteDefaultCapacity()
End Sub
Public Sub New()
WriteCapacity()
End Sub
Public Sub WriteCapacity()
Write(_Capacity)
Write("_")
End Sub
Public Shared Sub WriteDefaultCapacity()
Write(_DefaultCapacity)
Write("_")
End Sub
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37243: Auto-implemented properties cannot be WriteOnly.
Public Shared WriteOnly Property DefaultCapacity As Integer = 5
~~~~~~~~~~~~~~~
BC37243: Auto-implemented properties cannot be WriteOnly.
Public WriteOnly Property Capacity As Integer = _DefaultCapacity
~~~~~~~~
</expected>)
End Sub
<Fact>
Public Sub ReadOnlyAutoPropertiesAndImplements()
Dim verifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System.Console
Module Program
Sub Main()
Dim test As New Test()
Dim i As I1 = test
Write(i.P1)
Write("_")
End Sub
End Module
Interface I1
ReadOnly Property P1 As Integer
End Interface
Class Test
Implements I1
Sub New()
_P1 = 5
End Sub
Public ReadOnly Property P1 As Integer Implements I1.P1
End Class
</file>
</compilation>,
expectedOutput:="5_")
End Sub
<Fact>
Public Sub ReadOnlyWriteOnlyAutoPropertiesAndImplementsMismatch()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Module Program
Sub Main()
End Sub
End Module
Interface I1
ReadOnly Property P1 As Integer
WriteOnly Property P2 As Integer
Property P3 As Integer
Property P4 As Integer
End Interface
Class Test
Implements I1
Public WriteOnly Property P1 As Integer Implements I1.P1
Public ReadOnly Property P2 As Integer Implements I1.P2
Public WriteOnly Property P3 As Integer Implements I1.P3
Public ReadOnly Property P4 As Integer Implements I1.P4
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC37243: Auto-implemented properties cannot be WriteOnly.
Public WriteOnly Property P1 As Integer Implements I1.P1
~~
BC31444: 'ReadOnly Property P1 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property P1 As Integer Implements I1.P1
~~~~~
BC31444: 'WriteOnly Property P2 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property P2 As Integer Implements I1.P2
~~~~~
BC37243: Auto-implemented properties cannot be WriteOnly.
Public WriteOnly Property P3 As Integer Implements I1.P3
~~
BC31444: 'Property P3 As Integer' cannot be implemented by a WriteOnly property.
Public WriteOnly Property P3 As Integer Implements I1.P3
~~~~~
BC31444: 'Property P4 As Integer' cannot be implemented by a ReadOnly property.
Public ReadOnly Property P4 As Integer Implements I1.P4
~~~~~
</expected>)
End Sub
<Fact>
Public Sub ReadOnlyAutoPropertiesAndOverrides()
Dim verifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System.Console
Module Program
Sub Main()
Dim test As New Test()
Dim i As I1 = test
Write(i.P1)
Write("_")
End Sub
End Module
Class I1
Overridable ReadOnly Property P1 As Integer
End Class
Class Test
Inherits I1
Sub New()
_P1 = 5
End Sub
Public Overrides ReadOnly Property P1 As Integer
End Class
</file>
</compilation>,
expectedOutput:="5_")
End Sub
<Fact>
Public Sub ReadOnlyWriteOnlyAutoPropertiesAndOverridesMismatch()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Module Program
Sub Main()
End Sub
End Module
Class I1
Overridable WriteOnly Property P2 As Integer
Set
end set
end property
Overridable Property P4 As Integer
End Class
Class Test
Inherits I1
Public Overrides ReadOnly Property P2 As Integer
Public Overrides ReadOnly Property P4 As Integer
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overridable WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides ReadOnly Property P2 As Integer
~~
BC30362: 'Public Overrides ReadOnly Property P4 As Integer' cannot override 'Public Overridable Property P4 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'.
Public Overrides ReadOnly Property P4 As Integer
~~
</expected>)
End Sub
<Fact>
Public Sub ReadOnlyAutoPropertiesAndIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Module Program
Sub Main()
End Sub
End Module
Class Test
Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30025: Property missing 'End Property'.
Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30126: 'ReadOnly' property must provide a 'Get'.
Iterator ReadOnly Property P1 As System.Collections.Generic.IEnumerable(Of Integer)
~~
</expected>)
End Sub
<Fact>
Public Sub WriteOnlyAutoPropertiesAndIterator()
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="c.vb">
Module Program
Sub Main()
End Sub
End Module
Class Test
Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer)
End Class
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30025: Property missing 'End Property'.
Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31408: 'Iterator' and 'WriteOnly' cannot be combined.
Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer)
~~~~~~~~~
BC30124: Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
Iterator WriteOnly Property P2 As System.Collections.Generic.IEnumerable(Of Integer)
~~
</expected>)
End Sub
#End Region
#Region "Default Properties"
<Fact>
Public Sub DefaultProperties()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
Dim d As New DefaultProps
d(0) = 10
d("1") = 20
d.Items("2") = 30
d.items(3) = 40
System.Console.WriteLine(String.Join(",", d._items))
End Sub
End Module
Public Class DefaultProps
Public _items As Integer()
Public Sub New()
_items = New Integer(3) {}
End Sub
Default Property Items(index As Integer) As Integer
Get
Return _items(index)
End Get
Set(value As Integer)
_items(index) = value
End Set
End Property
Default Property items(index As String) As Integer
Get
Return _items(index)
End Get
Set(value As Integer)
_items(index) = value
End Set
End Property
End Class
</file>
</compilation>
Dim expectedMainILSource = <![CDATA[
{
// Code size 72 (0x48)
.maxstack 3
.locals init (DefaultProps V_0) //d
IL_0000: newobj "Sub DefaultProps..ctor()"
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: ldc.i4.0
IL_0008: ldc.i4.s 10
IL_000a: callvirt "Sub DefaultProps.set_Items(Integer, Integer)"
IL_000f: ldloc.0
IL_0010: ldstr "1"
IL_0015: ldc.i4.s 20
IL_0017: callvirt "Sub DefaultProps.set_items(String, Integer)"
IL_001c: ldloc.0
IL_001d: ldstr "2"
IL_0022: ldc.i4.s 30
IL_0024: callvirt "Sub DefaultProps.set_items(String, Integer)"
IL_0029: ldloc.0
IL_002a: ldc.i4.3
IL_002b: ldc.i4.s 40
IL_002d: callvirt "Sub DefaultProps.set_Items(Integer, Integer)"
IL_0032: ldstr ","
IL_0037: ldloc.0
IL_0038: ldfld "DefaultProps._items As Integer()"
IL_003d: call "Function String.Join(Of Integer)(String, System.Collections.Generic.IEnumerable(Of Integer)) As String"
IL_0042: call "Sub System.Console.WriteLine(String)"
IL_0047: ret
}
]]>
Dim validator = Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("DefaultProps").Single()
Dim properties = type.GetMembers("Items").OfType(Of PropertySymbol)()
Assert.True(properties.All(Function(prop) prop.IsDefault), "Not All default properties had PropertySymbol.IsDefault=true")
End Sub
Dim compilationVerifier = CompileAndVerify(source, sourceSymbolValidator:=validator, symbolValidator:=validator, expectedOutput:="10,20,30,40")
compilationVerifier.VerifyIL("Program.Main", expectedMainILSource)
End Sub
<Fact>
Public Sub DefaultPropertySameBaseAndDerived()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
' Base and derived properties marked Default.
Class A1
Default Public ReadOnly Property P(i As Integer)
Get
Return Nothing
End Get
End Property
End Class
Class B1
Inherits A1
Default Public Overloads WriteOnly Property P(x As Integer, y As Integer)
Set(value)
End Set
End Property
End Class
Class C1
Inherits B1
End Class
' Derived property marked Default, base property not.
Class A2
Public ReadOnly Property P(i As Integer)
Get
Return Nothing
End Get
End Property
End Class
Class B2
Inherits A2
Default Public Overloads WriteOnly Property P(x As Integer, y As Integer)
Set(value)
End Set
End Property
End Class
Class C2
Inherits B2
End Class
' Base property marked Default, derived property not.
Class A3
Default Public ReadOnly Property P(i As Integer)
Get
Return Nothing
End Get
End Property
End Class
Class B3
Inherits A3
Public Overloads WriteOnly Property P(x As Integer, y As Integer)
Set(value)
End Set
End Property
End Class
Class C3
Inherits B3
End Class
Module M
Sub M(a As A1, b As B1, c As C1)
b.P(1, 2) = a.P(3)
b(1, 2) = a(3)
c.P(1, 2) = c.P(3)
c(1, 2) = c(3)
End Sub
Sub M(a As A2, b As B2, c As C2)
b.P(4, 5) = a.P(6)
b(4, 5) = a(6)
c.P(4, 5) = c.P(6)
c(4, 5) = c(6)
End Sub
Sub M(a As A3, b As B3, c As C3)
b.P(7, 8) = a.P(9)
b(7, 8) = a(9)
c.P(7, 8) = c.P(9)
c(7, 8) = c(9)
End Sub
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30367: Class 'A2' cannot be indexed because it has no default property.
b(4, 5) = a(6)
~
BC30057: Too many arguments to 'Public ReadOnly Default Property P(i As Integer) As Object'.
b(7, 8) = a(9)
~
BC30057: Too many arguments to 'Public ReadOnly Default Property P(i As Integer) As Object'.
c(7, 8) = c(9)
~
</expected>)
End Sub
<Fact>
Public Sub DefaultPropertyDifferentBaseAndDerived()
Dim compilationVerifier = CompileAndVerify(
<compilation>
<file name="c.vb">
Imports System
' Default property "P"
Class A
Default Public ReadOnly Property P(i As Integer)
Get
Console.WriteLine("A.P: {0}", i)
Return Nothing
End Get
End Property
Public ReadOnly Property Q(i As Integer)
Get
Console.WriteLine("A.Q: {0}", i)
Return Nothing
End Get
End Property
Public ReadOnly Property R(x As Integer, y As Integer)
Get
Console.WriteLine("A.R: {0}, {1}", x, y)
Return Nothing
End Get
End Property
End Class
' Default property "Q"
Class B
Inherits A
Public Overloads ReadOnly Property P(i As Integer)
Get
Console.WriteLine("B.P: {0}", i)
Return Nothing
End Get
End Property
Default Public Overloads ReadOnly Property Q(i As Integer)
Get
Console.WriteLine("B.Q: {0}", i)
Return Nothing
End Get
End Property
End Class
' Default property "R"
Class C
Inherits B
Default Public Overloads ReadOnly Property R(i As Integer)
Get
Console.WriteLine("C.R: {0}", i)
Return Nothing
End Get
End Property
End Class
' No default property
Class D
Inherits B
Public Overloads ReadOnly Property P(i As Integer)
Get
Console.WriteLine("C.P: {0}", i)
Return Nothing
End Get
End Property
Public Overloads ReadOnly Property Q(i As Integer)
Get
Console.WriteLine("C.Q: {0}", i)
Return Nothing
End Get
End Property
End Class
Module M
Sub M(x As C, y As D)
Dim value = x(1)
value = x(2, 3)
value = y(4)
value = DirectCast(y, B)(5)
value = DirectCast(y, A)(6)
End Sub
Sub Main()
M(New C(), New D())
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[
C.R: 1
A.R: 2, 3
B.Q: 4
B.Q: 5
A.P: 6
]]>)
End Sub
<Fact>
Public Sub DefaultPropertyGroupError()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb">
Class C
Default Protected Property P(o As Object)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Module M
Function F(o As C)
Return o(Nothing)
End Function
End Module
</file>
</compilation>)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30389: 'C.P(o As Object)' is not accessible in this context because it is 'Protected'.
Return o(Nothing)
~
</expected>)
End Sub
<Fact>
Public Sub DefaultMembersFromMetadata()
Dim customIL = <![CDATA[
// DefaultMember names field
.class public DefaultField
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.field public object F
}
// DefaultMember names method
.class public DefaultMethod
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object F(object o) { ldnull ret }
}
// DefaultMember names property
.class public DefaultProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object DefaultProperty::get_F(object o) }
}
// DefaultMember names static property
.class public DefaultStaticProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public static hidebysig object get_F(object o) { ldnull ret }
.property object F(object o) { .get object DefaultStaticProperty::get_F(object o) }
}
// Property but no DefaultMember
.class public PropertyNoDefault
{
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object PropertyNoDefault::get_F(object o) }
}
// DefaultMember names property with different case
.class public DifferentCase
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('DefaultName')}
.method public hidebysig instance object get(object o) { ldnull ret }
.property object defaultNAME(object o) { .get instance object DifferentCase::get(object o) }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Module M
Sub M(
x1 As DefaultField,
x2 As DefaultMethod,
x3 As DefaultProperty,
x4 As DefaultStaticProperty,
x5 As PropertyNoDefault,
x6 As DifferentCase)
Dim value As Object
value = x1.F
value = x1()
value = x2.F(value)
value = x2(value)
value = x3.F(value)
value = x3(value)
value = x4.F(value)
value = x4(value)
value = x5.F(value)
value = x5(value)
value = x6.DefaultName(value)
value = x6(value)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30367: Class 'DefaultField' cannot be indexed because it has no default property.
value = x1()
~~
BC30367: Class 'DefaultMethod' cannot be indexed because it has no default property.
value = x2(value)
~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
value = x4.F(value)
~~~~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
value = x4(value)
~~
BC30367: Class 'PropertyNoDefault' cannot be indexed because it has no default property.
value = x5(value)
~~
</expected>)
End Sub
<Fact>
Public Sub DefaultAmbiguousMembersFromMetadata()
Dim customIL = <![CDATA[
// DefaultMember names field and property
.class public DefaultFieldAndProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object DefaultFieldAndProperty::get_F(object o) }
.field public object F
}
// DefaultMember names method and property
.class public DefaultMethodAndProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object F(object x, object y) { ldnull ret }
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object DefaultMethodAndProperty::get_F(object o) }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Module M
Sub M(
a As DefaultFieldAndProperty,
b As DefaultMethodAndProperty)
Dim value As Object
value = a.F
value = a(value)
value = b.F(value)
value = b(value)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultFieldAndProperty'.
value = a.F
~~~
BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultFieldAndProperty'.
value = a(value)
~
BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultMethodAndProperty'.
value = b.F(value)
~~~
BC31429: 'F' is ambiguous because multiple kinds of members with this name exist in class 'DefaultMethodAndProperty'.
value = b(value)
~
</expected>)
End Sub
<Fact>
Public Sub DefaultPropertiesFromMetadata()
Dim customIL = <![CDATA[
// DefaultMember names property
.class public DefaultProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object DefaultProperty::get_F(object o) }
}
// Property but no DefaultMember
.class public PropertyNoDefault
{
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object PropertyNoDefault::get_F(object o) }
}
// DefaultMember names property in base
.class public DefaultBaseProperty extends PropertyNoDefault
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
}
// DefaultMember names field in this class and property in base
.class public DefaultFieldAndBaseProperty extends PropertyNoDefault
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.field public object F
}
// DefaultMember names property (with no args) in this class and property (with args) in base
.class public DefaultPropertyAndBaseProperty extends PropertyNoDefault
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F() { ldnull ret }
.property object F() { .get instance object DefaultPropertyAndBaseProperty::get_F() }
}
// DefaultMember names assembly property in this class and public property in base
.class public DefaultAssemblyPropertyAndBaseProperty extends PropertyNoDefault
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method assembly hidebysig instance object get_F() { ldnull ret }
.property object F() { .get instance object DefaultAssemblyPropertyAndBaseProperty::get_F() }
}
// DefaultMember names no fields in this class while base has different DefaultMember
.class public DifferentDefaultBaseProperty extends DefaultProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')}
}
// DefaultMember names property in this class while base has different DefaultMember
.class public DifferentDefaultPropertyAndBaseProperty extends DefaultProperty
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')}
.method public hidebysig instance object get_G() { ldnull ret }
.property object G() { .get instance object DifferentDefaultPropertyAndBaseProperty::get_G() }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Module M
Sub M(
x1 As DefaultBaseProperty,
x2 As DefaultFieldAndBaseProperty,
x3 As DefaultPropertyAndBaseProperty,
x4 As DefaultAssemblyPropertyAndBaseProperty,
x5 As DifferentDefaultBaseProperty,
x6 As DifferentDefaultPropertyAndBaseProperty)
Dim value As Object = Nothing
value = x1.F(value)
value = x1(value)
value = x2()
value = x3.F(value)
value = x3(value)
value = x3()
value = x4.F(value)
value = x4(value)
value = x4()
value = x5.F(value)
value = x5(value)
value = x6.F(value)
value = x6(value)
value = x6.G()
value = x6()
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30367: Class 'DefaultBaseProperty' cannot be indexed because it has no default property.
value = x1(value)
~~
BC30367: Class 'DefaultFieldAndBaseProperty' cannot be indexed because it has no default property.
value = x2()
~~
BC30367: Class 'DefaultAssemblyPropertyAndBaseProperty' cannot be indexed because it has no default property.
value = x4(value)
~~
BC30367: Class 'DefaultAssemblyPropertyAndBaseProperty' cannot be indexed because it has no default property.
value = x4()
~~
BC30574: Option Strict On disallows late binding.
value = x6(value)
~~
</expected>)
End Sub
<Fact()>
Public Sub DefaultPropertiesFromMetadata2()
Dim customIL = <![CDATA[
.class public auto ansi Class1
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 54 65 73 74 00 00 ) // ...Test..
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method Class1::.ctor
.method public specialname static int32
get_Test(int32 x) cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
} // end of method Class1::get_Test
.method public specialname static int32
get_Test(int32 x,
int32 y) cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.2
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
} // end of method Class1::get_Test
.method public specialname instance int32
get_Test(int64 x,
int32 y) cil managed
{
// Code size 6 (0x6)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldc.i4.3
IL_0001: stloc.0
IL_0002: br.s IL_0004
IL_0004: ldloc.0
IL_0005: ret
} // end of method Class1::get_Test
.property int32 Test(int32)
{
.get int32 Class1::get_Test(int32)
} // end of property Class1::Test
.property int32 Test(int32,
int32)
{
.get int32 Class1::get_Test(int32,
int32)
} // end of property Class1::Test
.property instance int32 Test(int64,
int32)
{
.get instance int32 Class1::get_Test(int64,
int32)
} // end of property Class1::Test
} // end of class Class1
]]>
Dim source =
<compilation>
<file name="a.vb">
Module M
Sub Main()
Dim x As New Class1()
System.Console.WriteLine(x(1, 2))
System.Console.WriteLine(x(2))
System.Console.WriteLine(x(3L, 2))
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine(x(1, 2))
~
BC42025: Access of shared member, constant member, enum member or nested type through an instance; qualifying expression will not be evaluated.
System.Console.WriteLine(x(2))
~
</expected>)
CompileAndVerify(compilation, expectedOutput:=
<![CDATA[
2
1
3
]]>)
End Sub
<Fact>
Public Sub DefaultPropertiesDerivedTypes()
Dim customIL = <![CDATA[
// Base class with default property
.class public A
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object A::get_F(object o) }
}
// Derived class with property overload
.class public B1 extends A
{
.method public hidebysig instance object get_F(object x, object y) { ldnull ret }
.property object F(object x, object y) { .get instance object B1::get_F(object x, object y) }
}
// Derived class with different default property
.class public B2 extends A
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')}
.method public hidebysig instance object get_G(object x, object y) { ldnull ret }
.property object G(object x, object y) { .get instance object B2::get_G(object x, object y) }
}
// Derived class with different internal default property
.class public B3 extends A
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('G')}
.method assembly hidebysig instance object get_G(object x, object y) { ldnull ret }
.property object G(object x, object y) { .get instance object B3::get_G(object x, object y) }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Module M
Sub M(b1 As B1, b2 As B2, b3 As B3)
Dim value As Object
value = b1(1)
value = b1(2, 3)
value = b2(1)
value = b2(2, 3)
value = b3(1)
value = b3(2, 3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'.
value = b1(2, 3)
~
BC30455: Argument not specified for parameter 'y' of 'Public Overloads ReadOnly Default Property G(x As Object, y As Object) As Object'.
value = b2(1)
~~
BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'.
value = b3(2, 3)
~
</expected>)
End Sub
<WorkItem(529554, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529554")>
<Fact()>
Public Sub DefaultPropertiesWithShadowingMethod()
Dim customIL = <![CDATA[
// Base class with default property
.class public A
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object o) { ldnull ret }
.property object F(object o) { .get instance object A::get_F(object o) }
}
// Derived class with method with same name
.class public B extends A
{
.method public hidebysig instance object F(int32 x, int32 y) { ldnull ret }
}
// Derived class with default property overload
.class public C1 extends B
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig instance object get_F(object x, object y) { ldnull ret }
.property object F(object x, object y) { .get instance object C1::get_F(object x, object y) }
}
// Derived class with internal default property overload
.class public C2 extends B
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method assembly hidebysig instance object get_F(object x, object y) { ldnull ret }
.property object F(object x, object y) { .get instance object C2::get_F(object x, object y) }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Module M
Sub M(b As B, c1 As C1, c2 As C2)
Dim value As Object
value = b(1)
value = b(2, 3)
value = c1(1)
value = c1(2, 3)
value = c2(1)
value = c2(2, 3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'.
value = b(2, 3)
~
BC30455: Argument not specified for parameter 'y' of 'Public Overloads ReadOnly Default Property F(x As Object, y As Object) As Object'.
value = c1(1)
~~
BC30057: Too many arguments to 'Public Overloads ReadOnly Default Property F(o As Object) As Object'.
value = c2(2, 3)
~
</expected>)
End Sub
<WorkItem(529553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529553")>
<Fact()>
Public Sub DefaultPropertiesInterfacesWithShadowingMethod()
Dim customIL = <![CDATA[
// Base class with default property
.class interface public IA
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig newslot abstract virtual instance object get_F(object o) { }
.property object F(object o) { .get instance object IA::get_F(object o) }
}
// Derived class with method with same name
.class interface public IB implements IA
{
.method public hidebysig newslot abstract virtual instance object F(int32 x, int32 y) { }
}
// Derived class with default property overload
.class interface public IC implements IB
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('F')}
.method public hidebysig newslot abstract virtual instance object get_F(object x, object y) { }
.property object F(object x, object y) { .get instance object IC::get_F(object x, object y) }
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Option Strict On
Module M
Sub M(b As IB, c As IC)
Dim value As Object
value = b(1)
value = b(2, 3)
value = c(1)
value = c(2, 3)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, includeVbRuntime:=True)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'ReadOnly Default Property F(o As Object) As Object'.
value = b(2, 3)
~
</expected>)
End Sub
''' <summary>
''' Should only generate DefaultMemberAttribute if not specified explicitly.
''' </summary>
<Fact()>
Public Sub DefaultMemberAttribute_Errors()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Reflection
' No DefaultMemberAttribute.
Interface IA
Default ReadOnly Property P(o As Object)
End Interface
' Expected DefaultMemberAttribute.
<DefaultMember("P")>
Interface IB
Default ReadOnly Property P(o As Object)
End Interface
' Different DefaultMemberAttribute.
<DefaultMember("Q")>
Interface IC
Default ReadOnly Property P(o As Object)
End Interface
' Nothing DefaultMemberAttribute value.
<DefaultMember(Nothing)>
Interface ID
Default ReadOnly Property P(o As Object)
End Interface
' Empty DefaultMemberAttribute value.
<DefaultMember("")>
Interface IE
Default ReadOnly Property P(o As Object)
End Interface
' Different case.
<DefaultMember("p")>
Interface [IF]
Default ReadOnly Property P(o As Object)
End Interface
' Different case.
<DefaultMember("P")>
Interface IG
Default ReadOnly Property p(o As Object)
End Interface
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'IC'.
Interface IC
~~
BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'ID'.
Interface ID
~~
BC32304: Conflict between the default property and the 'DefaultMemberAttribute' defined on 'IE'.
Interface IE
~~
]]></errors>)
End Sub
''' <summary>
''' Should only generate DefaultMemberAttribute if not specified explicitly.
''' </summary>
<Fact()>
Public Sub DefaultMemberAttribute()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb"><![CDATA[
Imports System.Reflection
' No DefaultMemberAttribute.
Interface IA
Default ReadOnly Property P(o As Object)
End Interface
' Expected DefaultMemberAttribute.
<DefaultMember("P")>
Interface IB
Default ReadOnly Property P(o As Object)
End Interface
' Different DefaultMemberAttribute.
Interface IC
Default ReadOnly Property P(o As Object)
End Interface
' Nothing DefaultMemberAttribute value.
<DefaultMember(Nothing)>
Interface ID
ReadOnly Property P(o As Object)
End Interface
' Empty DefaultMemberAttribute value.
<DefaultMember("")>
Interface IE
ReadOnly Property P(o As Object)
End Interface
' Different case.
<DefaultMember("p")>
Interface [IF]
Default ReadOnly Property P(o As Object)
End Interface
' Different case.
<DefaultMember("P")>
Interface IG
Default ReadOnly Property p(o As Object)
End Interface
]]></file>
</compilation>)
CompileAndVerify(compilation, symbolValidator:=
Sub(m As ModuleSymbol)
Dim globalNamespace = m.GlobalNamespace
Dim type = globalNamespace.GetMember(Of NamedTypeSymbol)("IA")
CheckDefaultMemberAttribute(type, "P")
type = globalNamespace.GetMember(Of NamedTypeSymbol)("IB")
CheckDefaultMemberAttribute(type, "P")
type = globalNamespace.GetMember(Of NamedTypeSymbol)("IC")
CheckDefaultMemberAttribute(type, "P")
type = globalNamespace.GetMember(Of NamedTypeSymbol)("ID")
CheckDefaultMemberAttribute(type, Nothing)
type = globalNamespace.GetMember(Of NamedTypeSymbol)("IE")
CheckDefaultMemberAttribute(type, "")
type = globalNamespace.GetMember(Of NamedTypeSymbol)("IF")
CheckDefaultMemberAttribute(type, "p")
type = globalNamespace.GetMember(Of NamedTypeSymbol)("IG")
CheckDefaultMemberAttribute(type, "P")
End Sub)
End Sub
Private Sub CheckDefaultMemberAttribute(type As NamedTypeSymbol, name As String)
Dim attribute = type.GetAttributes().Single()
Dim attributeType = attribute.AttributeConstructor.ContainingType
Assert.Equal("DefaultMemberAttribute", attributeType.Name)
Assert.Equal(attribute.ConstructorArguments(0).Value, name)
End Sub
<Fact>
Public Sub ParameterNames()
Dim customIL = <![CDATA[
.class public C
{
// Property with getter and setter.
.method public instance object get_P(object g1) { ldnull ret }
.method public instance void set_P(object s1, object s2) { ret }
.property object P(object p1)
{
.get instance object C::get_P(object p2)
.set instance void C::set_P(object p3, object p4)
}
// Property with getter only.
.method public instance object get_Q(object g1) { ldnull ret }
.property object Q(object p1)
{
.get instance object C::get_Q(object p2)
}
// Property with setter only.
.method public instance void set_R(object s1, object s2, object s3) { ret }
.property object R(object p1, object p2)
{
.set instance void C::set_R(object p3, object p4, object p5)
}
// Bogus property: getter with too many parameters.
.method public instance object get_S(object g1, object g2) { ldnull ret }
.method public instance void set_S(object s1, object s2) { ret }
.property object S(object p1)
{
.get instance object C::get_S(object p2, object p3)
.set instance void C::set_S(object p4, object p5)
}
// Bogus property: setter with too many parameters.
.method public instance void set_T(object s1, object s2, object s3) { ret }
.property object T(object p1)
{
.set instance void C::set_T(object p2, object p3, object p4)
}
// Bogus property: getter and setter with too many parameters.
.method public instance object get_U(object g1, object g2) { ldnull ret }
.method public instance void set_U(object s1, object s2, object s3) { ret }
.property object U(object p1)
{
.get instance object C::get_U(object p2, object P3)
.set instance void C::set_U(object p4, object p5, object t6)
}
// Bogus property: getter with too few parameters.
.method public instance object get_V() { ldnull ret }
.method public instance void set_V(object s1, object s2) { ret }
.property object V(object p1)
{
.get instance object C::get_V()
.set instance void C::set_V(object p4, object p5)
}
// Bogus property: setter with too few parameters.
.method public instance void set_W(object s1, object s2) { ret }
.property object W(object p1, object p2)
{
.set instance void C::set_W(object p3, object p4)
}
// Bogus property: getter and setter with too few parameters.
.method public instance object get_X(object g1) { ldnull ret }
.method public instance void set_X(object s1, object s2) { ret }
.property object X(object p1, object p2)
{
.get instance object C::get_X(object P3)
.set instance void C::set_X(object p4, object p5)
}
}
]]>
Dim source =
<compilation>
<file name="a.vb">
Module M
Sub M(c As C)
Dim value = c.P()
c.P() = value
value = c.Q()
c.R() = value
c.S() = value
value = c.S(value)
c.T() = value
value = c.U()
c.U() = value
value = c.V()
c.V() = value
c.W() = value
value = c.X()
c.X() = value
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL)
Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C")
CheckParameterNames(type.GetMember(Of PropertySymbol)("P"), "Param")
CheckParameterNames(type.GetMember(Of PropertySymbol)("Q"), "g1")
CheckParameterNames(type.GetMember(Of PropertySymbol)("R"), "s1", "s2")
CheckParameterNames(type.GetMember(Of PropertySymbol)("S"), "Param")
CheckParameterNames(type.GetMember(Of PropertySymbol)("T"), "s1")
CheckParameterNames(type.GetMember(Of PropertySymbol)("U"), "Param")
CheckParameterNames(type.GetMember(Of PropertySymbol)("V"), "s1")
CheckParameterNames(type.GetMember(Of PropertySymbol)("W"), "s1", "s2")
CheckParameterNames(type.GetMember(Of PropertySymbol)("X"), "Param", "s2")
' TODO: There are two issues (differences from Dev10) with the following:
' 1) We're currently using the property parameter name rather than the
' accessor parameter name in "Argument not specified for parameter '...'".
' 2) Not all the bogus properties are supported.
#If False Then
CompilationUtils.AssertTheseErrors(compilation,
<expected>
BC30455: Argument not specified for parameter 'g1' of 'Public Property P(g1 As Object) As Object'.
Dim value = c.P()
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public Property P(g1 As Object) As Object'.
c.P() = value
~~~~~
BC30455: Argument not specified for parameter 'g1' of 'Public ReadOnly Property Q(g1 As Object) As Object'.
value = c.Q()
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property R(s1 As Object) As Object'.
c.R() = value
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public Property S(g1 As Object) As Object'.
c.S() = value
~~~~~
BC30455: Argument not specified for parameter 'g2' of 'Public Property S(g1 As Object) As Object'.
value = c.S(value)
~~~~~~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property T(s1 As Object) As Object'.
c.T() = value
~~~~~
BC30455: Argument not specified for parameter 's2' of 'Public WriteOnly Property T(s1 As Object) As Object'.
c.T() = value
~~~~~
BC30455: Argument not specified for parameter 'g1' of 'Public Property U(g1 As Object) As Object'.
value = c.U()
~~~~~
BC30455: Argument not specified for parameter 'g2' of 'Public Property U(g1 As Object) As Object'.
value = c.U()
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public Property U(g1 As Object) As Object'.
c.U() = value
~~~~~
BC30455: Argument not specified for parameter 's2' of 'Public Property U(g1 As Object) As Object'.
c.U() = value
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public Property V(Param As Object) As Object'.
c.V() = value
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public WriteOnly Property W(s1 As Object, s2 As Object) As Object'.
c.W() = value
~~~~~
BC30455: Argument not specified for parameter 'g1' of 'Public Property X(g1 As Object, Param As Object) As Object'.
value = c.X()
~~~~~
BC30455: Argument not specified for parameter 's1' of 'Public Property X(g1 As Object, Param As Object) As Object'.
c.X() = value
~~~~~
</expected>)
#End If
End Sub
Private Shared Sub CheckParameterNames([property] As PropertySymbol, ParamArray names() As String)
Dim parameters = [property].Parameters
Assert.Equal(parameters.Length, names.Length)
For i = 0 To names.Length - 1
Assert.Equal(parameters(i).Name, names(i))
Next
End Sub
' Should be possible to invoke a default property with no
' parameters, even though the property declaration is an error.
<Fact>
Public Sub DefaultParameterlessProperty()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="a.vb">
Class C
Default ReadOnly Property P()
Get
Return Nothing
End Get
End Property
Shared Sub M(ByVal x As C)
N(x.P()) ' No error
N(x()) ' No error
End Sub
Shared Sub N(ByVal o)
End Sub
End Class
</file>
</compilation>)
Dim expectedErrors = <errors>
BC31048: Properties with no required parameters cannot be declared 'Default'.
Default ReadOnly Property P()
~
</errors>
CompilationUtils.AssertTheseDeclarationDiagnostics(compilation, expectedErrors)
End Sub
''' <summary>
''' If the default property is parameterless (supported for
''' types from metadata), bind the argument list to the
''' default property of the return type instead.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType01()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Reflection
Public Class A
Default ReadOnly Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
End Class
<DefaultMember("Q")>
Public Class B
ReadOnly Property Q As A
Get
Return Nothing
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
compilation1.AssertNoErrors()
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As B)
Dim value As Object
value = o()(Nothing)
value = o(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
' DefaultMember attribute from source should be ignored.
Dim reference1a = New VisualBasicCompilationReference(compilation1)
Dim compilation2a = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1a})
compilation2a.AssertTheseDiagnostics(
<expected>
BC30367: Class 'B' cannot be indexed because it has no default property.
value = o()(Nothing)
~
BC30367: Class 'B' cannot be indexed because it has no default property.
value = o(Nothing)
~
</expected>)
' DefaultMember attribute from metadata should be used.
Dim reference1b = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2b = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1b})
compilation2b.AssertNoErrors()
End Sub
''' <summary>
''' WriteOnly default parameterless property.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType02()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Reflection
Public Class A
Default ReadOnly Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
End Class
<DefaultMember("Q")>
Public Class B
WriteOnly Property Q As A
Set
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
compilation1.AssertNoErrors()
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As B)
Dim value As Object
value = o()(Nothing)
value = o(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(
<expected>
BC30524: Property 'Q' is 'WriteOnly'.
value = o()(Nothing)
~~~
BC30524: Property 'Q' is 'WriteOnly'.
value = o(Nothing)
~
</expected>)
End Sub
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType03()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Reflection
Public Class A
End Class
<DefaultMember("Q")>
Public Class B
ReadOnly Property Q As A
Get
Return Nothing
End Get
End Property
End Class
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
compilation1.AssertNoErrors()
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As B)
Dim value As Object
value = o()
value = o(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(
<expected>
BC32016: 'Public ReadOnly Default Property Q As A' has no parameters and its return type cannot be indexed.
value = o(Nothing)
~
</expected>)
End Sub
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessDefaultPropertyReturnType04()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Imports System.Reflection
Public Class A
Default WriteOnly Property P(o As Object) As Object
Set(value As Object)
End Set
End Property
End Class
' Parameterless default member property.
<DefaultMember("P1")>
Public Class B1
ReadOnly Property P1 As A
Get
Return Nothing
End Get
End Property
End Class
' Default member property with ParamArray.
<DefaultMember("P2")>
Public Class B2
ReadOnly Property P2(ParamArray args As Object()) As A
Get
Return Nothing
End Get
End Property
End Class
' Default member property with Optional argument.
<DefaultMember("P3")>
Public Class B3
ReadOnly Property P3(Optional arg As Object = Nothing) As A
Get
Return Nothing
End Get
End Property
End Class
' Parameterless default member property with overload.
<DefaultMember("P4")>
Public Class B4
Overloads ReadOnly Property P4 As A
Get
Return Nothing
End Get
End Property
Overloads ReadOnly Property P4(arg As Object) As A
Get
Return Nothing
End Get
End Property
End Class
' Parameterless default member function.
<DefaultMember("F")>
Public Class B5
Function F() As A
Return Nothing
End Function
End Class
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
compilation1.AssertNoErrors()
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(_1 As B1, _2 As B2, _3 As B3, _4 As B4, _5 As B5)
_1(Nothing) = Nothing
_2(Nothing) = Nothing
_3(Nothing) = Nothing
_4(Nothing) = Nothing
_5(Nothing) = Nothing
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(
<expected>
BC30526: Property 'P2' is 'ReadOnly'.
_2(Nothing) = Nothing
~~~~~~~~~~~~~~~~~~~~~
BC30526: Property 'P3' is 'ReadOnly'.
_3(Nothing) = Nothing
~~~~~~~~~~~~~~~~~~~~~
BC30526: Property 'P4' is 'ReadOnly'.
_4(Nothing) = Nothing
~~~~~~~~~~~~~~~~~~~~~
BC30367: Class 'B5' cannot be indexed because it has no default property.
_5(Nothing) = Nothing
~~
</expected>)
Dim source3 =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(_1 As B1, _2 As B2, _3 As B3, _4 As B4)
Dim value As Object = Nothing
_1(Nothing) = value
value = _2(Nothing)
value = _3(Nothing)
value = _4(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation3 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {reference1})
compilation3.AssertNoErrors()
Dim compilationVerifier = CompileAndVerify(compilation3)
compilationVerifier.VerifyIL("M.M(B1, B2, B3, B4)",
<![CDATA[
{
// Code size 45 (0x2d)
.maxstack 3
.locals init (Object V_0) //value
IL_0000: ldnull
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: callvirt "Function B1.get_P1() As A"
IL_0008: ldnull
IL_0009: ldloc.0
IL_000a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000f: callvirt "Sub A.set_P(Object, Object)"
IL_0014: ldarg.1
IL_0015: ldnull
IL_0016: callvirt "Function B2.get_P2(ParamArray Object()) As A"
IL_001b: stloc.0
IL_001c: ldarg.2
IL_001d: ldnull
IL_001e: callvirt "Function B3.get_P3(Object) As A"
IL_0023: stloc.0
IL_0024: ldarg.3
IL_0025: ldnull
IL_0026: callvirt "Function B4.get_P4(Object) As A"
IL_002b: stloc.0
IL_002c: ret
}
]]>)
End Sub
''' <summary>
''' Default member from ElementAtOrDefault.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessElementAtOrDefault01()
Dim source =
<compilation>
<file name="c.vb"><) As C1
Return Nothing
End Function
Public Function ElementAtOrDefault() As A
Return Nothing
End Function
End Class
' Default member returns Array.
Class C2
Public Function [Select](f As System.Func(Of Object, Object)) As C2
Return Nothing
End Function
Public Function ElementAtOrDefault() As Object()
Return Nothing
End Function
End Class
' Default member returns Delegate.
Class C3
Public Function [Select](f As System.Func(Of Object, Object)) As C3
Return Nothing
End Function
Public Function ElementAtOrDefault() As D
Return Nothing
End Function
End Class
Module M
Sub M(_1 As C1, _2 As C2, _3 As C3)
Dim value As Object
value = _1()(Nothing)
value = _1(Nothing)
value = _1()()
value = _2()(Nothing)
value = _2(Nothing)
value = _2()()
value = _3()(Nothing)
value = _3(Nothing)
value = _3()()
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'o' of 'Public ReadOnly Default Property P(o As Object) As Object'.
value = _1()()
~~~~
BC30105: Number of indices is less than the number of dimensions of the indexed array.
value = _2()()
~~
BC30455: Argument not specified for parameter 'o' of 'D'.
value = _3()()
~~~~
</expected>)
End Sub
''' <summary>
''' Default member from ElementAtOrDefault.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessElementAtOrDefault02()
Dim source =
<compilation>
<file name="c.vb"><) As B
Return Nothing
End Function
Public Function ElementAtOrDefault() As A
Return Nothing
End Function
End Class
Class C
Public Function [Select](f As System.Func(Of Object, Object)) As C
Return Nothing
End Function
Public Function ElementAtOrDefault() As B
Return Nothing
End Function
End Class
Class D
Public Function [Select](f As System.Func(Of Object, Object)) As D
Return Nothing
End Function
Public Function ElementAtOrDefault() As C
Return Nothing
End Function
End Class
Module M
Sub M(o As D)
Dim value As Object
value = o()()()(Nothing)
value = o()()(Nothing)
value = o()(Nothing)
value = o(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertTheseDiagnostics(
<expected>
BC30057: Too many arguments to 'Public Function ElementAtOrDefault() As A'.
value = o()(Nothing)
~~~~~~~
BC30057: Too many arguments to 'Public Function ElementAtOrDefault() As B'.
value = o(Nothing)
~~~~~~~
</expected>)
End Sub
''' <summary>
''' ElementAtOrDefault returning System.Array.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<WorkItem(575547, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/575547")>
<CompilerTrait(CompilerFeature.IOperation)>
<Fact()>
Public Sub DefaultPropertyOfParameterlessElementAtOrDefault03()
' Option Strict On
Dim source1 =
<compilation>
<file name="c.vb"><) As C
Return Nothing
End Function
Public Function ElementAtOrDefault() As System.Array
Return Nothing
End Function
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o()(1)
value = o(2)
o()(3) = value
o(4) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40AndVBRuntime(source1)
compilation1.AssertTheseDiagnostics(
<expected>
BC30574: Option Strict On disallows late binding.
value = o()(1)
~~~
BC30574: Option Strict On disallows late binding.
value = o(2)
~
BC30574: Option Strict On disallows late binding.
o()(3) = value
~~~
BC30574: Option Strict On disallows late binding.
o(4) = value
~
</expected>)
Dim tree = compilation1.SyntaxTrees.Single()
Dim node = tree.GetRoot().DescendantNodes().OfType(Of InvocationExpressionSyntax)().ElementAt(2)
Assert.Equal("o(2)", node.ToString())
compilation1.VerifyOperationTree(node, expectedOperationTree:=
<![CDATA[
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'o(2)')
Children(2):
IInvocationOperation ( Function C.ElementAtOrDefault() As System.Array) (OperationKind.Invocation, Type: System.Array, IsInvalid, IsImplicit) (Syntax: 'o')
Instance Receiver:
IParameterReferenceOperation: o (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'o')
Arguments(0)
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value)
' Option Strict Off
Dim source2 =
<compilation>
<file name="c.vb"><) As C
Return Nothing
End Function
Public Function ElementAtOrDefault() As System.Array
Return Nothing
End Function
End Class
Module M
Sub M(o As C)
Dim value As Object
value = o()(1)
value = o(2)
o()(3) = value
o(4) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntime(source2)
compilation2.AssertNoErrors()
End Sub
''' <summary>
''' ElementAtOrDefault property. (ElementAtOrDefault field
''' not supported - see #576814.)
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessElementAtOrDefault04()
Dim source =
<compilation>
<file name="c.vb"><) As A
Return Nothing
End Function
Public ReadOnly Property ElementAtOrDefault As Integer()
Get
Return Nothing
End Get
End Property
End Class
Module M
Sub M(_a As A)
Dim value As Integer
value = _a(1)
_a(2) = value
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertNoErrors()
Dim compilationVerifier = CompileAndVerify(compilation)
compilationVerifier.VerifyIL("M.M(A)",
<![CDATA[
{
// Code size 19 (0x13)
.maxstack 3
.locals init (Integer V_0) //value
IL_0000: ldarg.0
IL_0001: callvirt "Function A.get_ElementAtOrDefault() As Integer()"
IL_0006: ldc.i4.1
IL_0007: ldelem.i4
IL_0008: stloc.0
IL_0009: ldarg.0
IL_000a: callvirt "Function A.get_ElementAtOrDefault() As Integer()"
IL_000f: ldc.i4.2
IL_0010: ldloc.0
IL_0011: stelem.i4
IL_0012: ret
}
]]>)
End Sub
''' <summary>
''' Parentheses required for call to delegate.
''' </summary>
<WorkItem(531372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531372")>
<Fact()>
Public Sub DefaultPropertyOfParameterlessDelegate()
Dim source =
<compilation>
<file name="c.vb"><![CDATA[
Delegate Function D() As C
Class C
Default ReadOnly Property P(o As Object) As Object
Get
Return Nothing
End Get
End Property
End Class
Module M
Sub M(o As D)
Dim value As Object
value = o()(Nothing)
value = o(Nothing)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source)
compilation.AssertTheseDiagnostics(
<expected>
BC30057: Too many arguments to 'D'.
value = o(Nothing)
~~~~~~~
</expected>)
End Sub
<WorkItem(578180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578180")>
<Fact()>
Public Sub DefaultPropertyOfInheritedConstrainedTypeParameter()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System.Reflection
<DefaultMember("P")>
Public Interface I
ReadOnly Property P As Object
End Interface
<DefaultMember("P")>
Public Class C
Public ReadOnly Property P As Object
Get
Return Nothing
End Get
End Property
End Class
<DefaultMember("P")>
Public Structure S
Public ReadOnly Property P As Object
Get
Return Nothing
End Get
End Property
End Structure
<DefaultMember("M")>
Public Enum E
M
End Enum
Public Delegate Function D() As Object
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
compilation1.AssertNoErrors()
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
MustInherit Class A(Of T)
MustOverride Function F(Of U As T)(o As U) As Object
End Class
' Interface with default parameterless property.
Class B1
Inherits A(Of I)
Public Overrides Function F(Of T As I)(o1 As T) As Object
Return o1()
End Function
End Class
' Class with default parameterless property.
Class B2
Inherits A(Of C)
Public Overrides Function F(Of T As C)(o2 As T) As Object
Return o2()
End Function
End Class
' Structure with default parameterless property.
Class B3
Inherits A(Of S)
Public Overrides Function F(Of T As S)(o3 As T) As Object
Return o3()
End Function
End Class
' Enum with default member.
Class B4
Inherits A(Of E)
Public Overrides Function F(Of T As E)(o4 As T) As Object
Return o4()
End Function
End Class
' Delegate.
Class B5
Inherits A(Of D)
Public Overrides Function F(Of T As D)(o5 As T) As Object
Return o5()
End Function
End Class
' Array.
Class B6
Inherits A(Of C())
Public Overrides Function F(Of T As C())(o6 As T) As Object
Return o6()
End Function
End Class
' Type parameter.
Class B7(Of T)
Inherits A(Of T)
Public Overrides Function F(Of U As T)(o7 As U) As Object
Return o7()
End Function
End Class
]]>
</file>
</compilation>
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim compilation2 = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(
<expected>
BC30547: 'T' cannot be indexed because it has no default property.
Return o3()
~~
BC30547: 'T' cannot be indexed because it has no default property.
Return o4()
~~
BC30547: 'T' cannot be indexed because it has no default property.
Return o5()
~~
BC30547: 'T' cannot be indexed because it has no default property.
Return o6()
~~
BC30547: 'U' cannot be indexed because it has no default property.
Return o7()
~~
</expected>)
End Sub
<WorkItem(539951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539951")>
<Fact>
Public Sub ImportedParameterlessDefaultProperties()
Dim customIL = <![CDATA[
.class public auto ansi beforefieldinit CSDefaultMembers
extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 05 49 74 65 6D 73 00 00 ) // ...Items..
.field private int32 '<Items>k__BackingField'
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
.method public hidebysig specialname instance int32
get_Items() cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 11 (0xb)
.maxstack 1
.locals init (int32 V_0)
IL_0000: ldarg.0
IL_0001: ldfld int32 CSDefaultMembers::'<Items>k__BackingField'
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
} // end of method CSDefaultMembers::get_Items
.method public hidebysig specialname instance void
set_Items(int32 'value') cil managed
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 )
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld int32 CSDefaultMembers::'<Items>k__BackingField'
IL_0007: ret
} // end of method CSDefaultMembers::set_Items
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method CSDefaultMembers::.ctor
.property instance int32 Items()
{
.get instance int32 CSDefaultMembers::get_Items()
.set instance void CSDefaultMembers::set_Items(int32)
} // end of property CSDefaultMembers::Items
} // end of class CSDefaultMembers]]>
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
Dim obj As CSDefaultMembers = New CSDefaultMembers()
obj() = 9
Dim x = obj()
System.Console.WriteLine(x)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(source, customIL.Value, TestOptions.ReleaseExe, includeVbRuntime:=True)
CompilationUtils.AssertNoErrors(compilation)
CompileAndVerify(compilation, expectedOutput:="9")
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub DefaultPropertyInFunctionReturn()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Private Obj As VBDefaultMembers
Sub Main()
Obj = New VBDefaultMembers()
Obj(1) = 4
System.Console.WriteLine(Goo(1))
Dim dd As DefaultDefaultMember = New DefaultDefaultMember
dd.Item = Obj
System.Console.WriteLine(dd.Item(1))
' bind-position
End Sub
Function Goo() As VBDefaultMembers
Return Obj
End Function
Function Bar() As Integer()
Return Nothing
End Function
End Module
Public Class DefaultDefaultMember
Property Item As VBDefaultMembers
End Class
Public Class VBDefaultMembers
'Property Items As Integer
Public _items As Integer() = New Integer(4) {}
Default Public Property Items(index As Integer) As Integer
Get
Return _items(index)
End Get
Set(value As Integer)
_items(index) = value
End Set
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
Dim position = (source...<file>.Single().Value.IndexOf("' bind-position", StringComparison.Ordinal))
Dim bindings = compilation.GetSemanticModel(CompilationUtils.GetTree(compilation, "a.vb"))
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Goo().Items(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Goo.Items(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Goo()(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Goo(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("dd.Item(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, bindings.GetSpeculativeSemanticInfoSummary(position, SyntaxFactory.ParseExpression("Bar(1)"), SpeculativeBindingOption.BindAsExpression).Type.SpecialType)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[
4
4
]]>)
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub EmptyArgumentListWithNoIndexerOrDefaultProperty()
Dim source =
<compilation>
<file name="a.vb">
Class C2
Private Sub M()
Dim x = A(6)
Dim y = B(6)
Dim z = C(6)
Call A(6)
Call B(6)
Call C(6)
End Sub
Private Function A() As String
Return "Hello"
End Function
Private Function B() As Integer()
Return Nothing
End Function
Private Function C() As Integer
Return Nothing
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32016: 'Private Function C() As Integer' has no parameters and its return type cannot be indexed.
Dim z = C(6)
~
BC30057: Too many arguments to 'Private Function A() As String'.
Call A(6)
~
BC30057: Too many arguments to 'Private Function B() As Integer()'.
Call B(6)
~
BC30057: Too many arguments to 'Private Function C() As Integer'.
Call C(6)
~
</expected>)
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub WrongArityWithFunctionsOfZeroParameters()
Dim source =
<compilation>
<file name="a.vb">
Class C1
Public Function Goo() As Integer()
Return Nothing
End Function
Public Sub TST()
Dim a As Integer = Goo(Of Integer)(1)
End Sub
End Class
Class C2
Public Function Goo(Of T)() As Integer()
Return Nothing
End Function
Public Sub TST()
Dim a As Integer = Goo(1)
Call Goo(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC32045: 'Public Function Goo() As Integer()' has no type parameters and so cannot have type arguments.
Dim a As Integer = Goo(Of Integer)(1)
~~~~~~~~~~~~
BC30057: Too many arguments to 'Public Function Goo(Of T)() As Integer()'.
Dim a As Integer = Goo(1)
~
BC30057: Too many arguments to 'Public Function Goo(Of T)() As Integer()'.
Call Goo(1)
~
</expected>)
' WARNING!!! Dev10 generates:
'
' BC32045: 'Public Function Goo() As Integer()' has no type parameters and so cannot have type arguments.
' BC32050: BC32050: Type parameter 'T' for 'Public Function Goo(Of T)() As Integer()' cannot be inferred.
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub PropertyReturningDelegate()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public ReadOnly Property Goo As Func(Of String, Integer)
Get
Return AddressOf Impl
End Get
End Property
Private Function Impl(str As String) As Integer
Return 0
End Function
Public Sub TST()
Dim a As Integer = Goo()("abc")
Dim b As Integer = Goo("abc")
Dim c = Goo()
Dim d = Goo
Call Goo()("abc")
Call Goo("abc")
Call Goo()
Call Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public ReadOnly Property Goo As Func(Of String, Integer)'.
Call Goo("abc")
~~~~~
BC30545: Property access must assign to the property or use its value.
Call Goo()
~~~~~
BC30545: Property access must assign to the property or use its value.
Call Goo
~~~
</expected>)
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub FunctionWithZeroParametersReturningDelegate()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class C
Public Function Goo() As Func(Of String, Integer)
Return AddressOf Impl
End Function
Private Function Impl(str As String) As Integer
Return 0
End Function
Public Sub TST()
Dim a As Integer = Goo()("abc")
Dim b As Integer = Goo("abc")
Dim c = Goo()
Dim d = Goo()
Goo()("abc")
Goo("abc")
Goo()
Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Function Goo() As Func(Of String, Integer)'.
Goo("abc")
~~~~~
</expected>)
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub EmptyArgumentListWithFunctionAndSub()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Public Function Goo() As Integer()
Dim arr As Integer() = New Integer(4) {}
arr(2) = 234
Return arr
End Function
Public Sub Goo(i As Integer)
System.Console.WriteLine(i)
End Sub
Public Sub Main()
Dim a As Integer = Goo(2)
Call Goo(a)
End Sub
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="234")
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub FunctionsWithDifferentArity_0()
Dim source =
<compilation>
<file name="a.vb">
Class CLS
Public Overloads Function Goo(Of T)() As Integer()
Return Nothing
End Function
Public Overloads Function Goo() As Integer()
Return Nothing
End Function
Public Sub TST()
Dim a As Integer = Goo(Of Integer)(1)
Dim b As Integer = Goo(1)
Call Goo(Of Integer)(1)
Call Goo(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Overloads Function Goo(Of Integer)() As Integer()'.
Call Goo(Of Integer)(1)
~
BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
Call Goo(1)
~~~
</expected>)
' WARNING!!! Dev10 generates:
'
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub FunctionsWithDifferentArity_1()
Dim source =
<compilation>
<file name="a.vb">
Class CBase
Public Function Goo(Of T)() As Integer()
Return Nothing
End Function
End Class
Class CDerived
Inherits CBase
Public Overloads Function Goo() As Integer()
Return Nothing
End Function
Public Sub TST()
Dim a As Integer = Goo(Of Integer)(1)
Dim b As Integer = Goo(1)
Call Goo(Of Integer)(1)
Call Goo(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30057: Too many arguments to 'Public Function Goo(Of Integer)() As Integer()'.
Call Goo(Of Integer)(1)
~
BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
Call Goo(1)
~~~
</expected>)
' WARNING!!! Dev10 generates:
'
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub FunctionsWithDifferentArity_2()
Dim source =
<compilation>
<file name="a.vb">
Class CBase
Public Function Goo(Of T)() As Integer()
Return Nothing
End Function
End Class
Class CDerived
Inherits CBase
Public Overloads Function Goo(Of X, Y)() As Integer()
Return Nothing
End Function
Public Sub TST()
Dim a As Integer = Goo(Of Integer)(1)
Dim b As Integer = Goo(1)
Call Goo(Of Integer)(1)
Call Goo(1)
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
Dim b As Integer = Goo(1)
~~~
BC30057: Too many arguments to 'Public Function Goo(Of Integer)() As Integer()'.
Call Goo(Of Integer)(1)
~
BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
Call Goo(1)
~~~
</expected>)
' WARNING!!! Dev10 generates:
'
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC32050: Type parameter 'X' for 'Public Overloads Function Goo(Of X, Y)() As Integer()' cannot be inferred.
' BC32050: Type parameter 'Y' for 'Public Overloads Function Goo(Of X, Y)() As Integer()' cannot be inferred.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
' BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub PropertiesWithInheritanceAndParentheses()
Dim source =
<compilation>
<file name="a.vb">
Interface IBase
Property Goo As Integer()
End Interface
Class CBase
Public Property Goo As Integer()
End Class
Class CDerived
Inherits CBase
Implements IBase
Public Overloads Property Goo2 As Integer() Implements IBase.Goo
Public Overloads Property Goo As Integer()
Public Sub TST()
Dim a As Integer = Goo()(1)
Dim b As Integer = Goo(1)
Dim c As Integer() = Goo()
Dim d As Integer() = Goo
Call Goo()(1)
Call Goo(1)
Call Goo()
Call Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30454: Expression is not a method.
Call Goo()(1)
~~~~~
BC30516: Overload resolution failed because no accessible 'Goo' accepts this number of arguments.
Call Goo(1)
~~~
BC30545: Property access must assign to the property or use its value.
Call Goo()
~~~~~
BC30545: Property access must assign to the property or use its value.
Call Goo
~~~
</expected>)
' WARNING!!! Dev10 generates:
'
' BC30454: Expression is not a method.
' BC30545: Property access must assign to the property or use its value.
' BC30545: Property access must assign to the property or use its value.
' BC30545: Property access must assign to the property or use its value.
End Sub
<WorkItem(539957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539957")>
<Fact>
Public Sub WriteOnlyPropertiesWithInheritanceAndParentheses()
Dim source =
<compilation>
<file name="a.vb">
Interface IBase
WriteOnly Property Goo As Integer()
End Interface
Class CBase
Public WriteOnly Property Goo As Integer()
Set(value As Integer())
End Set
End Property
End Class
Class CDerived
Inherits CBase
Implements IBase
Public WriteOnly Property Goo2 As Integer() Implements IBase.Goo
Set(value As Integer())
End Set
End Property
Public Overloads WriteOnly Property Goo As Integer()
Set(value As Integer())
End Set
End Property
Public Sub TST()
Dim a As Integer = Goo()(1)
Dim b As Integer = Goo(1)
Dim c As Integer() = Goo()
Dim d As Integer() = Goo
End Sub
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(source)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30524: Property 'Goo' is 'WriteOnly'.
Dim a As Integer = Goo()(1)
~~~~~
BC30524: Property 'Goo' is 'WriteOnly'.
Dim b As Integer = Goo(1)
~~~
BC30524: Property 'Goo' is 'WriteOnly'.
Dim c As Integer() = Goo()
~~~~~
BC30524: Property 'Goo' is 'WriteOnly'.
Dim d As Integer() = Goo
~~~
</expected>)
End Sub
<WorkItem(539903, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539903")>
<Fact>
Public Sub DefaultPropertyBangOperator()
Dim source =
<compilation>
<file name="a.vb">
<![CDATA[
Module Program
Sub Main()
Dim bang = New TestClassX()
bang!Hello = "World"
System.Console.WriteLine(bang!Hello)
End Sub
End Module
Class TestClassX
Public _items() As String = New String(100) {}
Default Property Items(key As String) As String
Get
Return _items(key.Length)
End Get
Set(value As String)
_items(key.Length) = value
End Set
End Property
End Class
]]>
</file>
</compilation>
CompileAndVerify(source, expectedOutput:="World")
End Sub
#End Region
#Region "Typeless properties"
<Fact>
Public Sub TypelessAndImplicitlyTypeProperties()
Dim source =
<compilation>
<file name="a.vb"><![CDATA[
Class TestClass
Property Typeless
Property StringType$
Property IntegerType%
Property LongType&
Property DecimalType@
Property SingleType!
Property DoubleType#
End Class
]]>
</file>
</compilation>
Dim validator = Sub([module] As ModuleSymbol)
Dim testClassType = [module].GlobalNamespace.GetTypeMembers("TestClass").Single()
Dim propertiesDictionary = testClassType.GetMembers().OfType(Of PropertySymbol).ToDictionary(Function(prop) prop.Name, Function(prop) prop)
Assert.Equal(SpecialType.System_Object, propertiesDictionary!Typeless.Type.SpecialType)
Assert.Equal(SpecialType.System_String, propertiesDictionary!StringType.Type.SpecialType)
Assert.Equal(SpecialType.System_Int32, propertiesDictionary!IntegerType.Type.SpecialType)
Assert.Equal(SpecialType.System_Int64, propertiesDictionary!LongType.Type.SpecialType)
Assert.Equal(SpecialType.System_Decimal, propertiesDictionary!DecimalType.Type.SpecialType)
Assert.Equal(SpecialType.System_Single, propertiesDictionary!SingleType.Type.SpecialType)
Assert.Equal(SpecialType.System_Double, propertiesDictionary!DoubleType.Type.SpecialType)
End Sub
CompileAndVerify(source, sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
#End Region
#Region "Properties calls"
Private ReadOnly _propertiesCallBaseSource As XElement =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
Dim obj As TestClass1 = New TestClass1()
obj.P1 = New TestClass2()
obj.P2 = New TestClass2()
obj.P1.id = 1
obj.P2.id = 2
<more_code/>
End Sub
Sub ByRefSwap(ByRef myObj1 As TestClass2, ByRef myObj2 As TestClass2)
Dim tempObj As TestClass2 = myObj1
myObj1 = myObj2
myObj2 = tempObj
End Sub
Sub ByValSwap(myObj1 As TestClass2, myObj2 As TestClass2)
Dim tempObj As TestClass2 = myObj1
myObj1 = myObj2
myObj2 = tempObj
End Sub
End Module
Public Class TestClass2
Property id As Integer
End Class
Public Class TestClass1
Property P1 As TestClass2
Property P2 As TestClass2
End Class
</file>
</compilation>
<Fact>
Public Sub PassPropertyByValue()
_propertiesCallBaseSource.Element("file").SetElementValue("more_code",
<![CDATA[
ByValSwap(obj.P1, obj.P2) 'now o.P1.id = 1 and o.P2.id = 2
System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value)
CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="1,2")
End Sub
<Fact>
Public Sub PassPropertyByRef()
_propertiesCallBaseSource.Element("file").SetElementValue("more_code",
<![CDATA[
ByRefSwap(obj.P1, obj.P2) 'now o.P1.id = 2 and o.P2.id = 1
System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value)
CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="2,1")
End Sub
<Fact>
Public Sub PassPropertyByRefWithByValueOverride()
_propertiesCallBaseSource.Element("file").SetElementValue("more_code",
<![CDATA[
ByRefSwap((obj.P1), obj.P2) 'now o.P1.id = 1 and o.P2.id = 2
System.Console.WriteLine(String.Join(",", obj.P1.id, obj.P2.id))]]>.Value)
CompileAndVerify(_propertiesCallBaseSource, expectedOutput:="1,1")
End Sub
#End Region
#Region "Properties member access"
<WorkItem(539962, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539962")>
<Fact>
Public Sub PropertiesAccess()
Dim source =
<compilation>
<file name="a.vb">
Public Class TestClass
Public Property P1 As Integer
Get
Return 0
End Get
Set
End Set
End Property
Friend ReadOnly Property P2 As Integer
Get
Return 0
End Get
End Property
Protected Friend ReadOnly Property P3 As Integer
Get
Return 0
End Get
End Property
Protected ReadOnly Property P4 As Integer
Get
Return 0
End Get
End Property
Private WriteOnly Property P5 As Integer
Set
End Set
End Property
ReadOnly Property P6 As Integer
Get
Return 0
End Get
End Property
Public Property P7 As Integer
Private Get
Return 0
End Get
Set
End Set
End Property
Friend Property P8 As Integer
Get
Return 0
End Get
Private Set
End Set
End Property
Protected Property P9 As Integer
Get
Return 0
End Get
Private Set
End Set
End Property
Protected Friend Property P10 As Integer
Protected Get
Return 0
End Get
Set
End Set
End Property
Protected Friend Property P11 As Integer
Friend Get
Return 0
End Get
Set
End Set
End Property
End Class
</file>
</compilation>
Dim validator = Function(isFromSource As Boolean) _
Sub([module] As ModuleSymbol)
Dim type = [module].GlobalNamespace.GetTypeMembers("TestClass").Single()
Dim members = type.GetMembers()
' Ensure member names are unique.
Dim memberNames = members.[Select](Function(member) member.Name).Distinct().ToList()
Assert.Equal(memberNames.Count, members.Length)
'Dim constructor = members.FirstOrDefault(Function(member) member.Name = ".ctor")
'Assert.NotNull(constructor)
Dim p1 = type.GetMember(Of PropertySymbol)("P1")
Dim p2 = type.GetMember(Of PropertySymbol)("P2")
Dim p3 = type.GetMember(Of PropertySymbol)("P3")
Dim p4 = type.GetMember(Of PropertySymbol)("P4")
Dim p7 = type.GetMember(Of PropertySymbol)("P7")
Dim p8 = type.GetMember(Of PropertySymbol)("P8")
Dim p9 = type.GetMember(Of PropertySymbol)("P9")
Dim p10 = type.GetMember(Of PropertySymbol)("P10")
Dim p11 = type.GetMember(Of PropertySymbol)("P11")
Dim privateOrNotApplicable = If(isFromSource, Accessibility.Private, Accessibility.NotApplicable)
CheckPropertyAccessibility(p1, Accessibility.Public, Accessibility.Public, Accessibility.Public)
CheckPropertyAccessibility(p2, Accessibility.Friend, Accessibility.Friend, Accessibility.NotApplicable)
CheckPropertyAccessibility(p3, Accessibility.ProtectedOrFriend, Accessibility.ProtectedOrFriend, Accessibility.NotApplicable)
CheckPropertyAccessibility(p4, Accessibility.Protected, Accessibility.Protected, Accessibility.NotApplicable)
CheckPropertyAccessibility(p10, Accessibility.ProtectedOrFriend, Accessibility.Protected, Accessibility.ProtectedOrFriend)
CheckPropertyAccessibility(p11, Accessibility.ProtectedOrFriend, Accessibility.Friend, Accessibility.ProtectedOrFriend)
If isFromSource Then
Dim p5 = type.GetMember(Of PropertySymbol)("P5")
Dim p6 = type.GetMember(Of PropertySymbol)("P6")
CheckPropertyAccessibility(p5, Accessibility.Private, Accessibility.NotApplicable, Accessibility.Private)
CheckPropertyAccessibility(p6, Accessibility.Public, Accessibility.Public, Accessibility.NotApplicable)
End If
'This checks a moved to last because they are affected by bug#
CheckPropertyAccessibility(p7, Accessibility.Public, privateOrNotApplicable, Accessibility.Public)
CheckPropertyAccessibility(p8, Accessibility.Friend, Accessibility.Friend, privateOrNotApplicable)
CheckPropertyAccessibility(p9, Accessibility.Protected, Accessibility.Protected, privateOrNotApplicable)
End Sub
CompileAndVerify(source, symbolValidator:=validator(False), sourceSymbolValidator:=validator(True), options:=TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal))
End Sub
#End Region
#Region "Ported C# test cases"
#Region "Symbols"
<Fact>
Public Sub Simple1()
Dim text = <compilation><file name="c.vb"><![CDATA[
Class A
Private MustOverride Property P() As Integer
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
Dim [global] = comp.GlobalNamespace
Dim a = [global].GetTypeMembers("A", 0).Single()
Dim p = TryCast(a.GetMembers("P").AsEnumerable().SingleOrDefault(), PropertySymbol)
End Sub
<Fact>
Public Sub EventEscapedIdentifier()
Dim text = <compilation><file name="c.vb"><![CDATA[
Delegate Sub [out]()
Class C1
Private Property [in] as out
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
Dim c1 As NamedTypeSymbol = DirectCast(comp.SourceModule.GlobalNamespace.GetMembers("C1").Single(), NamedTypeSymbol)
Dim ein As PropertySymbol = DirectCast(c1.GetMembers("in").Single(), PropertySymbol)
Assert.Equal("in", ein.Name)
Assert.Equal("Private Property [in] As out", ein.ToString())
Dim dout As NamedTypeSymbol = DirectCast(ein.Type, NamedTypeSymbol)
Assert.Equal("out", dout.Name)
Assert.Equal("out", dout.ToString())
End Sub
''' <summary>
''' Properties should refer to methods
''' in the type members collection.
''' </summary>
<Fact>
Public Sub MethodsAndAccessorsSame()
Dim sources = <compilation>
<file name="c.vb"><![CDATA[
Class A
Public Shared Property P
Public Property Q
Public Property R(arg)
Get
Return Nothing
End Get
Set(value)
End Set
End Property
End Class
Class B(Of T, U)
Public Shared Property P
Public Property Q
Public Property R(arg As U) As T
Get
Return Nothing
End Get
Set(value As T)
End Set
End Property
End Class
Class C
Inherits B(Of String, Integer)
End Class
]]></file>
</compilation>
Dim validator = Sub([module] As ModuleSymbol)
Dim type As NamedTypeSymbol
Dim accessor As MethodSymbol
Dim prop As PropertySymbol
' Non-generic type.
type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.Equal(type.TypeParameters.Length, 0)
Assert.Same(type.ConstructedFrom, type)
accessor = type.GetMember(Of MethodSymbol)("get_P")
VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor)
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P"))
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q"))
prop = type.GetMember(Of PropertySymbol)("R")
VerifyMethodsAndAccessorsSame(type, prop)
' Generic type.
type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("B")
Assert.Equal(type.TypeParameters.Length, 2)
Assert.Same(type.ConstructedFrom, type)
accessor = type.GetMember(Of MethodSymbol)("get_P")
VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor)
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P"))
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q"))
prop = type.GetMember(Of PropertySymbol)("R")
VerifyMethodsAndAccessorsSame(type, prop)
Assert.Equal(type.TypeArguments(0), prop.Type)
Assert.Equal(type.TypeArguments(1), prop.Parameters(0).Type)
' Generic type with parameter substitution.
type = [module].GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").BaseType
Assert.Equal(type.TypeParameters.Length, 2)
Assert.NotSame(type.ConstructedFrom, type)
accessor = type.GetMember(Of MethodSymbol)("get_P")
VerifyMethodAndAccessorSame(type, DirectCast(accessor.AssociatedSymbol, PropertySymbol), accessor)
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("P"))
VerifyMethodsAndAccessorsSame(type, type.GetMember(Of PropertySymbol)("Q"))
prop = type.GetMember(Of PropertySymbol)("R")
VerifyMethodsAndAccessorsSame(type, prop)
Assert.Equal(type.TypeArguments(0), prop.Type)
Assert.Equal(type.TypeArguments(1), prop.Parameters(0).Type)
End Sub
CompileAndVerify(sources, sourceSymbolValidator:=validator, symbolValidator:=validator)
End Sub
<Fact>
Public Sub NoAccessors()
Dim source =
<compilation>
<file name="a.vb">
Module Program
Sub Main()
End Sub
Sub M(i As NoAccessors)
i.Instance = NoAccessors.Static
End Sub
End Module
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source, {TestReferences.SymbolsTests.Properties}, TestOptions.ReleaseExe)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30456: 'Instance' is not a member of 'NoAccessors'.
i.Instance = NoAccessors.Static
~~~~~~~~~~
BC30456: 'Static' is not a member of 'NoAccessors'.
i.Instance = NoAccessors.Static
~~~~~~~~~~~~~~~~~~
</expected>)
Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("NoAccessors").Single(), PENamedTypeSymbol)
' Methods are available.
Assert.NotNull(type.GetMembers("StaticMethod").SingleOrDefault())
Assert.NotNull(type.GetMembers("InstanceMethod").SingleOrDefault())
Assert.Equal(2, type.GetMembers().OfType(Of MethodSymbol)().Count())
' Properties are not available.
Assert.Null(type.GetMembers("Static").SingleOrDefault())
Assert.Null(type.GetMembers("Instance").SingleOrDefault())
Assert.Equal(0, type.GetMembers().OfType(Of PropertySymbol)().Count())
End Sub
<Fact>
Public Sub FamilyAssembly()
Dim source =
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
System.Console.Write(Signatures.StaticGet())
End Sub
End Module
</file>
</compilation>
Dim compilation = CompileWithCustomPropertiesAssembly(source, TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.Internal))
Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("FamilyAssembly").Single(), PENamedTypeSymbol)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyGetAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.[Protected],
Accessibility.[Friend])
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.[Protected],
Accessibility.ProtectedOrFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.[Protected],
Accessibility.[Protected],
Accessibility.ProtectedAndFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("AssemblyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.[Friend],
Accessibility.ProtectedOrFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("AssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.[Friend],
Accessibility.[Friend],
Accessibility.ProtectedAndFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyOrAssemblyGetFamilyOrAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.ProtectedOrFriend,
Accessibility.ProtectedOrFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyOrAssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.ProtectedOrFriend,
Accessibility.ProtectedAndFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyAndAssemblyGetFamilyAndAssemblySetStatic").Single(), PEPropertySymbol),
Accessibility.ProtectedAndFriend,
Accessibility.ProtectedAndFriend,
Accessibility.ProtectedAndFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyAndAssemblyGetOnlyInstance").Single(), PEPropertySymbol),
Accessibility.ProtectedAndFriend,
Accessibility.ProtectedAndFriend,
Accessibility.NotApplicable)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyOrAssemblySetOnlyInstance").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.NotApplicable,
Accessibility.ProtectedOrFriend)
VerifyAccessibility(
DirectCast(type.GetMembers("FamilyAndAssemblyGetFamilyOrAssemblySetInstance").Single(), PEPropertySymbol),
Accessibility.ProtectedOrFriend,
Accessibility.ProtectedAndFriend,
Accessibility.ProtectedOrFriend)
End Sub
<Fact>
Public Sub PropertyAccessorDoesNotHideMethod()
Dim vbSource = <compilation><file name="c.vb">
Interface IA
Function get_Goo() As String
End Interface
Interface IB
Inherits IA
ReadOnly Property Goo() As Integer
End Interface
Class Program
Private Shared Sub Main()
Dim x As IB = Nothing
Dim s As String = x.get_Goo().ToLower()
End Sub
End Class
</file></compilation>
CompileAndVerify(vbSource).VerifyDiagnostics(
Diagnostic(ERRID.WRN_SynthMemberShadowsMember5, "Goo").WithArguments("property", "Goo", "get_Goo", "interface", "IA"))
End Sub
<Fact>
Public Sub PropertyAccessorDoesNotConflictWithMethod()
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Interface IA
Function get_Goo() As String
End Interface
Interface IB
ReadOnly Property Goo() As Integer
End Interface
Interface IC
Inherits IA
Inherits IB
End Interface
Class Program
Private Shared Sub Main()
Dim x As IC = Nothing
Dim s As String = x.get_Goo().ToLower()
End Sub
End Class
]]></file></compilation>
CompileAndVerify(vbSource)
End Sub
<Fact>
Public Sub PropertyAccessorCannotBeCalledAsMethod()
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Interface I
ReadOnly Property Goo() As Integer
End Interface
Class Program
Private Shared Sub Main()
Dim x As I = Nothing
Dim s As String = x.get_Goo()
End Sub
End Class
]]></file></compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(vbSource)
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "x.get_Goo").WithArguments("get_Goo", "I"))
Assert.False(compilation.Emit(IO.Stream.Null).Success)
End Sub
<Fact>
Public Sub CanReadInstancePropertyWithStaticGetterAsStatic()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property instance int32 Goo() { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<WorkItem(528038, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528038")>
<Fact()>
Public Sub CanNotReadInstancePropertyWithStaticGetterAsInstance()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property instance int32 Goo() { .get int32 A::get_Goo() }
}
]]>
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<WorkItem(527658, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527658")>
<Fact>
Public Sub PropertyWithPinnedModifierIsBogus()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property instance int32 pinned Goo() { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).AssertTheseDiagnostics(
<expected>
BC30643: Property 'Goo' is of an unsupported type.
Dim x As Object = A.Goo
~~~
</expected>)
End Sub
<WorkItem(538850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538850")>
<Fact()>
Public Sub PropertyWithMismatchedReturnTypeOfGetterIsBogus()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property string Goo() { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource)
compilation.AssertNoErrors()
End Sub
<WorkItem(527659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527659")>
<Fact()>
Public Sub PropertyWithCircularReturnTypeIsNotSupported()
Dim ilSource = <![CDATA[
.class public E extends E { }
.class public A {
.method public static class E get_Goo() { ldnull throw }
.property class E Goo() { .get class E A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics()
' Dev10 errors:
' error CS0268: Imported type 'E' is invalid. It contains a circular base type dependency.
' error CS0570: 'A.Goo' is not supported by the language
End Sub
<WorkItem(527664, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527664")>
<Fact>
Public Sub PropertyWithOpenGenericTypeAsTypeArgumentOfReturnTypeIsNotSupported()
Dim ilSource = <![CDATA[
.class public E<T> { }
.class public A {
.method public static class E<class E> get_Goo() { ldnull throw }
.property class E<class E> Goo() { .get class E<class E> A::get_Goo() }
}]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics()
End Sub
<WorkItem(527657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527657")>
<Fact>
Public Sub Dev10IgnoresSentinelInPropertySignature()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property int32 Goo(...) { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub CanReadModOptProperty()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32) get_Goo() { ldnull throw }
.property int32 modopt(int32) Goo() { .get int32 modopt(int32) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<WorkItem(527660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527660")>
<Fact>
Public Sub CanReadPropertyWithModOptInBaseClassOfReturnType()
Dim ilSource = <![CDATA[
.class public E extends class [mscorlib]System.Collections.Generic.List`1<int32> modopt(int8) { }
.class public A {
.method public static class E get_Goo() { ldnull throw }
.property class E Goo() { .get class E A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub CanReadPropertyOfArrayTypeWithModOptElement()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32)[] get_Goo() { ldnull throw }
.property int32 modopt(int32)[] Goo() { .get int32 modopt(int32)[] A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer() = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub CanReadModOptPropertyWithNonModOptGetter()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property int32 modopt(int32) Goo() { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<WorkItem(527656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527656")>
<Fact>
Public Sub CanReadNonModOptPropertyWithOpenGenericModOptGetter()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(class [mscorlib]System.IComparable`1) get_Goo() { ldnull throw }
.property int32 Goo() { .get int32 modopt(class [mscorlib]System.IComparable`1) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub CanReadNonModOptPropertyWithModOptGetter()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32) get_Goo() { ldnull throw }
.property int32 Goo() { .get int32 modopt(int32) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub CanReadModOptPropertyWithDifferentModOptGetter()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32) get_Goo() { ldnull throw }
.property int32 modopt(string) Goo() { .get int32 modopt(int32) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
''' <summary>
''' Nested modopt is invalid and results in a use-site error
''' in Roslyn. The native compiler ignores modopts completely.
''' </summary>
<WorkItem(538845, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538845")>
<Fact>
Public Sub CanReadPropertyWithMultipleAndNestedModOpts()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32) get_Goo() { ldnull throw }
.property int32 modopt(int8) modopt(native int modopt(uint8)*[] modopt(void)) Goo() { .get int32 modopt(int32) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).AssertTheseDiagnostics(
<expected>
BC30643: Property 'Goo' is of an unsupported type.
Dim x As Integer = A.Goo
~~~
</expected>)
End Sub
''' <summary>
''' Nested modreq within modopt is invalid and results in a use-site error
''' in Roslyn. The native compiler ignores modopts completely.
''' </summary>
<Fact()>
Public Sub CanReadPropertyWithModReqsNestedWithinModOpts()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 modopt(int32) get_Goo() { ldnull throw }
.property int32 modopt(class [mscorlib]System.IComparable`1<method void*()[]> modreq(bool)) Goo() { .get int32 modopt(int32) A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Integer = A.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).AssertTheseDiagnostics(
<expected>
BC30643: Property 'Goo' is of an unsupported type.
Dim x As Integer = A.Goo
~~~
</expected>)
End Sub
<WorkItem(538846, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538846")>
<Fact>
Public Sub CanNotReadPropertyWithModReq()
Dim ilSource = <![CDATA[
.class public A {
.method public static int32 get_Goo() { ldnull throw }
.property int32 modreq(int8) Goo() { .get int32 A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
x = A.get_Goo()
End Sub
End Class
]]></file></compilation>
Dim compilation = CompilationUtils.CreateCompilationWithCustomILSource(vbSource, ilSource)
CompilationUtils.AssertTheseDiagnostics(compilation,
<expected>
BC30643: Property 'A.Goo' is of an unsupported type.
Dim x As Object = A.Goo
~~~
BC30456: 'get_Goo' is not a member of 'A'.
x = A.get_Goo()
~~~~~~~~~
</expected>)
End Sub
<WorkItem(527662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527662")>
<WorkItem(99292, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=99292")>
<Fact>
Public Sub CanNotReadPropertyWithModReqInBaseClassOfReturnType()
Dim ilSource = <![CDATA[
.class public E extends class [mscorlib]System.Collections.Generic.List`1<int32 modreq(int8)[]> { }
.class public A {
.method public static class E get_Goo() { ldnull throw }
.property class E Goo() { .get class E A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Private Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
CompileWithCustomILSource(vbSource, ilSource)
End Sub
<Fact>
Public Sub VoidReturningPropertyHidesMembersFromBase()
Dim ilSource = <![CDATA[
.class public B {
.method public static int32 get_Goo() { ldnull throw }
.property int32 Goo() { .get int32 B::get_Goo() }
}
.class public A extends B {
.method public static void get_Goo() { ldnull throw }
.property void Goo() { .get void A::get_Goo() }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class B
Shared Sub Main()
Dim x As Object = A.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics(
Diagnostic(ERRID.ERR_VoidValue, "A.Goo"))
End Sub
<WorkItem(527663, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527663")>
<Fact>
Public Sub CanNotReadPropertyFromAmbiguousGenericClass()
Dim ilSource = <![CDATA[
.class public A`1<T> {
.method public static int32 get_Goo() { ldnull throw }
.property int32 Goo() { .get int32 A`1::get_Goo() }
}
.class public A<T> {
.method public static int32 get_Goo() { ldnull throw }
.property int32 Goo() { .get int32 A::get_Goo() }
}
]]>
Dim source = <compilation><file name="c.vb"><![CDATA[
Class B
Shared Sub Main()
Dim x As Object = A(Of Integer).Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(source, ilSource).
VerifyDiagnostics(Diagnostic(ERRID.ERR_AmbiguousInUnnamedNamespace1, "A(Of Integer)").WithArguments("A"))
End Sub
<Fact>
Public Sub PropertyWithoutAccessorsIsBogus()
Dim ilSource = <![CDATA[
.class public B {
.method public instance void .ctor() {
ldarg.0
call instance void class System.Object::.ctor()
ret
}
.property int32 Goo() { }
}
]]>.Value
Dim vbSource = <compilation><file name="c.vb"><![CDATA[
Class C
Private Shared Sub Main()
Dim goo As Object = B.Goo
End Sub
End Class
]]></file></compilation>
CreateCompilationWithCustomILSource(vbSource, ilSource).VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "B.Goo").WithArguments("Goo", "B"))
End Sub
<WorkItem(538946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538946")>
<Fact>
Public Sub FalseAmbiguity()
Dim text = <compilation><file name="c.vb"><![CDATA[
Interface IA
ReadOnly Property Goo() As Integer
End Interface
Interface IB(Of T)
Inherits IA
End Interface
Interface IC
Inherits IB(Of Integer)
Inherits IB(Of String)
End Interface
Class C
Private Shared Sub Main()
Dim x As IC = Nothing
Dim y As Integer = x.Goo
End Sub
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
Dim diagnostics = comp.GetDiagnostics()
Assert.Empty(diagnostics)
End Sub
<WorkItem(539320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539320")>
<Fact>
Public Sub FalseWarningCS0109ForNewModifier()
Dim text = <compilation><file name="c.vb"><![CDATA[
Class [MyBase]
Public ReadOnly Property MyProp() As Integer
Get
Return 1
End Get
End Property
End Class
Class [MyClass]
Inherits [MyBase]
Private intI As Integer = 0
Private Shadows Property MyProp() As Integer
Get
Return intI
End Get
Set
intI = value
End Set
End Property
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
Dim diagnostics = comp.GetDiagnostics()
Assert.Empty(diagnostics)
End Sub
<Fact>
Public Sub FalseErrorCS0103ForValueKeywordInExpImpl()
Dim text = <compilation><file name="c.vb"><![CDATA[
Interface MyInter
Property MyProp() As Integer
End Interface
Class TestClass
Implements MyInter
Shared intI As Integer = 0
Private Property MyInter_MyProp() As Integer Implements MyInter.MyProp
Get
Return intI
End Get
Set
intI = value
End Set
End Property
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
Dim diagnostics = comp.GetDiagnostics()
Assert.Empty(diagnostics)
End Sub
<Fact>
Public Sub ExplicitInterfaceImplementationSimple()
Dim text = <compilation><file name="c.vb"><![CDATA[
Interface I
Property P() As Integer
End Interface
Class C
Implements I
Private Property I_P() As Integer Implements I.P
Get
Return m_I_P
End Get
Set
m_I_P = Value
End Set
End Property
Private m_I_P As Integer
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
CompilationUtils.AssertNoErrors(comp)
Dim globalNamespace = comp.GlobalNamespace
Dim [interface] = DirectCast(globalNamespace.GetTypeMembers("I").Single(), NamedTypeSymbol)
Assert.Equal(TypeKind.[Interface], [interface].TypeKind)
Dim interfaceProperty = DirectCast([interface].GetMembers("P").Single(), PropertySymbol)
Dim [class] = DirectCast(globalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol)
Assert.Equal(TypeKind.[Class], [class].TypeKind)
Assert.True([class].Interfaces.Contains([interface]))
Dim classProperty = DirectCast([class].GetMembers("I_P").Single(), PropertySymbol)
CheckPropertyExplicitImplementation([class], classProperty, interfaceProperty)
End Sub
<Fact>
Public Sub ExplicitInterfaceImplementationGeneric()
Dim text = <compilation><file name="c.vb"><![CDATA[
Namespace N
Interface I(Of T)
Property P() As T
End Interface
End Namespace
Class C
Implements N.I(Of Integer)
Private Property N_I_P() As Integer Implements N.I(Of Integer).P
Get
Return m_N_I_P
End Get
Set
m_N_I_P = Value
End Set
End Property
Private m_N_I_P As Integer
End Class
]]></file></compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(text)
CompilationUtils.AssertNoErrors(comp)
Dim globalNamespace = comp.GlobalNamespace
Dim [namespace] = DirectCast(globalNamespace.GetMembers("N").Single(), NamespaceSymbol)
Dim [interface] = DirectCast([namespace].GetTypeMembers("I").Single(), NamedTypeSymbol)
Assert.Equal(TypeKind.[Interface], [interface].TypeKind)
Dim interfaceProperty = DirectCast([interface].GetMembers("P").Single(), PropertySymbol)
Dim [class] = DirectCast(globalNamespace.GetTypeMembers("C").Single(), NamedTypeSymbol)
Assert.Equal(TypeKind.[Class], [class].TypeKind)
Dim classProperty = DirectCast([class].GetMembers("N_I_P").Single(), PropertySymbol)
Dim substitutedInterface = [class].Interfaces.Single()
Assert.Equal([interface], substitutedInterface.ConstructedFrom)
Dim substitutedInterfaceProperty = DirectCast(substitutedInterface.GetMembers("P").Single(), PropertySymbol)
CheckPropertyExplicitImplementation([class], classProperty, substitutedInterfaceProperty)
End Sub
#End Region
#Region "Emit"""
<Fact>
Public Sub PropertyNonDefaultAccessorNames()
Dim source = <compilation><file name="c.vb"><![CDATA[
Class Program
Private Shared Sub M(i As Valid)
i.Instance = 0
System.Console.Write("{0}", i.Instance)
End Sub
Shared Sub Main()
Valid.[Static] = 0
System.Console.Write("{0}", Valid.[Static])
End Sub
End Class
]]></file></compilation>
Dim compilation = CompileAndVerify(source, references:={s_propertiesDll}, expectedOutput:="0")
Dim ilSource = <![CDATA[{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: call "Sub Valid.StaticSet(Integer)"
IL_0006: ldstr "{0}"
IL_000b: call "Function Valid.StaticGet() As Integer"
IL_0010: box "Integer"
IL_0015: call "Sub System.Console.Write(String, Object)"
IL_001a: ret
}
]]>
compilation.VerifyIL("Program.Main", ilSource)
End Sub
<WorkItem(528542, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528542")>
<Fact()>
Public Sub MismatchedAccessorTypes()
Dim source = <code><file name="c.vb"><![CDATA[
Class Program
Private Shared Sub M(i As Mismatched)
i.Instance = 0
System.Console.Write("{0}", i.Instance)
End Sub
Private Shared Sub N(i As Signatures)
i.StaticAndInstance = 0
i.GetUsedAsSet = 0
End Sub
Private Shared Sub Main()
Mismatched.[Static] = 0
System.Console.Write("{0}", Mismatched.[Static])
End Sub
End Class
]]></file></code>
CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {s_propertiesDll}).VerifyDiagnostics(
Diagnostic(ERRID.ERR_NameNotMember2, "i.Instance").WithArguments("Instance", "Mismatched"),
Diagnostic(ERRID.ERR_NameNotMember2, "i.Instance").WithArguments("Instance", "Mismatched"),
Diagnostic(ERRID.ERR_UnsupportedProperty1, "StaticAndInstance").WithArguments("Signatures.StaticAndInstance"),
Diagnostic(ERRID.ERR_UnsupportedProperty1, "GetUsedAsSet").WithArguments("Signatures.GetUsedAsSet"),
Diagnostic(ERRID.ERR_NameNotMember2, "Mismatched.[Static]").WithArguments("Static", "Mismatched"),
Diagnostic(ERRID.ERR_NameNotMember2, "Mismatched.[Static]").WithArguments("Static", "Mismatched"))
End Sub
''' <summary>
''' Calling bogus methods directly should not be allowed.
''' </summary>
<Fact>
Public Sub CallMethodsDirectly()
Dim source = <compilation><file name="c.vb"><![CDATA[
Class Program
Private Shared Sub M(i As Mismatched)
i.InstanceBoolSet(False)
System.Console.Write("{0}", i.InstanceInt32Get())
End Sub
Private Shared Sub Main()
Mismatched.StaticBoolSet(False)
System.Console.Write("{0}", Mismatched.StaticInt32Get())
End Sub
End Class
]]></file></compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndReferences(source, {s_propertiesDll})
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC30456: 'InstanceBoolSet' is not a member of 'Mismatched'.
i.InstanceBoolSet(False)
~~~~~~~~~~~~~~~~~
BC30456: 'InstanceInt32Get' is not a member of 'Mismatched'.
System.Console.Write("{0}", i.InstanceInt32Get())
~~~~~~~~~~~~~~~~~~
BC30456: 'StaticBoolSet' is not a member of 'Mismatched'.
Mismatched.StaticBoolSet(False)
~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'StaticInt32Get' is not a member of 'Mismatched'.
System.Console.Write("{0}", Mismatched.StaticInt32Get())
~~~~~~~~~~~~~~~~~~~~~~~~~
</errors>)
End Sub
<Fact>
Public Sub MethodsReferencedInMultipleProperties()
Dim source = <compilation><file name="c.vb"><![CDATA[
Class Program
Private Shared Sub M(i As Signatures)
i.GoodInstance = 0
System.Console.Write("{0}", i.GoodInstance)
End Sub
Public Shared Sub Main()
Signatures.GoodStatic = 0
System.Console.Write("{0}", Signatures.GoodStatic)
End Sub
End Class
]]></file></compilation>
Dim result = CompileAndVerify(source, references:={s_propertiesDll}, expectedOutput:="0")
Dim ilSource = <![CDATA[{
// Code size 27 (0x1b)
.maxstack 2
IL_0000: ldc.i4.0
IL_0001: call "Sub Signatures.StaticSet(Integer)"
IL_0006: ldstr "{0}"
IL_000b: call "Function Signatures.StaticGet() As Integer"
IL_0010: box "Integer"
IL_0015: call "Sub System.Console.Write(String, Object)"
IL_001a: ret
}
]]>
result.VerifyIL("Program.Main", ilSource)
Dim compilation = CompileWithCustomPropertiesAssembly(source)
Dim type = DirectCast(compilation.GlobalNamespace.GetMembers("Signatures").Single(), PENamedTypeSymbol)
' Valid static property, property with signature that does not match accessors,
' and property with accessors that do not match each other.
Dim goodStatic = DirectCast(type.GetMembers("GoodStatic").Single(), PEPropertySymbol)
Dim badStatic = DirectCast(type.GetMembers("BadStatic").Single(), PEPropertySymbol)
Dim mismatchedStatic = DirectCast(type.GetMembers("MismatchedStatic").Single(), PEPropertySymbol)
Assert.Null(goodStatic.GetUseSiteErrorInfo())
Assert.Null(badStatic.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported
Assert.Null(mismatchedStatic.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported
VerifyAccessor(goodStatic.GetMethod, goodStatic, MethodKind.PropertyGet)
VerifyAccessor(goodStatic.SetMethod, goodStatic, MethodKind.PropertySet)
VerifyAccessor(badStatic.GetMethod, goodStatic, MethodKind.PropertyGet)
VerifyAccessor(badStatic.SetMethod, goodStatic, MethodKind.PropertySet)
VerifyAccessor(mismatchedStatic.GetMethod, goodStatic, MethodKind.PropertyGet)
VerifyAccessor(mismatchedStatic.SetMethod, mismatchedStatic, MethodKind.PropertySet)
' Valid instance property, property with signature that does not match accessors,
' and property with accessors that do not match each other.
Dim goodInstance = DirectCast(type.GetMembers("GoodInstance").Single(), PEPropertySymbol)
Dim badInstance = DirectCast(type.GetMembers("BadInstance").Single(), PEPropertySymbol)
Dim mismatchedInstance = DirectCast(type.GetMembers("MismatchedInstance").Single(), PEPropertySymbol)
Assert.Null(goodInstance.GetUseSiteErrorInfo())
Assert.Null(badInstance.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported
Assert.Null(mismatchedInstance.GetUseSiteErrorInfo()) ' Mismatch based on property type is supported
VerifyAccessor(goodInstance.GetMethod, goodInstance, MethodKind.PropertyGet)
VerifyAccessor(goodInstance.SetMethod, goodInstance, MethodKind.PropertySet)
VerifyAccessor(badInstance.GetMethod, goodInstance, MethodKind.PropertyGet)
VerifyAccessor(badInstance.SetMethod, goodInstance, MethodKind.PropertySet)
VerifyAccessor(mismatchedInstance.GetMethod, goodInstance, MethodKind.PropertyGet)
VerifyAccessor(mismatchedInstance.SetMethod, mismatchedInstance, MethodKind.PropertySet)
' Mix of static and instance accessors.
Dim staticAndInstance = DirectCast(type.GetMembers("StaticAndInstance").Single(), PEPropertySymbol)
VerifyAccessor(staticAndInstance.GetMethod, goodStatic, MethodKind.PropertyGet)
VerifyAccessor(staticAndInstance.SetMethod, goodInstance, MethodKind.PropertySet)
Assert.Equal(ERRID.ERR_UnsupportedProperty1, staticAndInstance.GetUseSiteErrorInfo().Code)
' Property with get and set accessors both referring to the same get method.
Dim getUsedAsSet = DirectCast(type.GetMembers("GetUsedAsSet").Single(), PEPropertySymbol)
VerifyAccessor(getUsedAsSet.GetMethod, goodInstance, MethodKind.PropertyGet)
VerifyAccessor(getUsedAsSet.SetMethod, goodInstance, MethodKind.PropertyGet)
Assert.Equal(ERRID.ERR_UnsupportedProperty1, getUsedAsSet.GetUseSiteErrorInfo().Code)
End Sub
#End Region
#End Region
<WorkItem(540343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540343")>
<Fact>
Public Sub PropertiesWithCircularTypeReferences()
CompileAndVerify(
<compilation>
<file name="Cobj010mod.vb">
Module Cobj010mod
Class Class1
Public Property c2 As Class2
End Class
Class Class2
Public Property c3 As Class3
End Class
Class Class3
Public Property c4 As Class4
End Class
Class Class4
Public Property c5 As Class5
End Class
Class Class5
Public Property c6 As Class6
End Class
Class Class6
Public Property c7 As Class7
End Class
Class Class7
Public Property c8 As Class8
End Class
Class Class8
Public Property c1 As Class1
End Class
Sub Main()
Dim c1 As New Class1()
if c1 is nothing
c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8.c1.c2.c3.c4.c5.c6.c7.c8 = New Class8()
end if
End Sub
End Module
</file>
</compilation>, expectedOutput:="")
End Sub
<WorkItem(540342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540342")>
<Fact>
Public Sub NoSequencePointsForAutoPropertyAccessors()
Dim source =
<compilation>
<file name="c.vb">
Class C
Property P
End Class
</file>
</compilation>
CompileAndVerify(source, options:=TestOptions.ReleaseDll).VerifyDiagnostics()
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName1()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Class Base
Public ReadOnly Property BANANa(x as string, y as integer) as integer
Get
return 1
End Get
End Property
End Class
Partial Class Class1
Inherits Base
Public ReadOnly Property baNana()
Get
return 1
End Get
End Property
Public ReadOnly Property Banana(x as integer)
Get
return 1
End Get
End Property
End Class
</file>
<file name="a.vb">
Partial Class Class1
Public ReadOnly Property baNANa(xyz as String)
Get
return 1
End Get
End Property
Public ReadOnly Property BANANA(x as Long)
Get
return 1
End Get
End Property
End Class
</file>
</compilation>)
' No "Overloads", so all properties should match first overloads in first source file
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allProperties = class1.GetMembers("baNana").OfType(Of PropertySymbol)()
' All properties in Class1 should have metadata name "baNana" (first spelling, by source position).
Dim count = 0
For Each m In allProperties
count = count + 1
Assert.Equal("baNana", m.MetadataName)
If m.Parameters.Any Then
Assert.NotEqual("baNana", m.Name)
End If
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName2()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Class Base
Public ReadOnly Property BANANa(x as string, y as integer)
Get
return 1
End Get
End Property
End Class
Partial Class Class1
Inherits Base
Overloads Public ReadOnly Property baNana()
Get
return 1
End Get
End Property
Overloads Public ReadOnly Property Banana(x as integer)
Get
return 1
End Get
End Property
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Public ReadOnly Property baNANa(xyz as String)
Get
return 1
End Get
End Property
Overloads Public ReadOnly Property BANANA(x as Long)
Get
return 1
End Get
End Property
End Class
</file>
</compilation>)
' "Overloads" specified, so all properties should match method in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allProperties = class1.GetMembers("baNANa").OfType(Of PropertySymbol)()
' All properties in Class1 should have metadata name "baNANa".
Dim count = 0
For Each m In allProperties
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName3()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Class Base
Overridable Public ReadOnly Property BANANa(x as string, y as integer)
Get
return 1
End Get
End Property
End Class
Partial Class Class1
Inherits Base
Overloads Public ReadOnly Property baNana()
Get
return 1
End Get
End Property
Overrides Public ReadOnly Property baNANa(xyz as String, a as integer)
Get
return 1
End Get
End Property
Overloads Public ReadOnly Property Banana(x as integer)
Get
return 1
End Get
End Property
End Class
</file>
<file name="a.vb">
Partial Class Class1
Overloads Public ReadOnly Property BANANA(x as Long)
Get
return 1
End Get
End Property
End Class
</file>
</compilation>)
' "Overrides" specified, so all properties should match property in base
Dim class1 = compilation.GetTypeByMetadataName("Class1")
Dim allProperties = class1.GetMembers("baNANa").OfType(Of PropertySymbol)()
' All properties in Class1 should have metadata name "BANANa".
Dim count = 0
For Each m In allProperties
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(4, count)
CompilationUtils.AssertNoErrors(compilation)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName4()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Interface Base1
ReadOnly Property BANANa(x as string, y as integer)
End Interface
Interface Base2
ReadOnly Property BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads ReadOnly Property baNana()
Overloads ReadOnly Property baNANa(xyz as String, a as integer)
Overloads ReadOnly Property Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, so all properties should match properties in base
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allProperties = interface1.GetMembers("baNANa").OfType(Of PropertySymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "BANANa".
Dim count = 0
For Each m In allProperties
count = count + 1
Assert.Equal("BANANa", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact>
Public Sub MultipleOverloadsMetadataName5()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
Interface Base1
ReadOnly Property BAnANa(x as string, y as integer)
End Interface
Interface Base2
ReadOnly Property BANANa(x as string, y as integer, z as Object)
End Interface
Interface Base3
Inherits Base2
End Interface
Interface Interface1
Inherits Base1, Base3
Overloads ReadOnly Property baNana()
Overloads ReadOnly Property baNANa(xyz as String, a as integer)
Overloads ReadOnly Property Banana(x as integer)
End Interface
</file>
</compilation>)
' "Overloads" specified, but base properties have multiple casing, so don't use it.
Dim interface1 = compilation.GetTypeByMetadataName("Interface1")
Dim allProperties = interface1.GetMembers("baNANa").OfType(Of PropertySymbol)()
CompilationUtils.AssertNoErrors(compilation)
' All methods in Interface1 should have metadata name "baNana".
Dim count = 0
For Each m In allProperties
count = count + 1
Assert.Equal("baNana", m.MetadataName)
Next
Assert.Equal(3, count)
End Sub
<Fact()>
Public Sub AutoImplementedAccessorAreImplicitlyDeclared()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(
<compilation>
<file name="b.vb">
MustInherit Class A
Public MustOverride Property P As Integer
Public Property P2 As Integer
End Class
Interface I
Property Q As Integer
End Interface
</file>
</compilation>)
' Per design meeting (see bug 11253), in VB, if there's no "Get" or "Set" written,
' then IsImplicitlyDeclared should be tru.
Dim globalNS = comp.GlobalNamespace
Dim a = globalNS.GetTypeMembers("A", 0).Single()
Dim i = globalNS.GetTypeMembers("I", 0).Single()
Dim p = TryCast(a.GetMembers("P").AsEnumerable().SingleOrDefault(), PropertySymbol)
Assert.True(p.GetMethod.IsImplicitlyDeclared)
Assert.True(p.SetMethod.IsImplicitlyDeclared)
p = TryCast(a.GetMembers("P2").SingleOrDefault(), PropertySymbol)
Assert.True(p.GetMethod.IsImplicitlyDeclared)
Assert.True(p.SetMethod.IsImplicitlyDeclared)
Dim q = TryCast(i.GetMembers("Q").AsEnumerable().SingleOrDefault(), PropertySymbol)
Assert.True(q.GetMethod.IsImplicitlyDeclared)
Assert.True(q.SetMethod.IsImplicitlyDeclared)
End Sub
<Fact(), WorkItem(544315, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544315")>
Public Sub PropertyAccessorParameterLocation()
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="b.vb">
Imports System
Public Class A
Public Default ReadOnly Property Prop(ByVal p1 As Integer) As String
Get
Return "passed"
End Get
End Property
End Class
</file>
</compilation>)
Dim globalNS = comp.SourceModule.GlobalNamespace
Dim a = globalNS.GetTypeMembers("A").Single()
Dim p = TryCast(a.GetMembers("Prop").Single(), PropertySymbol)
Dim paras = p.Parameters
Assert.Equal(1, paras.Length)
Dim p1 = paras(0)
Assert.Equal("p1", p1.Name)
Assert.Equal(1, p1.Locations.Length)
Assert.Equal(1, p.GetMethod.Parameters.Length)
Dim p11 = p.GetMethod.Parameters(0)
Assert.False(p11.Locations.IsEmpty, "Parameter Location NotEmpty")
Assert.True(p11.Locations(0).IsInSource, "Parameter Location(0) IsInSource")
Assert.Equal(p1.Locations(0), p11.Locations(0))
End Sub
''' <summary>
''' Consistent accessor signatures but different
''' from property signature.
''' </summary>
<WorkItem(545814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545814")>
<Fact()>
Public Sub DifferentSignatures_AccessorsConsistent()
Dim source1 = <![CDATA[
.class public A
{
.method public instance object get_P1(object& i) { ldnull ret }
.method public instance void set_P1(object& i, object& v) { ret }
.method public instance object get_P2(object& i) { ldnull ret }
.method public instance void set_P3(object& i, object& v) { ret }
.property instance object P1(object)
{
.get instance object A::get_P1(object& i)
.set instance void A::set_P1(object& i, object& v)
}
.property instance object P2(object)
{
.get instance object A::get_P2(object& i)
}
.property instance object P3(object)
{
.set instance void A::set_P3(object& i, object& v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As A, i As Object)
o.P1(i) = o.P1(i)
o.P3(i) = o.P2(i)
F(o.P1(i))
End Sub
Sub F(ByRef o As Object)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertNoErrors()
Dim compilationVerifier = CompileAndVerify(compilation2)
compilationVerifier.VerifyIL("M.M(A, Object)",
<![CDATA[
{
// Code size 131 (0x83)
.maxstack 4
.locals init (Object V_0,
Object V_1,
Object V_2,
Object V_3)
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0007: stloc.0
IL_0008: ldloca.s V_0
IL_000a: ldarg.0
IL_000b: ldarg.1
IL_000c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0011: stloc.2
IL_0012: ldloca.s V_2
IL_0014: callvirt "Function A.get_P1(ByRef Object) As Object"
IL_0019: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_001e: stloc.1
IL_001f: ldloca.s V_1
IL_0021: callvirt "Sub A.set_P1(ByRef Object, ByRef Object)"
IL_0026: ldarg.0
IL_0027: ldarg.1
IL_0028: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_002d: stloc.1
IL_002e: ldloca.s V_1
IL_0030: ldarg.0
IL_0031: ldarg.1
IL_0032: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0037: stloc.2
IL_0038: ldloca.s V_2
IL_003a: callvirt "Function A.get_P2(ByRef Object) As Object"
IL_003f: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0044: stloc.0
IL_0045: ldloca.s V_0
IL_0047: callvirt "Sub A.set_P3(ByRef Object, ByRef Object)"
IL_004c: ldarg.0
IL_004d: dup
IL_004e: ldarg.1
IL_004f: dup
IL_0050: stloc.0
IL_0051: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0056: stloc.2
IL_0057: ldloca.s V_2
IL_0059: callvirt "Function A.get_P1(ByRef Object) As Object"
IL_005e: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0063: stloc.1
IL_0064: ldloca.s V_1
IL_0066: call "Sub M.F(ByRef Object)"
IL_006b: ldloc.0
IL_006c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0071: stloc.2
IL_0072: ldloca.s V_2
IL_0074: ldloc.1
IL_0075: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_007a: stloc.3
IL_007b: ldloca.s V_3
IL_007d: callvirt "Sub A.set_P1(ByRef Object, ByRef Object)"
IL_0082: ret
}
]]>)
' Accessor signature should be used for binding
' rather than property signature.
Dim source3 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As A)
Dim v As Integer = o.P1(1)
v = o.P2(2)
o.P3(3) = v
F(o.P1(1))
End Sub
Sub F(ByRef o As Integer)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {reference1})
compilation3.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'.
Dim v As Integer = o.P1(1)
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'.
v = o.P2(2)
~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'.
F(o.P1(1))
~~~~~~~
]]></errors>)
End Sub
''' <summary>
''' Different accessor signatures and different accessor and
''' property signatures. (Both are supported by Dev11, but
''' Roslyn requires accessors to have consistent signatures.)
''' </summary>
<WorkItem(545814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545814")>
<Fact()>
Public Sub DifferentSignatures_AccessorsDifferent()
Dim source1 = <![CDATA[
.class public A { }
.class public B { }
.class public C { }
.class public D
{
.method public instance class B get_P(class A i) { ldnull ret }
.method public instance void set_P(class B i, class C v) { ret }
.property instance class A P(class C)
{
.get instance class B D::get_P(class A)
.set instance void D::set_P(class B, class C)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
' Accessor method calls.
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As D, x As A, y As B, z As C)
' get_P signature.
y = o.P(x)
o.P(x) = y
' set_P signature.
z = o.P(y)
o.P(y) = z
' P signature.
x = o.P(z)
o.P(z) = x
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30643: Property 'D.P(i As C)' is of an unsupported type.
y = o.P(x)
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
o.P(x) = y
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
z = o.P(y)
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
o.P(y) = z
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
x = o.P(z)
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
o.P(z) = x
~
]]></errors>)
' Property references.
Dim source3 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As D, x As A)
MBByVal(o.P(x))
MBByRef(o.P(x))
MCByVal(o.P(x))
MCByRef(o.P(x))
End Sub
Sub MBByVal(y As B)
End Sub
Sub MBByRef(ByRef y As B)
End Sub
Sub MCByVal(z As C)
End Sub
Sub MCByRef(ByRef z As C)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {reference1})
compilation3.AssertTheseDiagnostics(<errors><![CDATA[
BC30643: Property 'D.P(i As C)' is of an unsupported type.
MBByVal(o.P(x))
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
MBByRef(o.P(x))
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
MCByVal(o.P(x))
~
BC30643: Property 'D.P(i As C)' is of an unsupported type.
MCByRef(o.P(x))
~
]]></errors>)
End Sub
''' <summary>
''' Properties used in object initializers and attributes.
''' </summary>
<WorkItem(545814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545814")>
<Fact()>
Public Sub DifferentSignatures_ObjectInitializersAndAttributes()
Dim source1 = <![CDATA[
.class public A extends [mscorlib]System.Attribute
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
.method public instance int32 get_P() { ldc.i4.0 ret }
.method public instance void set_P(int32 v) { ret }
.property object P()
{
.get instance int32 A::get_P()
.set instance void A::set_P(int32 v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
' Object initializer.
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Private F As New A With {.P = ""}
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.
Private F As New A With {.P = ""}
~~
]]></errors>)
' Attribute. Dev11 no errors.
Dim source3 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
<A(P:="")>
Class C
End Class
]]>
</file>
</compilation>
Dim compilation3 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source3, {reference1})
compilation3.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'String' to 'Integer'.
<A(P:="")>
~~
BC30934: Conversion from 'String' to 'Integer' cannot occur in a constant expression used as an argument to an attribute.
<A(P:="")>
~~
]]></errors>)
End Sub
''' <summary>
''' Overload resolution prefers supported properties over unsupported
''' properties. Since we're marking properties with inconsistent signatures
''' as unsupported, this can lead to different overload resolution than Dev11.
''' </summary>
''' <remarks></remarks>
<WorkItem(545814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545814")>
<Fact()>
Public Sub DifferentSignatures_OverloadResolution()
Dim source1 = <![CDATA[
.class public A { }
.class public B extends A { }
.class public C
{
.method public instance int32 get_P(class A o) { ldnull ret }
.method public instance void set_P(class A o, int32 v) { ret }
.method public instance int32 get_P(object o) { ldnull ret }
.method public instance void set_P(object o, int32 v) { ret }
// Property indexed by A, accessors indexed by A.
.property instance int32 P(class A)
{
.get instance int32 C::get_P(class A o)
.set instance void C::set_P(class A o, int32 v)
}
// Property indexed by B, accessors indexed by object.
.property instance int32 P(class B)
{
.get instance int32 C::get_P(object o)
.set instance void C::set_P(object o, int32 v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(_a As A, _b As B, o As C)
o.P(_a) += 1 ' Dev11: P(A); Roslyn: P(A)
o.P(_b) += 1 ' Dev11: P(B); Roslyn: P(A)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertNoErrors()
Dim compilationVerifier = CompileAndVerify(compilation2)
compilationVerifier.VerifyIL("M.M(A, B, C)",
<![CDATA[
{
// Code size 41 (0x29)
.maxstack 4
.locals init (C V_0,
A V_1)
IL_0000: ldarg.2
IL_0001: dup
IL_0002: stloc.0
IL_0003: ldarg.0
IL_0004: dup
IL_0005: stloc.1
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: callvirt "Function C.get_P(A) As Integer"
IL_000d: ldc.i4.1
IL_000e: add.ovf
IL_000f: callvirt "Sub C.set_P(A, Integer)"
IL_0014: ldarg.2
IL_0015: dup
IL_0016: stloc.0
IL_0017: ldarg.1
IL_0018: dup
IL_0019: stloc.1
IL_001a: ldloc.0
IL_001b: ldloc.1
IL_001c: callvirt "Function C.get_P(A) As Integer"
IL_0021: ldc.i4.1
IL_0022: add.ovf
IL_0023: callvirt "Sub C.set_P(A, Integer)"
IL_0028: ret
}
]]>)
End Sub
''' <summary>
''' Accessors with different parameter count than property.
''' </summary>
<WorkItem(545814, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545814")>
<Fact()>
Public Sub DifferentSignatures_ParameterCount()
Dim source1 = <![CDATA[
.class public A
{
.method public instance int32 get_P(object x, object y) { ldnull ret }
.method public instance void set_P(object x, object y, int32 v) { ret }
.method public instance int32 get_Q(object o) { ldnull ret }
.method public instance void set_Q(object o, int32 v) { ret }
// Property with fewer arguments than accessors.
.property instance int32 P(object)
{
.get instance int32 A::get_P(object x, object y)
.set instance void A::set_P(object x, object y, int32 v)
}
// Property with more arguments than accessors.
.property instance int32 Q(object, object)
{
.get instance int32 A::get_Q(object o)
.set instance void A::set_Q(object o, int32 v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As A, x As Object, y As Object)
o.P(x) = o.P(x)
o.P(x, y) = o.P(x, y)
o.Q(x) += 1
o.Q(x, y) += 1
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30643: Property 'A.P(x As Object)' is of an unsupported type.
o.P(x) = o.P(x)
~
BC30643: Property 'A.P(x As Object)' is of an unsupported type.
o.P(x) = o.P(x)
~
BC30643: Property 'A.P(x As Object)' is of an unsupported type.
o.P(x, y) = o.P(x, y)
~
BC30643: Property 'A.P(x As Object)' is of an unsupported type.
o.P(x, y) = o.P(x, y)
~
BC30643: Property 'A.Q(o As Object, v As Object)' is of an unsupported type.
o.Q(x) += 1
~
BC30643: Property 'A.Q(o As Object, v As Object)' is of an unsupported type.
o.Q(x, y) += 1
~
]]></errors>)
End Sub
<WorkItem(545959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545959")>
<Fact()>
Public Sub DifferentAccessorSignatures_NamedArguments_1()
Dim ilSource = <![CDATA[
.class abstract public A
{
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method public abstract virtual instance void get(object x, object y)
{
}
.method public abstract virtual instance void set(object x, object y)
{
}
.method public instance int32 get_P(object x, object y)
{
ldarg.0
ldarg.1
ldarg.2
callvirt instance void A::get(object, object)
ldnull
ret
}
.method public instance void set_P(object y, object x, int32 v)
{
ldarg.0
ldarg.1
ldarg.2
callvirt instance void A::set(object, object)
ret
}
.property instance int32 P(object, object)
{
.get instance int32 A::get_P(object, object)
.set instance void A::set_P(object, object, int32)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><
System.Console.WriteLine("get {0}, {1}", x, y)
End Sub
Public Overrides Sub [set](x As Object, y As Object)
System.Console.WriteLine("set {0}, {1}", x, y)
End Sub
End Class
Module M
Sub Main()
Dim o = New B()
o.P(1, 2) *= 1
o.P(x:=3, y:=4) *= 1
M(o.P(x:=5, y:=6))
End Sub
Sub M(ByRef i As Integer)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'.
o.P(x:=3, y:=4) *= 1
~
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'.
o.P(x:=3, y:=4) *= 1
~
BC30272: 'x' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'.
o.P(x:=3, y:=4) *= 1
~
BC30272: 'y' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'.
o.P(x:=3, y:=4) *= 1
~
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'.
M(o.P(x:=5, y:=6))
~
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(Param As Object, Param As Object) As Integer'.
M(o.P(x:=5, y:=6))
~
BC30272: 'x' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'.
M(o.P(x:=5, y:=6))
~
BC30272: 'y' is not a parameter of 'Public Property P(Param As Object, Param As Object) As Integer'.
M(o.P(x:=5, y:=6))
~
</expected>)
End Sub
''' <summary>
''' Named arguments that differ by case.
''' </summary>
<Fact()>
Public Sub DifferentAccessorSignatures_NamedArguments_2()
Dim ilSource = <![CDATA[
.class public A
{
.method public instance int32 get_P(object one, object two) { ldnull ret }
.method public instance void set_P(object ONE, object _two, int32 v) { ret }
.property instance int32 P(object, object)
{
.get instance int32 A::get_P(object one, object two)
.set instance void A::set_P(object ONE, object _two, int32 v)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As A)
o.P(1, 2) += 1
o.P(one:=1, two:=2) += 1
o.P(ONE:=1, _two:=2) += 1
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(one As Object, Param As Object) As Integer'.
o.P(one:=1, two:=2) += 1
~
BC30272: 'two' is not a parameter of 'Public Property P(one As Object, Param As Object) As Integer'.
o.P(one:=1, two:=2) += 1
~~~
BC30455: Argument not specified for parameter 'Param' of 'Public Property P(one As Object, Param As Object) As Integer'.
o.P(ONE:=1, _two:=2) += 1
~
BC30272: '_two' is not a parameter of 'Public Property P(one As Object, Param As Object) As Integer'.
o.P(ONE:=1, _two:=2) += 1
~~~~
</expected>)
End Sub
''' <summary>
''' ByRef must be consistent between accessor parameters.
''' Note: Dev11 does not require this.
''' </summary>
<Fact()>
Public Sub DifferentAccessorSignatures_ByRef()
Dim ilSource = <![CDATA[
.class public A1
{
.method public instance object get_P(object i) { ldnull ret }
.method public instance void set_P(object i, object v) { ret }
.property instance object P(object)
{
.get instance object A1::get_P(object)
.set instance void A1::set_P(object, object v)
}
}
.class public A2
{
.method public instance object get_P(object i) { ldnull ret }
.method public instance void set_P(object& i, object v) { ret }
.property instance object P(object)
{
.get instance object A2::get_P(object)
.set instance void A2::set_P(object&, object v)
}
}
.class public A3
{
.method public instance object get_P(object i) { ldnull ret }
.method public instance void set_P(object i, object& v) { ret }
.property instance object P(object)
{
.get instance object A3::get_P(object)
.set instance void A3::set_P(object, object& v)
}
}
.class public A4
{
.method public instance object& get_P(object i) { ldnull ret }
.method public instance void set_P(object i, object v) { ret }
.property instance object& P(object)
{
.get instance object& A4::get_P(object)
.set instance void A4::set_P(object, object v)
}
}
.class public A5
{
.method public instance object& get_P(object i) { ldnull ret }
.method public instance void set_P(object& i, object v) { ret }
.property instance object& P(object)
{
.get instance object& A5::get_P(object)
.set instance void A5::set_P(object&, object v)
}
}
.class public A6
{
.method public instance object& get_P(object i) { ldnull ret }
.method public instance void set_P(object i, object& v) { ret }
.property instance object& P(object)
{
.get instance object& A6::get_P(object)
.set instance void A6::set_P(object, object& v)
}
}
.class public A7
{
.method public instance object get_P(object& i) { ldnull ret }
.method public instance void set_P(object i, object v) { ret }
.property instance object P(object&)
{
.get instance object A7::get_P(object&)
.set instance void A7::set_P(object, object v)
}
}
.class public A8
{
.method public instance object get_P(object& i) { ldnull ret }
.method public instance void set_P(object& i, object v) { ret }
.property instance object P(object&)
{
.get instance object A8::get_P(object&)
.set instance void A8::set_P(object&, object v)
}
}
.class public A9
{
.method public instance object get_P(object& i) { ldnull ret }
.method public instance void set_P(object i, object& v) { ret }
.property instance object P(object&)
{
.get instance object A9::get_P(object&)
.set instance void A9::set_P(object, object& v)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(_1 As A1, _2 As A2, _3 As A3, _4 As A4, _5 As A5, _6 As A6, _7 As A7, _8 As A8, _9 As A9)
Dim x As Object = Nothing
Dim y As Object = Nothing
_1.P(y) = _1.P(x)
_2.P(y) = _2.P(x)
_3.P(y) = _3.P(x)
_4.P(y) = _4.P(x)
_5.P(y) = _5.P(x)
_6.P(y) = _6.P(x)
_7.P(y) = _7.P(x)
_8.P(y) = _8.P(x)
_9.P(y) = _9.P(x)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30643: Property 'A2.P(ByRef i As Object)' is of an unsupported type.
_2.P(y) = _2.P(x)
~
BC30643: Property 'A2.P(ByRef i As Object)' is of an unsupported type.
_2.P(y) = _2.P(x)
~
BC30643: Property 'A5.P(ByRef i As Object)' is of an unsupported type.
_5.P(y) = _5.P(x)
~
BC30643: Property 'A5.P(ByRef i As Object)' is of an unsupported type.
_5.P(y) = _5.P(x)
~
BC30643: Property 'A7.P(ByRef i As Object)' is of an unsupported type.
_7.P(y) = _7.P(x)
~
BC30643: Property 'A7.P(ByRef i As Object)' is of an unsupported type.
_7.P(y) = _7.P(x)
~
BC30643: Property 'A9.P(ByRef i As Object)' is of an unsupported type.
_9.P(y) = _9.P(x)
~
BC30643: Property 'A9.P(ByRef i As Object)' is of an unsupported type.
_9.P(y) = _9.P(x)
~
</expected>)
End Sub
''' <summary>
''' ParamArray must be consistent between accessor parameters.
''' Note: Dev11 does not require this.
''' </summary>
<Fact()>
Public Sub DifferentAccessorSignatures_ParamArray()
Dim ilSource = <![CDATA[
.class public A
{
.method public instance object get_NoParamArray(object[] i)
{
ldnull
ret
}
.method public instance void set_NoParamArray(object[] i, object v)
{
ret
}
.method public instance object get_ParamArray(object[] i)
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
ldnull
ret
}
.method public instance void set_ParamArray(object[] i, object v)
{
.param [1]
.custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 )
ret
}
// ParamArray on both accessors.
.property instance object P1(object[])
{
.get instance object A::get_ParamArray(object[])
.set instance void A::set_ParamArray(object[], object)
}
// ParamArray on getter only.
.property instance object P2(object[])
{
.get instance object A::get_ParamArray(object[])
.set instance void A::set_NoParamArray(object[], object)
}
// ParamArray on setter only.
.property instance object P3(object[])
{
.get instance object A::get_NoParamArray(object[])
.set instance void A::set_ParamArray(object[], object)
}
// ParamArray on readonly property.
.property instance object P4(object[])
{
.get instance object A::get_ParamArray(object[])
}
// ParamArray on writeonly property.
.property instance object P5(object[])
{
.set instance void A::set_ParamArray(object[], object)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As A)
Dim v As Object
Dim arg1 As Object = Nothing
Dim arg2 As Object = Nothing
Dim args = {arg1, arg2}
v = o.P1(arg1, arg2)
o.P1(arg1, arg2) = v
v = o.P2(arg1, arg2)
o.P2(arg1, arg2) = v
v = o.P3(arg1, arg2)
o.P3(arg1, arg2) = v
v = o.P4(arg1, arg2)
o.P5(arg1, arg2) = v
v = o.P1(args)
o.P1(args) = v
v = o.P2(args)
o.P2(args) = v
v = o.P3(args)
o.P3(args) = v
v = o.P4(args)
o.P5(args) = v
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30057: Too many arguments to 'Public Property P2(i As Object()) As Object'.
v = o.P2(arg1, arg2)
~~~~
BC30057: Too many arguments to 'Public Property P2(i As Object()) As Object'.
o.P2(arg1, arg2) = v
~~~~
BC30057: Too many arguments to 'Public Property P3(i As Object()) As Object'.
v = o.P3(arg1, arg2)
~~~~
BC30057: Too many arguments to 'Public Property P3(i As Object()) As Object'.
o.P3(arg1, arg2) = v
~~~~
</expected>)
Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.True(type.GetMember(Of PropertySymbol)("P1").Parameters(0).IsParamArray)
Assert.False(type.GetMember(Of PropertySymbol)("P2").Parameters(0).IsParamArray)
Assert.False(type.GetMember(Of PropertySymbol)("P3").Parameters(0).IsParamArray)
Assert.True(type.GetMember(Of PropertySymbol)("P4").Parameters(0).IsParamArray)
Assert.True(type.GetMember(Of PropertySymbol)("P5").Parameters(0).IsParamArray)
End Sub
''' <summary>
''' OptionCompare must be consistent between accessor parameters.
''' Note: Dev11 does not require this.
''' </summary>
<Fact()>
Public Sub DifferentAccessorSignatures_OptionCompare()
Dim ilSource = <![CDATA[
.assembly extern Microsoft.VisualBasic { .ver 10:0:0:0 .publickeytoken = (B0 3F 5F 7F 11 D5 0A 3A ) }
.class public A
{
.method public instance object get_NoOptionCompare(object i)
{
ldnull
ret
}
.method public instance void set_NoOptionCompare(object i, object v)
{
ret
}
.method public instance object get_OptionCompare(object i)
{
.param [1]
.custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute::.ctor() = ( 01 00 00 00 )
ldnull
ret
}
.method public instance void set_OptionCompare(object i, object v)
{
.param [1]
.custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.OptionCompareAttribute::.ctor() = ( 01 00 00 00 )
ret
}
// OptionCompare on both accessors.
.property instance object P1(object)
{
.get instance object A::get_OptionCompare(object)
.set instance void A::set_OptionCompare(object, object)
}
// OptionCompare on getter only.
.property instance object P2(object)
{
.get instance object A::get_OptionCompare(object)
.set instance void A::set_NoOptionCompare(object, object)
}
// OptionCompare on setter only.
.property instance object P3(object)
{
.get instance object A::get_NoOptionCompare(object)
.set instance void A::set_OptionCompare(object, object)
}
// OptionCompare on readonly property.
.property instance object P4(object)
{
.get instance object A::get_OptionCompare(object)
}
// OptionCompare on writeonly property.
.property instance object P5(object)
{
.set instance void A::set_OptionCompare(object, object)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As A)
Dim v As Object = Nothing
v = o.P1(v)
o.P1(v) = v
v = o.P2(v)
o.P2(v) = v
v = o.P3(v)
o.P3(v) = v
v = o.P4(v)
o.P5(v) = v
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30643: Property 'A.P2(i As Object)' is of an unsupported type.
v = o.P2(v)
~~
BC30643: Property 'A.P2(i As Object)' is of an unsupported type.
o.P2(v) = v
~~
BC30643: Property 'A.P3(i As Object)' is of an unsupported type.
v = o.P3(v)
~~
BC30643: Property 'A.P3(i As Object)' is of an unsupported type.
o.P3(v) = v
~~
</expected>)
Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A")
Assert.True(type.GetMember(Of PropertySymbol)("P1").Parameters(0).HasOptionCompare)
Assert.False(type.GetMember(Of PropertySymbol)("P2").Parameters(0).HasOptionCompare)
Assert.False(type.GetMember(Of PropertySymbol)("P3").Parameters(0).HasOptionCompare)
Assert.True(type.GetMember(Of PropertySymbol)("P4").Parameters(0).HasOptionCompare)
Assert.True(type.GetMember(Of PropertySymbol)("P5").Parameters(0).HasOptionCompare)
End Sub
<Fact()>
Public Sub OptionalParameterValues()
Dim source1 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Imports System
Public Class A
Public ReadOnly Property P(x As Integer, Optional y As Integer = 1) As Integer
Get
Console.WriteLine("get_P: {0}", y)
Return 0
End Get
End Property
Public WriteOnly Property Q(x As Integer, Optional y As Integer = 2) As Integer
Set(value As Integer)
Console.WriteLine("set_Q: {0}", y)
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim compilation1 = CreateCompilationWithMscorlib40(source1)
Dim reference1 = MetadataReference.CreateFromImage(compilation1.EmitToArray())
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub Main()
Dim o As A = New A()
o.Q(2) = o.P(1)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompileAndVerify(source2, references:={reference1}, expectedOutput:=<![CDATA[
get_P: 1
set_Q: 2
]]>)
End Sub
<Fact()>
Public Sub DifferentAccessorSignatures_Optional()
Dim ilSource = <![CDATA[
.class public A
{
.method public instance object get_NoOpt(object x, object y)
{
.param[2] = int32(1)
ldnull
ret
}
.method public instance void set_NoOpt(object x, object y, object v)
{
ret
}
.method public instance object get_Opt(object x, [opt] object y)
{
.param[2] = int32(1)
ldnull
ret
}
.method public instance void set_Opt(object x, [opt] object y, object v)
{
.param[2] = int32(1)
ret
}
// Opt on both accessors.
.property instance object P1(object, object)
{
.get instance object A::get_Opt(object, object)
.set instance void A::set_Opt(object, object, object)
}
// Opt on getter only.
.property instance object P2(object, object)
{
.get instance object A::get_Opt(object, object)
.set instance void A::set_NoOpt(object, object, object)
}
// Opt on setter only.
.property instance object P3(object, object)
{
.get instance object A::get_NoOpt(object, object)
.set instance void A::set_Opt(object, object, object)
}
// Opt on readonly property.
.property instance object P4(object, object)
{
.get instance object A::get_Opt(object, object)
}
// Opt on writeonly property.
.property instance object P5(object, object)
{
.set instance void A::set_Opt(object, object, object)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As A)
Dim v As Object = Nothing
v = o.P1(v)
o.P1(v) = v
v = o.P2(v)
o.P2(v) = v
v = o.P3(v)
o.P3(v) = v
v = o.P4(v)
o.P5(v) = v
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'y' of 'Public Property P2(x As Object, y As Object) As Object'.
v = o.P2(v)
~~
BC30455: Argument not specified for parameter 'y' of 'Public Property P2(x As Object, y As Object) As Object'.
o.P2(v) = v
~~
BC30455: Argument not specified for parameter 'y' of 'Public Property P3(x As Object, y As Object) As Object'.
v = o.P3(v)
~~
BC30455: Argument not specified for parameter 'y' of 'Public Property P3(x As Object, y As Object) As Object'.
o.P3(v) = v
~~
</expected>)
Dim defaultValue = ConstantValue.Create(1)
Dim type = compilation.GlobalNamespace.GetMember(Of NamedTypeSymbol)("A")
Dim parameter As ParameterSymbol
parameter = type.GetMember(Of PropertySymbol)("P1").Parameters(1)
Assert.True(parameter.IsOptional)
Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue)
parameter = type.GetMember(Of PropertySymbol)("P2").Parameters(1)
Assert.False(parameter.IsOptional)
Assert.Null(parameter.ExplicitDefaultConstantValue)
parameter = type.GetMember(Of PropertySymbol)("P3").Parameters(1)
Assert.False(parameter.IsOptional)
Assert.Null(parameter.ExplicitDefaultConstantValue)
parameter = type.GetMember(Of PropertySymbol)("P4").Parameters(1)
Assert.True(parameter.IsOptional)
Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue)
parameter = type.GetMember(Of PropertySymbol)("P5").Parameters(1)
Assert.True(parameter.IsOptional)
Assert.Equal(parameter.ExplicitDefaultConstantValue, defaultValue)
End Sub
<WorkItem(545959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545959")>
<Fact()>
Public Sub DistinctOptionalParameterValues()
Dim ilSource = <![CDATA[
.class abstract public A
{
.custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = {string('P')}
.method public hidebysig specialname rtspecialname instance void .ctor()
{
ret
}
.method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y)
{
.param[2] = int32(1)
}
.method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v)
{
.param[2] = int32(2)
}
.property instance int32 P(int32, int32)
{
.get instance int32 A::get_P(int32, int32)
.set instance void A::set_P(int32, int32, int32)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><)
End Sub
Sub [ByRef](ByRef o As Integer)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, {reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'.
a(0) = a(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'.
a(0) = a(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'.
a(1) += 1
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Default Property P(x As Integer, y As Integer) As Integer'.
[ByRef](a.P(2))
~
</expected>)
End Sub
<WorkItem(545959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545959")>
<Fact()>
Public Sub DistinctOptionalParameterValues_BadValue()
Dim ilSource = <![CDATA[
.class abstract public A
{
.method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y)
{
.param[2] = ""
}
.method public abstract virtual instance void set_P(int32 x, [opt] int32 y, int32 v)
{
.param[2] = int32(1)
}
.method public abstract virtual instance int32 get_Q(int32 x, [opt] int32 y)
{
.param[2] = int32(2)
}
.method public abstract virtual instance void set_Q(int32 x, [opt] int32 y, int32 v)
{
.param[2] = ""
}
// Bad getter default value.
.property instance int32 P(int32, int32)
{
.get instance int32 A::get_P(int32, int32)
.set instance void A::set_P(int32, int32, int32)
}
// Bad setter default value.
.property instance int32 Q(int32, int32)
{
.get instance int32 A::get_Q(int32, int32)
.set instance void A::set_Q(int32, int32, int32)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As A)
o.P(1) = o.P(0)
o.P(2) += 1
o.P(3, 0) += 1
o.Q(1) = o.Q(0)
o.Q(2) += 1
o.Q(3, 0) += 1
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, {reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(1) = o.P(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(1) = o.P(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(2) += 1
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(1) = o.Q(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(1) = o.Q(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(2) += 1
~
</expected>)
End Sub
<WorkItem(545959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545959")>
<Fact()>
Public Sub DistinctOptionalParameterValues_AdditionalOptional()
Dim ilSource = <![CDATA[
.class abstract public A
{
.method public abstract virtual instance int32 get_P(int32 x, [opt] int32 y)
{
.param[2] = int32(1)
}
.method public abstract virtual instance void set_P(int32 x, int32 y, int32 v)
{
}
.method public abstract virtual instance int32 get_Q(int32 x, int32 y)
{
}
.method public abstract virtual instance void set_Q(int32 x, [opt] int32 y, int32 v)
{
.param[2] = int32(2)
}
// Optional parameter in getter.
.property instance int32 P(int32, int32)
{
.get instance int32 A::get_P(int32, int32)
.set instance void A::set_P(int32, int32, int32)
}
// Optional parameter in setter.
.property instance int32 Q(int32, int32)
{
.get instance int32 A::get_Q(int32, int32)
.set instance void A::set_Q(int32, int32, int32)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><)
[ByRef](o.P(5))
o.Q(1) = o.Q(0)
o.Q(2) += 1
o.Q(3, 0) += 1
[ByVal](o.Q(4))
[ByRef](o.Q(5))
End Sub
Sub [ByVal](ByVal o As Integer)
End Sub
Sub [ByRef](ByRef o As Integer)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, {reference})
compilation.AssertTheseDiagnostics(
<expected>
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(1) = o.P(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(1) = o.P(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
o.P(2) += 1
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
[ByVal](o.P(4))
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property P(x As Integer, y As Integer) As Integer'.
[ByRef](o.P(5))
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(1) = o.Q(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(1) = o.Q(0)
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
o.Q(2) += 1
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
[ByVal](o.Q(4))
~
BC30455: Argument not specified for parameter 'y' of 'Public MustOverride Overrides Property Q(x As Integer, y As Integer) As Integer'.
[ByRef](o.Q(5))
~
</expected>)
End Sub
''' <summary>
''' Signatures where the property value type
''' does not match the getter return type.
''' </summary>
<WorkItem(546476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546476")>
<Fact()>
Public Sub DifferentSignatures_PropertyType()
Dim source1 = <![CDATA[
.class public A { }
.class public B1 extends A { }
.class public B2 extends A { }
.class public C
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
.method public instance class A get_A() { ldnull ret }
.method public instance class B1 get_B1() { ldnull ret }
.method public instance class B2 get_B2() { ldnull ret }
.method public instance void set_A(class A v) { ret }
.method public instance void set_B1(class B1 v) { ret }
.property class A P1()
{
.get instance class B1 C::get_B1()
.set instance void C::set_A(class A v)
}
.property class B1 P2()
{
.get instance class A C::get_A()
.set instance void C::set_B1(class B1 v)
}
.property class B1 P3()
{
.get instance class B2 C::get_B2()
.set instance void C::set_B1(class B1 v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M1(o As C)
Dim v As B1
v = o.P1
v = o.P2
v = o.P3
o.P1 = v
o.P2 = v
o.P3 = v
M2(o.P1)
M2(o.P2)
M2(o.P3)
M3(o.P1)
M3(o.P2)
M3(o.P3)
End Sub
Sub M2(o As B1)
End Sub
Sub M3(ByRef o As B1)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
v = o.P2
~~~~
BC30311: Value of type 'B2' cannot be converted to 'B1'.
v = o.P3
~~~~
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
M2(o.P2)
~~~~
BC30311: Value of type 'B2' cannot be converted to 'B1'.
M2(o.P3)
~~~~
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
M3(o.P2)
~~~~
BC30311: Value of type 'B2' cannot be converted to 'B1'.
M3(o.P3)
~~~~
]]></errors>)
End Sub
''' <summary>
''' Signatures where the property value type
''' does not match the setter value type.
''' </summary>
<WorkItem(546476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546476")>
<Fact()>
Public Sub DifferentSignatures_PropertyType_2()
Dim source1 = <![CDATA[
.class public A { }
.class public B1 extends A { }
.class public B2 extends A { }
.class public C
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
.method public instance class A get_A() { ldnull ret }
.method public instance class B1 get_B1() { ldnull ret }
.method public instance void set_A(class A v) { ret }
.method public instance void set_B1(class B1 v) { ret }
.method public instance void set_B2(class B2 v) { ret }
.property class A P1()
{
.get instance class A C::get_A()
.set instance void C::set_B1(class B1 v)
}
.property class B1 P2()
{
.get instance class B1 C::get_B1()
.set instance void C::set_A(class A v)
}
.property class B1 P3()
{
.get instance class B1 C::get_B1()
.set instance void C::set_B2(class B2 v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M1(o As C)
Dim v As B1
v = o.P1
v = o.P2
v = o.P3
o.P1 = v
o.P2 = v
o.P3 = v
M2(o.P1)
M2(o.P2)
M2(o.P3)
M3(o.P1)
M3(o.P2)
M3(o.P3)
End Sub
Sub M2(o As B1)
End Sub
Sub M3(ByRef o As B1)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
v = o.P1
~~~~
BC30311: Value of type 'B1' cannot be converted to 'B2'.
o.P3 = v
~
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
M2(o.P1)
~~~~
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B1'.
M3(o.P1)
~~~~
BC33037: Cannot copy the value of 'ByRef' parameter 'o' back to the matching argument because type 'B1' cannot be converted to type 'B2'.
M3(o.P3)
~~~~
]]></errors>)
End Sub
''' <summary>
''' Signatures where the property value type does not
''' match the accessors, used in compound assignment.
''' </summary>
<WorkItem(546476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546476")>
<Fact()>
Public Sub DifferentSignatures_PropertyType_3()
Dim source1 = <![CDATA[
.class public C
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
.method public instance int32 get_P() { ldnull ret }
.method public instance void set_P(int32 v) { ret }
.method public instance object get_Q() { ldnull ret }
.method public instance void set_Q(object v) { ret }
.property object P()
{
.get instance int32 C::get_P()
.set instance void C::set_P(int32 v)
}
.property int32 Q()
{
.get instance object C::get_Q()
.set instance void C::set_Q(object v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As C)
o.P += 1
o.Q += 1
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30038: Option Strict On prohibits operands of type Object for operator '+'.
o.Q += 1
~~~
]]></errors>)
End Sub
''' <summary>
''' Getter return type is used for type inference.
''' Note: Dev11 uses the property type rather than getter.
''' </summary>
<WorkItem(546476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546476")>
<Fact()>
Public Sub DifferentSignatures_PropertyType_4()
Dim source1 = <![CDATA[
.class public A { }
.class public B extends A { }
.class public C
{
.method public hidebysig specialname rtspecialname instance void .ctor() { ret }
.method public instance class A get_A() { ldnull ret }
.method public instance class B get_B() { ldnull ret }
.method public instance void set_A(class A v) { ret }
.method public instance void set_B(class B v) { ret }
.property class A P1()
{
.get instance class A C::get_A()
.set instance void C::set_B(class B v)
}
.property class A P2()
{
.get instance class B C::get_B()
.set instance void C::set_A(class A v)
}
.property class B P3()
{
.get instance class A C::get_A()
.set instance void C::set_B(class B v)
}
.property class B P4()
{
.get instance class B C::get_B()
.set instance void C::set_A(class A v)
}
}
]]>.Value
Dim reference1 = CompileIL(source1)
Dim source2 =
<compilation>
<file name="c.vb"><![CDATA[
Option Strict On
Module M
Sub M(o As C)
Dim v As B
v = F1(o.P1)
v = F1(o.P2)
v = F1(o.P3)
v = F1(o.P4)
v = F2(o.P1)
v = F2(o.P2)
v = F2(o.P3)
v = F2(o.P4)
End Sub
Function F1(Of T)(o As T) As T
Return Nothing
End Function
Function F2(Of T)(ByRef o As T) As T
Return Nothing
End Function
End Module
]]>
</file>
</compilation>
Dim compilation2 = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(source2, {reference1})
compilation2.AssertTheseDiagnostics(<errors><![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B'.
v = F1(o.P1)
~~~~~~~~
BC30512: Option Strict On disallows implicit conversions from 'A' to 'B'.
v = F1(o.P3)
~~~~~~~~
BC32029: Option Strict On disallows narrowing from type 'A' to type 'B' in copying the value of 'ByRef' parameter 'o' back to the matching argument.
v = F2(o.P1)
~~~~
BC32029: Option Strict On disallows narrowing from type 'A' to type 'B' in copying the value of 'ByRef' parameter 'o' back to the matching argument.
v = F2(o.P3)
~~~~
]]></errors>)
End Sub
<Fact()>
Public Sub ByRefType()
Dim ilSource = <![CDATA[
.class public A
{
.method public instance object& get_P() { ldnull ret }
.method public instance void set_P(object& v) { ret }
.property instance object& P()
{
.get instance object& A::get_P()
.set instance void A::set_P(object&)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As A)
Dim v As Object
v = o.P
o.P = v
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertTheseDiagnostics()
End Sub
<Fact()>
Public Sub ByRefParameter()
Dim ilSource = <![CDATA[
.class public A
{
.method public instance object get_P(object& i) { ldnull ret }
.method public instance void set_P(object& i, object v) { ret }
.property instance object P(object&)
{
.get instance object A::get_P(object&)
.set instance void A::set_P(object&, object)
}
}
]]>.Value
Dim reference = CompileIL(ilSource)
Dim vbSource =
<compilation>
<file name="c.vb"><![CDATA[
Module M
Sub M(o As A)
Dim v As Object
v = o.P(Nothing)
o.P(Nothing) = v
o.P(v) = o.P(v)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(vbSource, references:={reference})
compilation.AssertNoErrors()
Dim compilationVerifier = CompileAndVerify(compilation)
compilationVerifier.VerifyIL("M.M(A)",
<![CDATA[
{
// Code size 68 (0x44)
.maxstack 4
.locals init (Object V_0, //v
Object V_1,
Object V_2)
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: stloc.1
IL_0003: ldloca.s V_1
IL_0005: callvirt "Function A.get_P(ByRef Object) As Object"
IL_000a: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000f: stloc.0
IL_0010: ldarg.0
IL_0011: ldnull
IL_0012: stloc.1
IL_0013: ldloca.s V_1
IL_0015: ldloc.0
IL_0016: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_001b: callvirt "Sub A.set_P(ByRef Object, Object)"
IL_0020: ldarg.0
IL_0021: ldloc.0
IL_0022: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0027: stloc.1
IL_0028: ldloca.s V_1
IL_002a: ldarg.0
IL_002b: ldloc.0
IL_002c: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0031: stloc.2
IL_0032: ldloca.s V_2
IL_0034: callvirt "Function A.get_P(ByRef Object) As Object"
IL_0039: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_003e: callvirt "Sub A.set_P(ByRef Object, Object)"
IL_0043: ret
}
]]>)
End Sub
<Fact()>
Public Sub MissingSystemTypes_Property()
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="a.vb"><![CDATA[
Interface I
ReadOnly Property P As Object
WriteOnly Property Q As Object
End Interface
]]></file>
</compilation>, references:=Nothing)
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'System.Object' is not defined.
ReadOnly Property P As Object
~~~~~~
BC30002: Type 'System.Void' is not defined.
WriteOnly Property Q As Object
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'System.Object' is not defined.
WriteOnly Property Q As Object
~~~~~~
]]></errors>)
End Sub
<WorkItem(530418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530418")>
<WorkItem(101153, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=101153")>
<Fact>
Public Sub MissingSystemTypes_AutoProperty()
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation name="MissingSystemTypes_AutoProperty">
<file name="a.vb"><![CDATA[
Class C
Property P As Object
End Class
]]></file>
</compilation>, references:=Nothing)
Const bug101153IsFixed = False
If bug101153IsFixed Then
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue' is not defined.
Property P As Object
~
BC30002: Type 'System.Void' is not defined.
Class C
~~~~~~~~
BC31091: Import of type 'Object' from assembly or module 'C.dll' failed.
Class C
~
BC30002: Type 'System.Void' is not defined.
Property P As Object
~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'System.Object' is not defined.
Property P As Object
~~~~~~
]]></errors>)
Else
compilation.AssertTheseDiagnostics(<errors><![CDATA[
BC30002: Type 'System.Void' is not defined.
Class C
~~~~~~~~
BC31091: Import of type 'Object' from assembly or module 'MissingSystemTypes_AutoProperty.dll' failed.
Class C
~
BC30002: Type 'System.Void' is not defined.
Property P As Object
~~~~~~~~~~~~~~~~~~~~
BC30002: Type 'System.Object' is not defined.
Property P As Object
~~~~~~
]]></errors>)
End If
End Sub
<WorkItem(531292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531292")>
<Fact()>
Public Sub Bug17897()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Module Program
Property Test0()
Protected Get
Return Nothing
End Get
Set(ByVal Value)
End Set
End Property
Protected Sub Test1()
End Sub
Protected Property Test2 As Integer
Property Test3()
Get
Return Nothing
End Get
Protected Set(ByVal Value)
End Set
End Property
Protected Test4 As Integer
Protected Class Test5
End Class
Protected Event Test6 As Action
Protected Delegate Sub Test7()
Sub Main(args As String())
End Sub
End Module
]]></file>
</compilation>)
compilation.AssertTheseDiagnostics(
<errors><![CDATA[
BC30503: Properties in a Module cannot be declared 'Protected'.
Protected Get
~~~~~~~~~
BC30433: Methods in a Module cannot be declared 'Protected'.
Protected Sub Test1()
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Protected'.
Protected Property Test2 As Integer
~~~~~~~~~
BC30503: Properties in a Module cannot be declared 'Protected'.
Protected Set(ByVal Value)
~~~~~~~~~
BC30593: Variables in Modules cannot be declared 'Protected'.
Protected Test4 As Integer
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Class Test5
~~~~~~~~~
BC30434: Events in a Module cannot be declared 'Protected'.
Protected Event Test6 As Action
~~~~~~~~~
BC30735: Type in a Module cannot be declared 'Protected'.
Protected Delegate Sub Test7()
~~~~~~~~~
]]></errors>)
End Sub
''' <summary>
''' When the output type is .winmdobj properties should emit put_Property methods instead
''' of set_Property methods.
''' </summary>
<Fact()>
Public Sub WinRtPropertySet()
Dim libSrc =
<compilation>
<file name="c.vb"><![CDATA[
Public Class C
Public Dim Abacking As Integer
Public Property A As Integer
Get
Return Abacking
End Get
Set
Abacking = value
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim getValidator =
Function(expectedMembers As String())
Return Sub(m As ModuleSymbol)
Dim actualMembers = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers().ToArray()
AssertEx.SetEqual((From s In actualMembers
Select s.Name), expectedMembers)
End Sub
End Function
Dim verify =
Sub(winmd As Boolean, expected As String())
Dim validator = getValidator(expected)
' We should see the same members from both source and metadata
Dim verifier = CompileAndVerify(
libSrc,
sourceSymbolValidator:=validator,
symbolValidator:=validator,
options:=If(winmd, TestOptions.ReleaseWinMD, TestOptions.ReleaseDll))
verifier.VerifyDiagnostics()
End Sub
' Test winmd
verify(True, New String() {
"Abacking",
"A",
"get_A",
"put_A",
WellKnownMemberNames.InstanceConstructorName})
' Test normal
verify(False, New String() {
"Abacking",
"A",
"get_A",
"set_A",
WellKnownMemberNames.InstanceConstructorName})
End Sub
<Fact()>
Public Sub WinRtAnonymousProperty()
Dim src = <compilation>
<file name="c.vb">
<![CDATA[
Imports System
Class C
Public Property P = New With {.Name = "prop"}
End Class
]]>
</file>
</compilation>
Dim srcValidator =
Sub(m As ModuleSymbol)
Dim members = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMembers()
AssertEx.SetEqual((From member In members Select member.Name),
{WellKnownMemberNames.InstanceConstructorName,
"_P",
"get_P",
"put_P",
"P"})
End Sub
Dim mdValidator =
Sub(m As ModuleSymbol)
Dim members = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("VB$AnonymousType_0").GetMembers()
AssertEx.SetEqual((From member In members Select member.Name),
{"get_Name",
"put_Name",
WellKnownMemberNames.InstanceConstructorName,
"ToString",
"Name"})
End Sub
Dim verifier = CompileAndVerify(src,
allReferences:={MscorlibRef_v4_0_30316_17626},
options:=TestOptions.ReleaseWinMD,
sourceSymbolValidator:=srcValidator,
symbolValidator:=mdValidator)
End Sub
''' <summary>
''' Accessor type names that conflict should cause the appropriate diagnostic
''' (i.e., set_ for dll, put_ for winmdobj)
''' </summary>
<Fact()>
Public Sub WinRtPropertyAccessorNameConflict()
Dim libSrc =
<compilation>
<file name="c.vb">
<![CDATA[
Public Class C
Public Property A as Integer
Public Sub put_A(value As Integer)
End Sub
Public Sub set_A(value as Integer)
End Sub
End Class
]]>
</file>
</compilation>
Dim comp = CreateCompilationWithMscorlib40(libSrc, OutputKind.DynamicallyLinkedLibrary)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "A").WithArguments("property", "A", "set_A", "class", "C"))
comp = CreateCompilationWithMscorlib40(libSrc, OutputKind.WindowsRuntimeMetadata)
comp.VerifyDiagnostics(
Diagnostic(ERRID.ERR_SynthMemberClashesWithMember5, "A").WithArguments("property", "A", "put_A", "class", "C"))
End Sub
#Region "Helpers"
Private Sub VerifyMethodsAndAccessorsSame(type As NamedTypeSymbol, [property] As PropertySymbol)
VerifyMethodAndAccessorSame(type, [property], [property].GetMethod)
VerifyMethodAndAccessorSame(type, [property], [property].SetMethod)
End Sub
Private Sub VerifyMethodAndAccessorSame(type As NamedTypeSymbol, [property] As PropertySymbol, accessor As MethodSymbol)
Assert.NotNull(accessor)
Assert.Same(type, accessor.ContainingType)
Assert.Same(type, accessor.ContainingSymbol)
Dim method = type.GetMembers(accessor.Name).Single()
Assert.NotNull(method)
Assert.Equal(accessor, method)
Dim isAccessor = accessor.MethodKind = MethodKind.PropertyGet OrElse accessor.MethodKind = MethodKind.PropertySet
Assert.True(isAccessor)
Assert.NotNull(accessor.AssociatedSymbol)
Assert.Same(accessor.AssociatedSymbol, [property])
End Sub
Private Shared Sub CheckPropertyAccessibility([property] As PropertySymbol, propertyAccessibility As Accessibility, getterAccessibility As Accessibility, setterAccessibility As Accessibility)
Dim type = [property].Type
Assert.NotEqual(type.PrimitiveTypeCode, Cci.PrimitiveTypeCode.Void)
Assert.Equal(propertyAccessibility, [property].DeclaredAccessibility)
CheckPropertyAccessorAccessibility([property], propertyAccessibility, [property].GetMethod, getterAccessibility)
CheckPropertyAccessorAccessibility([property], propertyAccessibility, [property].SetMethod, setterAccessibility)
End Sub
Private Shared Sub CheckPropertyAccessorAccessibility([property] As PropertySymbol, propertyAccessibility As Accessibility, accessor As MethodSymbol, accessorAccessibility As Accessibility)
If accessor Is Nothing Then
Assert.Equal(accessorAccessibility, Accessibility.NotApplicable)
Else
Dim containingType = [property].ContainingType
Assert.Same([property], accessor.AssociatedSymbol)
Assert.Same(containingType, accessor.ContainingType)
Assert.Same(containingType, accessor.ContainingSymbol)
Dim method = containingType.GetMembers(accessor.Name).Single()
Assert.Same(method, accessor)
Assert.Equal(accessorAccessibility, accessor.DeclaredAccessibility)
End If
End Sub
Private Shared Sub VerifyAutoProperty(type As NamedTypeSymbol, name As String, declaredAccessibility As Accessibility, isFromSource As Boolean)
Dim [property] = type.GetMembers(name).OfType(Of PropertySymbol)().SingleOrDefault()
Assert.NotNull([property])
Assert.Equal([property].DeclaredAccessibility, declaredAccessibility)
Dim field = type.GetMembers("_" + name).OfType(Of FieldSymbol)().SingleOrDefault()
If isFromSource Then
Dim sourceProperty = DirectCast([property], SourcePropertySymbol)
Assert.True(sourceProperty.IsAutoProperty)
Assert.NotNull(field)
Assert.Equal(field.DeclaredAccessibility, Accessibility.Private)
Assert.Equal(field.Type, [property].Type)
Else
Dim getterAttribute = [property].GetMethod.GetAttributes().Single()
Assert.Equal("CompilerGeneratedAttribute", getterAttribute.AttributeClass.Name)
Assert.Empty(getterAttribute.ConstructorArguments)
Dim setterAttribute = [property].SetMethod.GetAttributes().Single()
Assert.Equal("CompilerGeneratedAttribute", setterAttribute.AttributeClass.Name)
Assert.Empty(setterAttribute.ConstructorArguments)
Assert.Null(field)
End If
End Sub
Private Sub VerifyAccessor(accessor As MethodSymbol, associatedProperty As PEPropertySymbol, methodKind As MethodKind)
Assert.NotNull(accessor)
Assert.Same(accessor.AssociatedSymbol, associatedProperty)
Assert.Equal(accessor.MethodKind, methodKind)
If associatedProperty IsNot Nothing Then
Dim method = If((methodKind = MethodKind.PropertyGet), associatedProperty.GetMethod, associatedProperty.SetMethod)
Assert.Same(accessor, method)
End If
End Sub
Private Sub VerifyPropertyParams(propertySymbol As PropertySymbol, expectedParams As String(,))
For index = 0 To expectedParams.Length
Assert.Equal(propertySymbol.Parameters(index).Name, expectedParams(index, 0))
Assert.Equal(propertySymbol.Parameters(index).Type.Name, expectedParams(index, 1))
Next
End Sub
Private Shared Sub CheckPropertyExplicitImplementation([class] As NamedTypeSymbol, classProperty As PropertySymbol, interfaceProperty As PropertySymbol)
Dim interfacePropertyGetter = interfaceProperty.GetMethod
Assert.NotNull(interfacePropertyGetter)
Dim interfacePropertySetter = interfaceProperty.SetMethod
Assert.NotNull(interfacePropertySetter)
Assert.Equal(interfaceProperty, classProperty.ExplicitInterfaceImplementations.Single())
Dim classPropertyGetter = classProperty.GetMethod
Assert.NotNull(classPropertyGetter)
Dim classPropertySetter = classProperty.SetMethod
Assert.NotNull(classPropertySetter)
Assert.Equal(interfacePropertyGetter, classPropertyGetter.ExplicitInterfaceImplementations.Single())
Assert.Equal(interfacePropertySetter, classPropertySetter.ExplicitInterfaceImplementations.Single())
Dim typeDef = DirectCast([class], Cci.ITypeDefinition)
Dim [module] = New PEAssemblyBuilder(DirectCast([class].ContainingAssembly, SourceAssemblySymbol), EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable(Of ResourceDescription)())
Dim context = New EmitContext([module], Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True)
Dim explicitOverrides = typeDef.GetExplicitImplementationOverrides(context)
Assert.Equal(2, explicitOverrides.Count())
Assert.True(explicitOverrides.All(Function(override) [class] Is override.ContainingType))
' We're not actually asserting that the overrides are in this order - set comparison just seems like overkill for two elements
Dim getterOverride = explicitOverrides.First()
Assert.Equal(classPropertyGetter, getterOverride.ImplementingMethod)
Assert.Equal(interfacePropertyGetter.ContainingType, getterOverride.ImplementedMethod.GetContainingType(context))
Assert.Equal(interfacePropertyGetter.Name, getterOverride.ImplementedMethod.Name)
Dim setterOverride = explicitOverrides.Last()
Assert.Equal(classPropertySetter, setterOverride.ImplementingMethod)
Assert.Equal(interfacePropertySetter.ContainingType, setterOverride.ImplementedMethod.GetContainingType(context))
Assert.Equal(interfacePropertySetter.Name, setterOverride.ImplementedMethod.Name)
context.Diagnostics.Verify()
End Sub
Private Shared Sub VerifyAccessibility([property] As PEPropertySymbol, propertyAccessibility As Accessibility, getAccessibility As Accessibility, setAccessibility As Accessibility)
Assert.Equal([property].DeclaredAccessibility, propertyAccessibility)
VerifyAccessorAccessibility([property].GetMethod, getAccessibility)
VerifyAccessorAccessibility([property].SetMethod, setAccessibility)
End Sub
Private Shared Sub VerifyAccessorAccessibility(accessor As MethodSymbol, accessorAccessibility As Accessibility)
If accessorAccessibility = Accessibility.NotApplicable Then
Assert.Null(accessor)
Else
Assert.NotNull(accessor)
Assert.Equal(accessor.DeclaredAccessibility, accessorAccessibility)
End If
End Sub
Private Function CompileWithCustomPropertiesAssembly(source As XElement, Optional options As VisualBasicCompilationOptions = Nothing) As VisualBasicCompilation
Return CreateCompilationWithMscorlib40AndReferences(source, {s_propertiesDll}, options)
End Function
Private Shared ReadOnly s_propertiesDll As MetadataReference = TestReferences.SymbolsTests.Properties
Private Shared Sub VerifyPropertiesParametersCount([property] As PropertySymbol, expectedCount As Integer)
Assert.Equal([property].Parameters.Length, expectedCount)
If [property].GetMethod IsNot Nothing Then
Assert.Equal([property].GetMethod.Parameters.Length, expectedCount)
End If
If [property].SetMethod IsNot Nothing Then
Assert.Equal([property].SetMethod.Parameters.Length, expectedCount + 1)
End If
End Sub
Private Shared Sub VerifyPropertiesParametersTypes([property] As PropertySymbol, ParamArray expectedTypes() As TypeSymbol)
Assert.Equal([property].SetMethod.Parameters.Last().Type, [property].Type)
Assert.True((From param In [property].Parameters Select param.Type).SequenceEqual(expectedTypes))
If [property].GetMethod IsNot Nothing Then
Assert.True((From param In [property].GetMethod.Parameters Select param.Type).SequenceEqual(expectedTypes))
End If
If [property].SetMethod IsNot Nothing Then
Assert.True((From param In [property].SetMethod.Parameters Select param.Type).Take([property].Parameters.Length - 1).SequenceEqual(expectedTypes))
End If
End Sub
Private Shared Sub VerifyNoDiagnostics(result As EmitResult)
Assert.Equal(String.Empty, String.Join(Environment.NewLine, result.Diagnostics))
End Sub
#End Region
End Class
End Namespace
|
brettfo/roslyn
|
src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Source/PropertyTests.vb
|
Visual Basic
|
apache-2.0
| 278,320
|
' 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 _ilEmitStyle As ILEmitStyle
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 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,
emittingPdb 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)
_method = method
_block = boundBody
_builder = builder
_module = moduleBuilder
_diagnostics = diagnostics
'Always optimize synthesized methods that don't contain user code.
If Not method.GenerateDebugInfo Then
_ilEmitStyle = ILEmitStyle.Release
Else
If optimizations = OptimizationLevel.Debug Then
_ilEmitStyle = ILEmitStyle.Debug
Else
_ilEmitStyle = If(IsDebugPlus(),
ILEmitStyle.DebugFriendlyRelease,
ILEmitStyle.Release)
End If
End If
' 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 through, or changed during EnC.
'
' This setting only affects generating PDB sequence points, it shall Not affect generated IL in any way.
_emitPdbSequencePoints = emittingPdb AndAlso method.GenerateDebugInfo
Try
_block = Optimizer.Optimize(method, boundBody, debugFriendly:=_ilEmitStyle <> ILEmitStyle.Release, stackLocals:=_stackLocals)
Catch ex As BoundTreeVisitor.CancelledByStackGuardException
ex.AddAnError(diagnostics)
_block = boundBody
End Try
_checkCallsForUnsafeJITOptimization = (_method.ImplementationAttributes And MethodSymbol.DisableJITOptimizationFlags) <> MethodSymbol.DisableJITOptimizationFlags
Debug.Assert(Not _module.JITOptimizationIsDisabled(_method))
End Sub
Private Function IsDebugPlus() As Boolean
Return Me._module.Compilation.Options.DebugPlusMode
End Function
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
Try
EmitStatement(_block)
If _unhandledReturn Then
HandleReturn()
End If
If Not _diagnostics.HasAnyErrors Then
_builder.Realize()
End If
Catch e As EmitCancelledException
Debug.Assert(_diagnostics.HasAnyErrors())
End Try
_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 _ilEmitStyle = ILEmitStyle.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 _ilEmitStyle = ILEmitStyle.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
|
VPashkov/roslyn
|
src/Compilers/VisualBasic/Portable/CodeGen/CodeGenerator.vb
|
Visual Basic
|
apache-2.0
| 13,905
|
' 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.IO
Imports System.Reflection.Metadata
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.Metadata.Tools
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBAsyncTests
Inherits BasicTestBase
<WorkItem(1085911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085911")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub SimpleAsyncMethod()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Class C
Shared Async Function M() As Task(Of Integer)
Await Task.Delay(1)
Return 1
End Function
End Class
</file>
</compilation>
Dim v = CompileAndVerify(source, LatestVbReferences, options:=TestOptions.DebugDll)
v.VerifyIL("C.VB$StateMachine_1_M.MoveNext", "
{
// Code size 184 (0xb8)
.maxstack 3
.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_1_M V_4,
System.Exception V_5)
~IL_0000: ldarg.0
IL_0001: ldfld ""C.VB$StateMachine_1_M.$State As Integer""
IL_0006: stloc.1
.try
{
~IL_0007: ldloc.1
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0049
-IL_000e: nop
-IL_000f: ldc.i4.1
IL_0010: call ""Function System.Threading.Tasks.Task.Delay(Integer) As System.Threading.Tasks.Task""
IL_0015: callvirt ""Function System.Threading.Tasks.Task.GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter""
IL_001a: stloc.3
~IL_001b: ldloca.s V_3
IL_001d: call ""Function System.Runtime.CompilerServices.TaskAwaiter.get_IsCompleted() As Boolean""
IL_0022: brtrue.s IL_0067
IL_0024: ldarg.0
IL_0025: ldc.i4.0
IL_0026: dup
IL_0027: stloc.1
IL_0028: stfld ""C.VB$StateMachine_1_M.$State As Integer""
<IL_002d: ldarg.0
IL_002e: ldloc.3
IL_002f: stfld ""C.VB$StateMachine_1_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter""
IL_0034: ldarg.0
IL_0035: ldflda ""C.VB$StateMachine_1_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)""
IL_003a: ldloca.s V_3
IL_003c: ldarg.0
IL_003d: stloc.s V_4
IL_003f: ldloca.s V_4
IL_0041: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter, C.VB$StateMachine_1_M)(ByRef System.Runtime.CompilerServices.TaskAwaiter, ByRef C.VB$StateMachine_1_M)""
IL_0046: nop
IL_0047: leave.s IL_00b7
>IL_0049: ldarg.0
IL_004a: ldc.i4.m1
IL_004b: dup
IL_004c: stloc.1
IL_004d: stfld ""C.VB$StateMachine_1_M.$State As Integer""
IL_0052: ldarg.0
IL_0053: ldfld ""C.VB$StateMachine_1_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter""
IL_0058: stloc.3
IL_0059: ldarg.0
IL_005a: ldflda ""C.VB$StateMachine_1_M.$A0 As System.Runtime.CompilerServices.TaskAwaiter""
IL_005f: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
IL_0065: br.s IL_0067
IL_0067: ldloca.s V_3
IL_0069: call ""Sub System.Runtime.CompilerServices.TaskAwaiter.GetResult()""
IL_006e: nop
IL_006f: ldloca.s V_3
IL_0071: initobj ""System.Runtime.CompilerServices.TaskAwaiter""
-IL_0077: ldc.i4.1
IL_0078: stloc.0
IL_0079: leave.s IL_00a0
}
catch System.Exception
{
~IL_007b: dup
IL_007c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)""
IL_0081: stloc.s V_5
~IL_0083: ldarg.0
IL_0084: ldc.i4.s -2
IL_0086: stfld ""C.VB$StateMachine_1_M.$State As Integer""
IL_008b: ldarg.0
IL_008c: ldflda ""C.VB$StateMachine_1_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)""
IL_0091: ldloc.s V_5
IL_0093: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)""
IL_0098: nop
IL_0099: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()""
IL_009e: leave.s IL_00b7
}
-IL_00a0: ldarg.0
IL_00a1: ldc.i4.s -2
IL_00a3: dup
IL_00a4: stloc.1
IL_00a5: stfld ""C.VB$StateMachine_1_M.$State As Integer""
~IL_00aa: ldarg.0
IL_00ab: ldflda ""C.VB$StateMachine_1_M.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)""
IL_00b0: ldloc.0
IL_00b1: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)""
IL_00b6: nop
IL_00b7: ret
}", sequencePoints:="C+VB$StateMachine_1_M.MoveNext")
' NOTE: No <local> for the return variable "M".
v.VerifyPdb("C+VB$StateMachine_1_M.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_M" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="-1"/>
<slot kind="27" offset="-1"/>
<slot kind="0" offset="-1"/>
<slot kind="33" offset="0"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xe" startLine="5" startColumn="5" endLine="5" endColumn="50" document="1"/>
<entry offset="0xf" startLine="6" startColumn="9" endLine="6" endColumn="28" document="1"/>
<entry offset="0x1b" hidden="true" document="1"/>
<entry offset="0x77" startLine="7" startColumn="9" endLine="7" endColumn="17" document="1"/>
<entry offset="0x7b" hidden="true" document="1"/>
<entry offset="0x83" hidden="true" document="1"/>
<entry offset="0xa0" startLine="8" startColumn="5" endLine="8" endColumn="17" document="1"/>
<entry offset="0xaa" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xb8">
<namespace name="System" importlevel="file"/>
<namespace name="System.Threading.Tasks" importlevel="file"/>
<currentnamespace name=""/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="M"/>
<await yield="0x2d" resume="0x49" declaringType="C+VB$StateMachine_1_M" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(651996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/651996")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub TestAsync()
Dim source =
<compilation>
<file><![CDATA[
Option Strict Off
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Sub Main(args As String())
Test().Wait()
End Sub
Async Function F(ParamArray a() As Integer) As Task(Of Integer)
Await Task.Yield
Return 0
End Function
Async Function Test() As Task
Await F(Await F(
Await F(),
1,
Await F(12)),
Await F(
Await F(Await F(Await F())),
Await F(12)))
End Function
Async Sub S()
Await Task.Yield
End Sub
End Module
]]></file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugDll)
compilation.VerifyPdb("Module1.F",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1" name="F" parameterNames="a">
<customDebugInfo>
<forwardIterator name="VB$StateMachine_1_F"/>
</customDebugInfo>
</method>
</methods>
</symbols>)
compilation.VerifyPdb("Module1+VB$StateMachine_1_F.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1+VB$StateMachine_1_F" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="-1"/>
<slot kind="27" offset="-1"/>
<slot kind="0" offset="-1"/>
<slot kind="33" offset="0"/>
<slot kind="temp"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xe" startLine="11" startColumn="5" endLine="11" endColumn="68" document="1"/>
<entry offset="0xf" startLine="12" startColumn="9" endLine="12" endColumn="25" document="1"/>
<entry offset="0x1e" hidden="true" document="1"/>
<entry offset="0x7a" startLine="13" startColumn="9" endLine="13" endColumn="17" document="1"/>
<entry offset="0x7e" hidden="true" document="1"/>
<entry offset="0x86" hidden="true" document="1"/>
<entry offset="0xa3" startLine="14" startColumn="5" endLine="14" endColumn="17" document="1"/>
<entry offset="0xad" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xbb">
<importsforward declaringType="Module1" methodName="Main" parameterNames="args"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="Module1" methodName="F" parameterNames="a"/>
<await yield="0x30" resume="0x4c" declaringType="Module1+VB$StateMachine_1_F" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
compilation.VerifyPdb("Module1.Test",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1" name="Test">
<customDebugInfo>
<forwardIterator name="VB$StateMachine_2_Test"/>
</customDebugInfo>
</method>
</methods>
</symbols>)
compilation.VerifyPdb("Module1+VB$StateMachine_2_Test.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1+VB$StateMachine_2_Test" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="27" offset="-1"/>
<slot kind="33" offset="0"/>
<slot kind="33" offset="8"/>
<slot kind="33" offset="125"/>
<slot kind="33" offset="38"/>
<slot kind="33" offset="94"/>
<slot kind="temp"/>
<slot kind="temp"/>
<slot kind="33" offset="155"/>
<slot kind="33" offset="205"/>
<slot kind="33" offset="163"/>
<slot kind="33" offset="171"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x5d" startLine="16" startColumn="5" endLine="16" endColumn="34" document="1"/>
<entry offset="0x5e" startLine="17" startColumn="9" endLine="23" endColumn="34" document="1"/>
<entry offset="0x70" hidden="true" document="1"/>
<entry offset="0xf1" hidden="true" document="1"/>
<entry offset="0x176" hidden="true" document="1"/>
<entry offset="0x1f0" hidden="true" document="1"/>
<entry offset="0x269" hidden="true" document="1"/>
<entry offset="0x2e2" hidden="true" document="1"/>
<entry offset="0x363" hidden="true" document="1"/>
<entry offset="0x3e4" hidden="true" document="1"/>
<entry offset="0x463" hidden="true" document="1"/>
<entry offset="0x4bf" startLine="24" startColumn="5" endLine="24" endColumn="17" document="1"/>
<entry offset="0x4c1" hidden="true" document="1"/>
<entry offset="0x4c9" hidden="true" document="1"/>
<entry offset="0x4e6" startLine="24" startColumn="5" endLine="24" endColumn="17" document="1"/>
<entry offset="0x4f0" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x4fd">
<importsforward declaringType="Module1" methodName="Main" parameterNames="args"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="Module1" methodName="Test"/>
<await yield="0x82" resume="0xa2" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x103" resume="0x123" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x188" resume="0x1a7" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x202" resume="0x222" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x27b" resume="0x29b" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x2f4" resume="0x314" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x375" resume="0x395" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x3f6" resume="0x415" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
<await yield="0x475" resume="0x491" declaringType="Module1+VB$StateMachine_2_Test" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
compilation.VerifyPdb("Module1.S",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1" name="S">
<customDebugInfo>
<forwardIterator name="VB$StateMachine_3_S"/>
</customDebugInfo>
</method>
</methods>
</symbols>)
compilation.VerifyPdb("Module1+VB$StateMachine_3_S.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="Module1+VB$StateMachine_3_S" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="27" offset="-1"/>
<slot kind="33" offset="0"/>
<slot kind="temp"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xe" startLine="26" startColumn="5" endLine="26" endColumn="18" document="1"/>
<entry offset="0xf" startLine="27" startColumn="9" endLine="27" endColumn="25" document="1"/>
<entry offset="0x1d" hidden="true" document="1"/>
<entry offset="0x78" startLine="28" startColumn="5" endLine="28" endColumn="12" document="1"/>
<entry offset="0x7a" hidden="true" document="1"/>
<entry offset="0x82" hidden="true" document="1"/>
<entry offset="0x9f" startLine="28" startColumn="5" endLine="28" endColumn="12" document="1"/>
<entry offset="0xa9" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xb6">
<importsforward declaringType="Module1" methodName="Main" parameterNames="args"/>
</scope>
<asyncInfo>
<catchHandler offset="0x7a"/>
<kickoffMethod declaringType="Module1" methodName="S"/>
<await yield="0x2f" resume="0x4a" declaringType="Module1+VB$StateMachine_3_S" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub LocalCapturedInBetweenSuspensionPoints_Debug()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Public Class C
Private Async Function Async_Lambda() As Task
Dim x As Integer = 1
Dim y As Integer = 2
Dim a As Func(Of Integer) = Function() x + y
Await Console.Out.WriteAsync((x + y).ToString)
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
source,
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.DebugDll)
' Goal: We're looking for "$VB$ResumableLocal_$VB$Closure_$0" and "$VB$ResumableLocal_a$1".
compilation.VerifyPdb("C+VB$StateMachine_1_Async_Lambda.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_Async_Lambda" name="MoveNext">
<customDebugInfo>
<hoistedLocalScopes format="portable">
<slot startOffset="0x0" endOffset="0x139"/>
<slot startOffset="0x0" endOffset="0x139"/>
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind="27" offset="-1"/>
<slot kind="33" offset="118"/>
<slot kind="temp"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x11" startLine="5" startColumn="5" endLine="5" endColumn="50" document="1"/>
<entry offset="0x12" hidden="true" document="1"/>
<entry offset="0x1d" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/>
<entry offset="0x29" startLine="7" startColumn="13" endLine="7" endColumn="29" document="1"/>
<entry offset="0x35" startLine="9" startColumn="13" endLine="9" endColumn="53" document="1"/>
<entry offset="0x4c" startLine="11" startColumn="9" endLine="11" endColumn="55" document="1"/>
<entry offset="0x7b" hidden="true" document="1"/>
<entry offset="0xd9" startLine="12" startColumn="9" endLine="12" endColumn="21" document="1"/>
<entry offset="0xea" startLine="13" startColumn="9" endLine="13" endColumn="21" document="1"/>
<entry offset="0xfb" startLine="14" startColumn="5" endLine="14" endColumn="17" document="1"/>
<entry offset="0xfd" hidden="true" document="1"/>
<entry offset="0x105" hidden="true" document="1"/>
<entry offset="0x122" startLine="14" startColumn="5" endLine="14" endColumn="17" document="1"/>
<entry offset="0x12c" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x139">
<importsforward declaringType="C+_Closure$__1-0" methodName="_Lambda$__0"/>
<local name="$VB$ResumableLocal_$VB$Closure_$0" il_index="0" il_start="0x0" il_end="0x139" attributes="0"/>
<local name="$VB$ResumableLocal_a$1" il_index="1" il_start="0x0" il_end="0x139" attributes="0"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="Async_Lambda"/>
<await yield="0x8d" resume="0xab" declaringType="C+VB$StateMachine_1_Async_Lambda" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub LocalCapturedInBetweenSuspensionPoints_Release()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Public Class C
Private Async Function Async_Lambda() As Task
Dim x As Integer = 1
Dim y As Integer = 2
Dim a As Func(Of Integer) = Function() x + y
Await Console.Out.WriteAsync((x + y).ToString)
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
source,
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.ReleaseDll)
' Goal: We're looking for "$VB$ResumableLocal_$VB$Closure_$0" but not "$VB$ResumableLocal_a$1".
compilation.VerifyPdb("C+VB$StateMachine_1_Async_Lambda.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_Async_Lambda" name="MoveNext">
<customDebugInfo>
<hoistedLocalScopes format="portable">
<slot startOffset="0x0" endOffset="0x10f"/>
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xa" hidden="true" document="1"/>
<entry offset="0x15" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/>
<entry offset="0x21" startLine="7" startColumn="13" endLine="7" endColumn="29" document="1"/>
<entry offset="0x2d" startLine="11" startColumn="9" endLine="11" endColumn="55" document="1"/>
<entry offset="0x5c" hidden="true" document="1"/>
<entry offset="0xb3" startLine="12" startColumn="9" endLine="12" endColumn="21" document="1"/>
<entry offset="0xc4" startLine="13" startColumn="9" endLine="13" endColumn="21" document="1"/>
<entry offset="0xd5" startLine="14" startColumn="5" endLine="14" endColumn="17" document="1"/>
<entry offset="0xd7" hidden="true" document="1"/>
<entry offset="0xde" hidden="true" document="1"/>
<entry offset="0xf9" startLine="14" startColumn="5" endLine="14" endColumn="17" document="1"/>
<entry offset="0x103" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x10f">
<importsforward declaringType="C+_Closure$__1-0" methodName="_Lambda$__0"/>
<local name="$VB$ResumableLocal_$VB$Closure_$0" il_index="0" il_start="0x0" il_end="0x10f" attributes="0"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="Async_Lambda"/>
<await yield="0x6e" resume="0x88" declaringType="C+VB$StateMachine_1_Async_Lambda" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(827337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/827337"), WorkItem(836491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/836491")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub LocalNotCapturedInBetweenSuspensionPoints_Debug()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Public Class C
Private Async Function Async_NoLambda() As Task
Dim x As Integer = 1
Dim y As Integer = 2
Await Console.Out.WriteAsync((x + y).ToString)
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
source,
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.DebugDll)
' Goal: We're looking for the single-mangled names "$VB$ResumableLocal_x$1" and "$VB$ResumableLocal_y$2".
compilation.VerifyPdb("C+VB$StateMachine_1_Async_NoLambda.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_Async_NoLambda" name="MoveNext">
<customDebugInfo>
<hoistedLocalScopes format="portable">
<slot startOffset="0x0" endOffset="0xf6"/>
<slot startOffset="0x0" endOffset="0xf6"/>
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind="27" offset="-1"/>
<slot kind="33" offset="62"/>
<slot kind="temp"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xe" startLine="5" startColumn="5" endLine="5" endColumn="52" document="1"/>
<entry offset="0xf" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/>
<entry offset="0x16" startLine="7" startColumn="13" endLine="7" endColumn="29" document="1"/>
<entry offset="0x1d" startLine="9" startColumn="9" endLine="9" endColumn="55" document="1"/>
<entry offset="0x42" hidden="true" document="1"/>
<entry offset="0xa0" startLine="10" startColumn="9" endLine="10" endColumn="21" document="1"/>
<entry offset="0xac" startLine="11" startColumn="9" endLine="11" endColumn="21" document="1"/>
<entry offset="0xb8" startLine="12" startColumn="5" endLine="12" endColumn="17" document="1"/>
<entry offset="0xba" hidden="true" document="1"/>
<entry offset="0xc2" hidden="true" document="1"/>
<entry offset="0xdf" startLine="12" startColumn="5" endLine="12" endColumn="17" document="1"/>
<entry offset="0xe9" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xf6">
<namespace name="System" importlevel="file"/>
<namespace name="System.Threading.Tasks" importlevel="file"/>
<currentnamespace name=""/>
<local name="$VB$ResumableLocal_x$0" il_index="0" il_start="0x0" il_end="0xf6" attributes="0"/>
<local name="$VB$ResumableLocal_y$1" il_index="1" il_start="0x0" il_end="0xf6" attributes="0"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="Async_NoLambda"/>
<await yield="0x54" resume="0x72" declaringType="C+VB$StateMachine_1_Async_NoLambda" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub LocalNotCapturedInBetweenSuspensionPoints_Release()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Public Class C
Private Async Function Async_NoLambda() As Task
Dim x As Integer = 1
Dim y As Integer = 2
Await Console.Out.WriteAsync((x + y).ToString)
x.ToString()
y.ToString()
End Function
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
source,
{MscorlibRef_v4_0_30316_17626, MsvbRef},
TestOptions.ReleaseDll)
' Goal: We're looking for the single-mangled names "$VB$ResumableLocal_x$0" and "$VB$ResumableLocal_y$1".
compilation.VerifyPdb("C+VB$StateMachine_1_Async_NoLambda.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_Async_NoLambda" name="MoveNext">
<customDebugInfo>
<hoistedLocalScopes format="portable">
<slot startOffset="0x0" endOffset="0xe3"/>
<slot startOffset="0x0" endOffset="0xe3"/>
</hoistedLocalScopes>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0xa" startLine="6" startColumn="13" endLine="6" endColumn="29" document="1"/>
<entry offset="0x11" startLine="7" startColumn="13" endLine="7" endColumn="29" document="1"/>
<entry offset="0x18" startLine="9" startColumn="9" endLine="9" endColumn="55" document="1"/>
<entry offset="0x3d" hidden="true" document="1"/>
<entry offset="0x91" startLine="10" startColumn="9" endLine="10" endColumn="21" document="1"/>
<entry offset="0x9d" startLine="11" startColumn="9" endLine="11" endColumn="21" document="1"/>
<entry offset="0xa9" startLine="12" startColumn="5" endLine="12" endColumn="17" document="1"/>
<entry offset="0xab" hidden="true" document="1"/>
<entry offset="0xb2" hidden="true" document="1"/>
<entry offset="0xcd" startLine="12" startColumn="5" endLine="12" endColumn="17" document="1"/>
<entry offset="0xd7" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0xe3">
<namespace name="System" importlevel="file"/>
<namespace name="System.Threading.Tasks" importlevel="file"/>
<currentnamespace name=""/>
<local name="$VB$ResumableLocal_x$0" il_index="0" il_start="0x0" il_end="0xe3" attributes="0"/>
<local name="$VB$ResumableLocal_y$1" il_index="1" il_start="0x0" il_end="0xe3" attributes="0"/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="Async_NoLambda"/>
<await yield="0x4f" resume="0x66" declaringType="C+VB$StateMachine_1_Async_NoLambda" methodName="MoveNext"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<WorkItem(1085911, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1085911")>
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub AsyncReturnVariable()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Class C
Shared Async Function M() As Task(Of Integer)
Return 1
End Function
End Class
</file>
</compilation>
Dim c = CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugDll)
c.AssertNoErrors()
' NOTE: No <local> for the return variable "M".
c.VerifyPdb("C+VB$StateMachine_1_M.MoveNext",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_M" name="MoveNext">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="20" offset="-1"/>
<slot kind="27" offset="-1"/>
<slot kind="0" offset="-1"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" startLine="5" startColumn="5" endLine="5" endColumn="50" document="1"/>
<entry offset="0x8" startLine="6" startColumn="9" endLine="6" endColumn="17" document="1"/>
<entry offset="0xc" hidden="true" document="1"/>
<entry offset="0x13" hidden="true" document="1"/>
<entry offset="0x2f" startLine="7" startColumn="5" endLine="7" endColumn="17" document="1"/>
<entry offset="0x39" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x47">
<namespace name="System" importlevel="file"/>
<namespace name="System.Threading.Tasks" importlevel="file"/>
<currentnamespace name=""/>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="M"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub AsyncAndClosure()
Dim source =
<compilation>
<file>
Imports System
Imports System.Threading.Tasks
Module M
Async Function F() As Task(Of Boolean)
Dim z = Await Task.FromResult(1)
Dim x = Sub()
Console.WriteLine(z)
End Sub
Return False
End Function
End Module
</file>
</compilation>
Dim v = CompileAndVerify(source, LatestVbReferences, options:=TestOptions.DebugDll)
v.VerifyIL("M.VB$StateMachine_0_F.MoveNext", "
{
// Code size 254 (0xfe)
.maxstack 3
.locals init (Boolean V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Boolean) V_2,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_3,
M.VB$StateMachine_0_F V_4,
Integer V_5,
System.Exception V_6)
~IL_0000: ldarg.0
IL_0001: ldfld ""M.VB$StateMachine_0_F.$State As Integer""
IL_0006: stloc.1
.try
{
~IL_0007: ldloc.1
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0063
-IL_000e: nop
~IL_000f: ldarg.0
IL_0010: newobj ""Sub M._Closure$__0-0..ctor()""
IL_0015: stfld ""M.VB$StateMachine_0_F.$VB$ResumableLocal_$VB$Closure_$0 As M._Closure$__0-0""
-IL_001a: ldarg.0
IL_001b: ldarg.0
IL_001c: ldfld ""M.VB$StateMachine_0_F.$VB$ResumableLocal_$VB$Closure_$0 As M._Closure$__0-0""
IL_0021: stfld ""M.VB$StateMachine_0_F.$U1 As M._Closure$__0-0""
IL_0026: ldc.i4.1
IL_0027: call ""Function System.Threading.Tasks.Task.FromResult(Of Integer)(Integer) As System.Threading.Tasks.Task(Of Integer)""
IL_002c: callvirt ""Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_0031: stloc.3
~IL_0032: ldloca.s V_3
IL_0034: call ""Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean""
IL_0039: brtrue.s IL_0081
IL_003b: ldarg.0
IL_003c: ldc.i4.0
IL_003d: dup
IL_003e: stloc.1
IL_003f: stfld ""M.VB$StateMachine_0_F.$State As Integer""
<IL_0044: ldarg.0
IL_0045: ldloc.3
IL_0046: stfld ""M.VB$StateMachine_0_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_004b: ldarg.0
IL_004c: ldflda ""M.VB$StateMachine_0_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean)""
IL_0051: ldloca.s V_3
IL_0053: ldarg.0
IL_0054: stloc.s V_4
IL_0056: ldloca.s V_4
IL_0058: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), M.VB$StateMachine_0_F)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef M.VB$StateMachine_0_F)""
IL_005d: nop
IL_005e: leave IL_00fd
>IL_0063: ldarg.0
IL_0064: ldc.i4.m1
IL_0065: dup
IL_0066: stloc.1
IL_0067: stfld ""M.VB$StateMachine_0_F.$State As Integer""
IL_006c: ldarg.0
IL_006d: ldfld ""M.VB$StateMachine_0_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_0072: stloc.3
IL_0073: ldarg.0
IL_0074: ldflda ""M.VB$StateMachine_0_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_0079: initobj ""System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_007f: br.s IL_0081
IL_0081: ldarg.0
IL_0082: ldfld ""M.VB$StateMachine_0_F.$U1 As M._Closure$__0-0""
IL_0087: ldloca.s V_3
IL_0089: call ""Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer""
IL_008e: stloc.s V_5
IL_0090: ldloca.s V_3
IL_0092: initobj ""System.Runtime.CompilerServices.TaskAwaiter(Of Integer)""
IL_0098: ldloc.s V_5
IL_009a: stfld ""M._Closure$__0-0.$VB$Local_z As Integer""
IL_009f: ldarg.0
IL_00a0: ldnull
IL_00a1: stfld ""M.VB$StateMachine_0_F.$U1 As M._Closure$__0-0""
-IL_00a6: ldarg.0
IL_00a7: ldarg.0
IL_00a8: ldfld ""M.VB$StateMachine_0_F.$VB$ResumableLocal_$VB$Closure_$0 As M._Closure$__0-0""
IL_00ad: ldftn ""Sub M._Closure$__0-0._Lambda$__0()""
IL_00b3: newobj ""Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)""
IL_00b8: stfld ""M.VB$StateMachine_0_F.$VB$ResumableLocal_x$1 As <generated method>""
-IL_00bd: ldc.i4.0
IL_00be: stloc.0
IL_00bf: leave.s IL_00e6
}
catch System.Exception
{
~IL_00c1: dup
IL_00c2: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)""
IL_00c7: stloc.s V_6
~IL_00c9: ldarg.0
IL_00ca: ldc.i4.s -2
IL_00cc: stfld ""M.VB$StateMachine_0_F.$State As Integer""
IL_00d1: ldarg.0
IL_00d2: ldflda ""M.VB$StateMachine_0_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean)""
IL_00d7: ldloc.s V_6
IL_00d9: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean).SetException(System.Exception)""
IL_00de: nop
IL_00df: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()""
IL_00e4: leave.s IL_00fd
}
-IL_00e6: ldarg.0
IL_00e7: ldc.i4.s -2
IL_00e9: dup
IL_00ea: stloc.1
IL_00eb: stfld ""M.VB$StateMachine_0_F.$State As Integer""
~IL_00f0: ldarg.0
IL_00f1: ldflda ""M.VB$StateMachine_0_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean)""
IL_00f6: ldloc.0
IL_00f7: call ""Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Boolean).SetResult(Boolean)""
IL_00fc: nop
IL_00fd: ret
}
", sequencePoints:="M+VB$StateMachine_0_F.MoveNext")
End Sub
<Fact>
Public Sub PartialKickoffMethod()
Dim src = "
Public Partial Class C
Private Partial Sub M()
End Sub
Private Async Sub M()
End Sub
End Class
"
Dim compilation = CreateEmptyCompilation(src, LatestVbReferences, options:=TestOptions.DebugDll)
Dim v = CompileAndVerify(compilation)
v.VerifyPdb("C.M", "
<symbols>
<files>
<file id=""1"" name="""" language=""VB"" />
</files>
<methods>
<method containingType=""C"" name=""M"">
<customDebugInfo>
<forwardIterator name=""VB$StateMachine_1_M"" />
</customDebugInfo>
</method>
</methods>
</symbols>")
Dim peStream = New MemoryStream()
Dim pdbStream = New MemoryStream()
Dim result = compilation.Emit(peStream, pdbStream, options:=EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb))
pdbStream.Position = 0
Using provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream)
Dim mdReader = provider.GetMetadataReader()
Dim writer = New StringWriter()
Dim visualizer = New MetadataVisualizer(mdReader, writer, MetadataVisualizerOptions.NoHeapReferences)
visualizer.WriteMethodDebugInformation()
AssertEx.AssertEqualToleratingWhitespaceDifferences("
MethodDebugInformation (index: 0x31, size: 20):
==================================================
1: nil
2: nil
3: nil
4:
{
Kickoff Method: 0x06000002 (MethodDef)
Locals: 0x11000002 (StandAloneSig)
Document: #1
IL_0000: <hidden>
IL_0007: (6, 5) - (6, 26)
IL_0008: (7, 5) - (7, 12)
IL_000A: <hidden>
IL_0011: <hidden>
IL_002D: (7, 5) - (7, 12)
IL_0037: <hidden>
}
5: nil
", writer.ToString())
End Using
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub CatchInAsyncStateMachine()
Dim src = "
Imports System
Imports System.Threading.Tasks
Class C
Shared Async Function M() As Task
Dim o As Object
Try
o = Nothing
Catch e As Exception
#ExternalSource(""test"", 999)
o = e
#End ExternalSource
End Try
End Function
End Class"
Dim v = CompileAndVerifyEx(src, references:=LatestVbReferences, options:=TestOptions.DebugDll, targetFramework:=TargetFramework.Empty)
v.VerifyPdb("C+VB$StateMachine_1_M.MoveNext",
<symbols>
<files>
<file id="1" name="test" language="VB"/>
</files>
<methods>
<method containingType="C+VB$StateMachine_1_M" name="MoveNext">
<customDebugInfo>
<hoistedLocalScopes format="portable">
<slot startOffset="0x0" endOffset="0x71"/>
<slot startOffset="0x12" endOffset="0x34"/>
</hoistedLocalScopes>
<encLocalSlotMap>
<slot kind="27" offset="-1"/>
<slot kind="temp"/>
<slot kind="temp"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" hidden="true" document="1"/>
<entry offset="0x7" hidden="true" document="1"/>
<entry offset="0x8" hidden="true" document="1"/>
<entry offset="0x9" hidden="true" document="1"/>
<entry offset="0x12" hidden="true" document="1"/>
<entry offset="0x20" hidden="true" document="1"/>
<entry offset="0x21" startLine="999" startColumn="13" endLine="999" endColumn="18" document="1"/>
<entry offset="0x34" hidden="true" document="1"/>
<entry offset="0x35" hidden="true" document="1"/>
<entry offset="0x37" hidden="true" document="1"/>
<entry offset="0x3e" hidden="true" document="1"/>
<entry offset="0x5a" hidden="true" document="1"/>
<entry offset="0x64" hidden="true" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x71">
<namespace name="System" importlevel="file"/>
<namespace name="System.Threading.Tasks" importlevel="file"/>
<currentnamespace name=""/>
<local name="$VB$ResumableLocal_o$0" il_index="0" il_start="0x0" il_end="0x71" attributes="0"/>
<scope startOffset="0x12" endOffset="0x33">
<local name="$VB$ResumableLocal_e$1" il_index="1" il_start="0x12" il_end="0x33" attributes="0"/>
</scope>
</scope>
<asyncInfo>
<kickoffMethod declaringType="C" methodName="M"/>
</asyncInfo>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
ErikSchierboom/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBAsyncTests.vb
|
Visual Basic
|
apache-2.0
| 45,778
|
' 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 System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Common
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
Imports Microsoft.VisualStudio.Shell.TableManager
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
Public Class TodoListTableDataSourceTests
<Fact>
Public Sub TestCreation()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Assert.Equal(manager.Identifier, StandardTables.TasksTable)
Assert.Equal(1, manager.Sources.Count())
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
AssertEx.SetEqual(table.Columns, manager.GetColumnsForSources(SpecializedCollections.SingletonEnumerable(source)))
Assert.Equal(ServicesVSResources.CSharp_VB_Todo_List_Table_Data_Source, source.DisplayName)
Assert.Equal(StandardTableDataSources.CommentTableDataSource, source.SourceTypeIdentifier)
Assert.Equal(1, manager.Sinks_TestOnly.Count())
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Assert.Equal(0, sink.Entries.Count())
Assert.Equal(1, source.NumberOfSubscription_TestOnly)
subscription.Dispose()
Assert.Equal(0, source.NumberOfSubscription_TestOnly)
End Using
End Sub
<Fact>
Public Sub TestInitialEntries()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider(CreateItem(workspace, documentId))
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Assert.Equal(1, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntryChanged()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
provider.Items = New TodoItem() {CreateItem(workspace, documentId)}
provider.RaiseTodoListUpdated(workspace)
Assert.Equal(1, sink.Entries.Count)
provider.Items = Array.Empty(Of TodoItem)()
provider.RaiseClearTodoListUpdated(workspace, documentId)
Assert.Equal(0, sink.Entries.Count)
End Using
End Sub
<Fact>
Public Sub TestEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoItem))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(snapshot1.VersionNumber + 1, snapshot2.VersionNumber)
Assert.Equal(1, snapshot1.Count)
Dim filename = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal(item.OriginalFilePath, filename)
Dim text = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Text, text))
Assert.Equal(item.Message, text)
Dim line = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Line, line))
Assert.Equal(item.MappedLine, line)
Dim column = Nothing
Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Column, column))
Assert.Equal(item.MappedColumn, column)
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoItem))
Dim snapshot1 = factory.GetCurrentSnapshot()
factory.OnRefreshed()
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(0, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo2()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoItem))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoItem() {
New TodoItem(1, "test2", workspace, documentId, 11, 11, 21, 21, Nothing, "test2"),
New TodoItem(0, "test", workspace, documentId, 11, 11, 21, 21, Nothing, "test1")}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestSnapshotTranslateTo3()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim subscription = sinkAndSubscription.Value
Dim factory = TryCast(sink.Entries.First(), TableEntriesFactory(Of TodoItem))
Dim snapshot1 = factory.GetCurrentSnapshot()
provider.Items = New TodoItem() {
New TodoItem(1, "test2", workspace, documentId, 11, 11, 21, 21, Nothing, "test2"),
New TodoItem(0, "test3", workspace, documentId, 11, 11, 21, 21, Nothing, "test3")}
provider.RaiseTodoListUpdated(workspace)
Dim snapshot2 = factory.GetCurrentSnapshot()
Assert.Equal(-1, snapshot1.IndexOf(0, snapshot2))
End Using
End Sub
<Fact>
Public Sub TestInvalidEntry()
Using workspace = TestWorkspace.CreateCSharp(String.Empty)
Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
Dim item = CreateItem(workspace, documentId)
Dim provider = New TestTodoListProvider(item)
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim temp = Nothing
Assert.False(snapshot.TryGetValue(-1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(1, StandardTableKeyNames.DocumentName, temp))
Assert.False(snapshot.TryGetValue(0, "Test", temp))
End Using
End Sub
<Fact>
Public Sub TestAggregatedEntries()
Dim markup = <Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj1">
<Document FilePath="test1"><![CDATA[// TODO hello]]></Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="Proj2">
<Document IsLinkFile="true" LinkAssemblyName="Proj1" LinkFilePath="test1"/>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(markup)
Dim projects = workspace.CurrentSolution.Projects.ToArray()
Dim item1 = CreateItem(workspace, projects(0).DocumentIds.First())
Dim item2 = CreateItem(workspace, projects(1).DocumentIds.First())
Dim provider = New TestTodoListProvider()
Dim tableManagerProvider = New TestTableManagerProvider()
Dim table = New VisualStudioTodoListTable(workspace, provider, tableManagerProvider)
provider.Items = New TodoItem() {item1, item2}
provider.RaiseTodoListUpdated(workspace)
Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
Dim source = DirectCast(manager.Sources.First(), AbstractRoslynTableDataSource(Of TodoItem))
Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
Assert.Equal(1, snapshot.Count)
Dim filename As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
Assert.Equal("test1", filename)
Dim projectname As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName, projectname))
Assert.Equal("Proj1, Proj2", projectname)
Dim projectnames As Object = Nothing
Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectName + "s", projectnames))
Assert.Equal(2, DirectCast(projectnames, String()).Length)
Dim projectguid As Object = Nothing
Assert.False(snapshot.TryGetValue(0, StandardTableKeyNames.ProjectGuid, projectguid))
End Using
End Sub
Private Function CreateItem(workspace As Microsoft.CodeAnalysis.Workspace, documentId As DocumentId) As TodoItem
Return New TodoItem(0, "test", workspace, documentId, 10, 10, 20, 20, Nothing, "test1")
End Function
Private Class TestTodoListProvider
Implements ITodoListProvider
Public Items As TodoItem()
Public Sub New(ParamArray items As TodoItem())
Me.Items = items
End Sub
Public Event TodoListUpdated As EventHandler(Of TodoItemsUpdatedArgs) Implements ITodoListProvider.TodoListUpdated
Public Function GetTodoItems(workspace As Microsoft.CodeAnalysis.Workspace, documentId As DocumentId, cancellationToken As CancellationToken) As ImmutableArray(Of TodoItem) Implements ITodoListProvider.GetTodoItems
Assert.NotNull(workspace)
Assert.NotNull(documentId)
Return Items.Where(Function(t) t.DocumentId Is documentId).ToImmutableArrayOrEmpty()
End Function
Public Function GetTodoItemsUpdatedEventArgs(workspace As Microsoft.CodeAnalysis.Workspace, cancellationToken As CancellationToken) As IEnumerable(Of UpdatedEventArgs) Implements ITodoListProvider.GetTodoItemsUpdatedEventArgs
Return Items.Select(Function(t) New UpdatedEventArgs(Tuple.Create(Me, t.DocumentId), t.Workspace, t.DocumentId.ProjectId, t.DocumentId)).ToImmutableArrayOrEmpty()
End Function
Public Sub RaiseTodoListUpdated(workspace As Microsoft.CodeAnalysis.Workspace)
Dim map = Items.Where(Function(t) t.Workspace Is workspace).ToLookup(Function(t) t.DocumentId)
For Each group In map
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, group.Key), workspace, workspace.CurrentSolution, group.Key.ProjectId, group.Key, group.ToImmutableArrayOrEmpty()))
Next
End Sub
Public Sub RaiseClearTodoListUpdated(workspace As Microsoft.CodeAnalysis.Workspace, documentId As DocumentId)
RaiseEvent TodoListUpdated(Me, New TodoItemsUpdatedArgs(
Tuple.Create(Me, documentId), workspace, workspace.CurrentSolution, documentId.ProjectId, documentId, ImmutableArray(Of TodoItem).Empty))
End Sub
End Class
End Class
End Namespace
|
pdelvo/roslyn
|
src/VisualStudio/Core/Test/Diagnostics/TodoListTableDataSourceTests.vb
|
Visual Basic
|
apache-2.0
| 20,105
|
' 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.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel
Public MustInherit Class AbstractEventCollectorTests
Protected MustOverride ReadOnly Property LanguageName As String
Friend Function Add(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Sub(codeModelEvent, codeModelService)
Assert.NotNull(codeModelEvent)
Assert.Equal(CodeModelEventType.Add, codeModelEvent.Type)
CheckCodeModelEvents(codeModelEvent, codeModelService, node, parent)
End Sub
End Function
Friend Function Change(type As CodeModelEventType, node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Sub(codeModelEvent, codeModelService)
Assert.NotNull(codeModelEvent)
Assert.Equal(type, codeModelEvent.Type)
If node IsNot Nothing Then
Assert.NotNull(codeModelEvent.Node)
Assert.Equal(node, codeModelService.GetName(codeModelEvent.Node))
Else
Assert.Null(codeModelEvent.Node)
End If
If parent IsNot Nothing Then
Assert.NotNull(codeModelEvent.ParentNode)
Assert.Equal(parent, codeModelService.GetName(codeModelEvent.ParentNode))
End If
End Sub
End Function
Friend Function ArgChange(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Change(CodeModelEventType.ArgChange, node, parent)
End Function
Friend Function BaseChange(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Change(CodeModelEventType.BaseChange, node, parent)
End Function
Friend Function TypeRefChange(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Change(CodeModelEventType.TypeRefChange, node, parent)
End Function
Friend Function Rename(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Change(CodeModelEventType.Rename, node, parent)
End Function
Friend Function Unknown(node As String, Optional parent As String = Nothing) As Action(Of CodeModelEvent, ICodeModelService)
Return Change(CodeModelEventType.Unknown, node, parent)
End Function
Friend Function Remove(node As String, parent As String) As Action(Of CodeModelEvent, ICodeModelService)
Return Sub(codeModelEvent, codeModelService)
Assert.NotNull(codeModelEvent)
Assert.Equal(CodeModelEventType.Remove, codeModelEvent.Type)
CheckCodeModelEvents(codeModelEvent, codeModelService, node, parent)
End Sub
End Function
Private Sub CheckCodeModelEvents(codeModelEvent As CodeModelEvent, codeModelService As ICodeModelService, node As String, parent As String)
If node IsNot Nothing Then
Assert.NotNull(codeModelEvent.Node)
Assert.Equal(node, codeModelService.GetName(codeModelEvent.Node))
Else
Assert.Null(codeModelEvent.Node)
End If
If parent IsNot Nothing Then
Assert.NotNull(codeModelEvent.ParentNode)
Assert.Equal(parent, codeModelService.GetName(codeModelEvent.ParentNode))
Else
Assert.Null(codeModelEvent.ParentNode)
End If
End Sub
Friend Async Function TestAsync(code As XElement, change As XElement, ParamArray expectedEvents As Action(Of CodeModelEvent, ICodeModelService)()) As Task
Dim definition =
<Workspace>
<Project Language=<%= LanguageName %> CommonReferences="true">
<Document><%= code.Value %></Document>
<Document><%= change.Value %></Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(definition, exportProvider:=VisualStudioTestExportProvider.ExportProvider)
Dim project = workspace.CurrentSolution.Projects.First()
Dim codeModelService = project.LanguageServices.GetService(Of ICodeModelService)()
Assert.NotNull(codeModelService)
Dim codeDocument = workspace.CurrentSolution.GetDocument(workspace.Documents(0).Id)
Dim codeTree = Await codeDocument.GetSyntaxTreeAsync()
Dim changeDocument = workspace.CurrentSolution.GetDocument(workspace.Documents(1).Id)
Dim changeTree = Await changeDocument.GetSyntaxTreeAsync()
Dim collectedEvents = codeModelService.CollectCodeModelEvents(codeTree, changeTree)
Assert.NotNull(collectedEvents)
Assert.Equal(expectedEvents.Length, collectedEvents.Count)
For Each expectedEvent In expectedEvents
Dim collectedEvent = collectedEvents.Dequeue()
expectedEvent(collectedEvent, codeModelService)
Next
End Using
End Function
End Class
End Namespace
|
mmitche/roslyn
|
src/VisualStudio/Core/Test/CodeModel/AbstractEventCollectorTests.vb
|
Visual Basic
|
apache-2.0
| 5,879
|
#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
Module SocketConstants
'
' Taken from winsock2.h
'
' All Windows Sockets Error constants are biased by WSABASEERR from
' the "normal"
'
Friend Const WSABASEERR As Integer = 10000
End Module
|
tradewright/tradewright-twsapi
|
src/IBApi/ProtocolEngine/SocketConstants.vb
|
Visual Basic
|
mit
| 1,410
|
Imports System.Data.SqlClient
Imports EpdIt.DBUtilities
Partial Public Class DBHelper
''' <summary>
''' Executes a non-query stored procedure on the database.
''' </summary>
''' <param name="spName">The name of the stored procedure to execute.</param>
''' <param name="parameterArray">An array of SqlParameter values. The array may be modified by the stored produre if it includes output parameters.</param>
''' <param name="returnValue">Output parameter that stores the RETURN value of the stored procedure.</param>
''' <returns>The number of rows affected.</returns>
Private Function SPExecuteNonQuery(spName As String, parameterArray As SqlParameter(), ByRef returnValue As Integer) As Integer
If String.IsNullOrEmpty(spName) Then Throw New ArgumentException("The name of the stored procedure must be specified.", "spName")
Using connection As New SqlConnection(ConnectionString)
Using command As New SqlCommand(spName, connection)
' Setup
command.CommandType = CommandType.StoredProcedure
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
DBNullifyParameters(parameterArray)
command.Parameters.AddRange(parameterArray)
End If
Dim returnParameter As SqlParameter = ReturnValueParameter()
command.Parameters.Add(returnParameter)
' Run
command.Connection.Open()
Dim rowsAffected As Integer = command.ExecuteNonQuery()
command.Connection.Close()
' Cleanup
returnValue = returnParameter.Value
command.Parameters.Remove(returnParameter)
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
Dim newArray(command.Parameters.Count) As SqlParameter
command.Parameters.CopyTo(newArray, 0)
Array.Copy(newArray, parameterArray, parameterArray.Length)
End If
command.Parameters.Clear()
' Return
Return rowsAffected
End Using
End Using
End Function
''' <summary>
''' Retrieves a DataSet containing one or more DataTables selected from the database by calling a stored procedure.
''' (Adds the necessary columns and primary key information to complete the schema.)
''' </summary>
''' <param name="spName">The name of the stored procedure to execute.</param>
''' <param name="parameterArray">An array of SqlParameter values. The array may be modified by the stored produre if it includes output parameters.</param>
''' <param name="returnValue">Output parameter that stores the RETURN value of the stored procedure.</param>
''' <returns>A DataSet.</returns>
Private Function SPFillDataSet(spName As String, parameterArray As SqlParameter(), ByRef returnValue As Integer) As DataSet
If String.IsNullOrEmpty(spName) Then Throw New ArgumentException("The name of the stored procedure must be specified.", "spName")
Using connection As New SqlConnection(ConnectionString)
Using command As New SqlCommand(spName, connection)
' Setup
command.CommandType = CommandType.StoredProcedure
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
DBNullifyParameters(parameterArray)
command.Parameters.AddRange(parameterArray)
End If
Dim returnParameter As SqlParameter = ReturnValueParameter()
command.Parameters.Add(returnParameter)
' Run
Dim dataSet As New DataSet
Using adapter As New SqlDataAdapter(command)
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
adapter.Fill(dataSet)
End Using
' Cleanup
returnValue = returnParameter.Value
command.Parameters.Remove(returnParameter)
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
Dim newArray(command.Parameters.Count) As SqlParameter
command.Parameters.CopyTo(newArray, 0)
Array.Copy(newArray, parameterArray, parameterArray.Length)
End If
command.Parameters.Clear()
' Return
Return dataSet
End Using
End Using
End Function
''' <summary>
''' Retrieves a single value from the database by calling a stored procedure.
''' </summary>
''' <param name="spName">The name of the stored procedure to execute.</param>
''' <param name="parameterArray">An array of SqlParameter values. The array may be modified by the stored produre if it includes output parameters.</param>
''' <param name="returnValue">Output parameter that stores the RETURN value of the stored procedure.</param>
''' <returns>The first column of the first row in the result set, or a null reference (Nothing
''' in Visual Basic) if the result set is empty.</returns>
Private Function SPExecuteScalar(spName As String, parameterArray As SqlParameter(), ByRef returnValue As Integer) As Object
If String.IsNullOrEmpty(spName) Then Throw New ArgumentException("The name of the stored procedure must be specified.", "spName")
Using connection As New SqlConnection(ConnectionString)
Using command As New SqlCommand(spName, connection)
' Setup
command.CommandType = CommandType.StoredProcedure
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
DBNullifyParameters(parameterArray)
command.Parameters.AddRange(parameterArray)
End If
Dim returnParameter As SqlParameter = ReturnValueParameter()
command.Parameters.Add(returnParameter)
' Run
command.Connection.Open()
Dim result As Object = command.ExecuteScalar()
command.Connection.Close()
' Cleanup
returnValue = returnParameter.Value
command.Parameters.Remove(returnParameter)
If parameterArray IsNot Nothing AndAlso parameterArray.Count > 0 Then
Dim newArray(command.Parameters.Count) As SqlParameter
command.Parameters.CopyTo(newArray, 0)
Array.Copy(newArray, parameterArray, parameterArray.Length)
End If
command.Parameters.Clear()
' Return
Return result
End Using
End Using
End Function
End Class
|
ga-epd-it/db-helper
|
DBHelper/SPFunctions/SPExecute.vb
|
Visual Basic
|
mit
| 6,939
|
'------------------------------------------------------------------------------
' <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 Off
Option Explicit On
'''<summary>
'''Represents a strongly typed in-memory cache of data.
'''</summary>
<Global.System.Serializable(), _
Global.System.ComponentModel.DesignerCategoryAttribute("code"), _
Global.System.ComponentModel.ToolboxItem(true), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema"), _
Global.System.Xml.Serialization.XmlRootAttribute("dsTagger"), _
Global.System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")> _
Partial Public Class dsTagger
Inherits Global.System.Data.DataSet
Private tableDTI_Content_Tags As DTI_Content_TagsDataTable
Private tableDTI_Content_Tag_Pivot As DTI_Content_Tag_PivotDataTable
Private _schemaSerializationMode As Global.System.Data.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.BeginInit
Me.InitClass
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler MyBase.Relations.CollectionChanged, schemaChangedHandler
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context, false)
If (Me.IsBinarySerialized(info, context) = true) Then
Me.InitVars(false)
Dim schemaChangedHandler1 As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler Me.Tables.CollectionChanged, schemaChangedHandler1
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler1
Return
End If
Dim strSchema As String = CType(info.GetValue("XmlSchema", GetType(String)),String)
If (Me.DetermineSchemaSerializationMode(info, context) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
If (Not (ds.Tables("DTI_Content_Tags")) Is Nothing) Then
MyBase.Tables.Add(New DTI_Content_TagsDataTable(ds.Tables("DTI_Content_Tags")))
End If
If (Not (ds.Tables("DTI_Content_Tag_Pivot")) Is Nothing) Then
MyBase.Tables.Add(New DTI_Content_Tag_PivotDataTable(ds.Tables("DTI_Content_Tag_Pivot")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXmlSchema(New Global.System.Xml.XmlTextReader(New Global.System.IO.StringReader(strSchema)))
End If
Me.GetSerializationData(info, context)
Dim schemaChangedHandler As Global.System.ComponentModel.CollectionChangeEventHandler = AddressOf Me.SchemaChanged
AddHandler MyBase.Tables.CollectionChanged, schemaChangedHandler
AddHandler Me.Relations.CollectionChanged, schemaChangedHandler
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property DTI_Content_Tags() As DTI_Content_TagsDataTable
Get
Return Me.tableDTI_Content_Tags
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false), _
Global.System.ComponentModel.DesignerSerializationVisibility(Global.System.ComponentModel.DesignerSerializationVisibility.Content)> _
Public ReadOnly Property DTI_Content_Tag_Pivot() As DTI_Content_Tag_PivotDataTable
Get
Return Me.tableDTI_Content_Tag_Pivot
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.BrowsableAttribute(true), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Visible)> _
Public Overrides Property SchemaSerializationMode() As Global.System.Data.SchemaSerializationMode
Get
Return Me._schemaSerializationMode
End Get
Set
Me._schemaSerializationMode = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Tables() As Global.System.Data.DataTableCollection
Get
Return MyBase.Tables
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.DesignerSerializationVisibilityAttribute(Global.System.ComponentModel.DesignerSerializationVisibility.Hidden)> _
Public Shadows ReadOnly Property Relations() As Global.System.Data.DataRelationCollection
Get
Return MyBase.Relations
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub InitializeDerivedDataSet()
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataSet
Dim cln As dsTagger = CType(MyBase.Clone,dsTagger)
cln.InitVars
cln.SchemaSerializationMode = Me.SchemaSerializationMode
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeTables() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function ShouldSerializeRelations() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub ReadXmlSerializable(ByVal reader As Global.System.Xml.XmlReader)
If (Me.DetermineSchemaSerializationMode(reader) = Global.System.Data.SchemaSerializationMode.IncludeSchema) Then
Me.Reset
Dim ds As Global.System.Data.DataSet = New Global.System.Data.DataSet()
ds.ReadXml(reader)
If (Not (ds.Tables("DTI_Content_Tags")) Is Nothing) Then
MyBase.Tables.Add(New DTI_Content_TagsDataTable(ds.Tables("DTI_Content_Tags")))
End If
If (Not (ds.Tables("DTI_Content_Tag_Pivot")) Is Nothing) Then
MyBase.Tables.Add(New DTI_Content_Tag_PivotDataTable(ds.Tables("DTI_Content_Tag_Pivot")))
End If
Me.DataSetName = ds.DataSetName
Me.Prefix = ds.Prefix
Me.Namespace = ds.Namespace
Me.Locale = ds.Locale
Me.CaseSensitive = ds.CaseSensitive
Me.EnforceConstraints = ds.EnforceConstraints
Me.Merge(ds, false, Global.System.Data.MissingSchemaAction.Add)
Me.InitVars
Else
Me.ReadXml(reader)
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetSchemaSerializable() As Global.System.Xml.Schema.XmlSchema
Dim stream As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Me.WriteXmlSchema(New Global.System.Xml.XmlTextWriter(stream, Nothing))
stream.Position = 0
Return Global.System.Xml.Schema.XmlSchema.Read(New Global.System.Xml.XmlTextReader(stream), Nothing)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars()
Me.InitVars(true)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Overloads Sub InitVars(ByVal initTable As Boolean)
Me.tableDTI_Content_Tags = CType(MyBase.Tables("DTI_Content_Tags"),DTI_Content_TagsDataTable)
If (initTable = true) Then
If (Not (Me.tableDTI_Content_Tags) Is Nothing) Then
Me.tableDTI_Content_Tags.InitVars
End If
End If
Me.tableDTI_Content_Tag_Pivot = CType(MyBase.Tables("DTI_Content_Tag_Pivot"),DTI_Content_Tag_PivotDataTable)
If (initTable = true) Then
If (Not (Me.tableDTI_Content_Tag_Pivot) Is Nothing) Then
Me.tableDTI_Content_Tag_Pivot.InitVars
End If
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.DataSetName = "dsTagger"
Me.Prefix = ""
Me.Namespace = "http://tempuri.org/dsTagger.xsd"
Me.EnforceConstraints = true
Me.SchemaSerializationMode = Global.System.Data.SchemaSerializationMode.IncludeSchema
Me.tableDTI_Content_Tags = New DTI_Content_TagsDataTable()
MyBase.Tables.Add(Me.tableDTI_Content_Tags)
Me.tableDTI_Content_Tag_Pivot = New DTI_Content_Tag_PivotDataTable()
MyBase.Tables.Add(Me.tableDTI_Content_Tag_Pivot)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializeDTI_Content_Tags() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Function ShouldSerializeDTI_Content_Tag_Pivot() As Boolean
Return false
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub SchemaChanged(ByVal sender As Object, ByVal e As Global.System.ComponentModel.CollectionChangeEventArgs)
If (e.Action = Global.System.ComponentModel.CollectionChangeAction.Remove) Then
Me.InitVars
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedDataSetSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim ds As dsTagger = New dsTagger()
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim any As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any.Namespace = ds.Namespace
sequence.Items.Add(any)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub DTI_Content_TagsRowChangeEventHandler(ByVal sender As Object, ByVal e As DTI_Content_TagsRowChangeEvent)
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Delegate Sub DTI_Content_Tag_PivotRowChangeEventHandler(ByVal sender As Object, ByVal e As DTI_Content_Tag_PivotRowChangeEvent)
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class DTI_Content_TagsDataTable
Inherits Global.System.Data.DataTable
Implements Global.System.Collections.IEnumerable
Private columnId As Global.System.Data.DataColumn
Private columnTag_Name As Global.System.Data.DataColumn
Private columnMain_Id As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "DTI_Content_Tags"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property IdColumn() As Global.System.Data.DataColumn
Get
Return Me.columnId
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Tag_NameColumn() As Global.System.Data.DataColumn
Get
Return Me.columnTag_Name
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Main_IdColumn() As Global.System.Data.DataColumn
Get
Return Me.columnMain_Id
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As DTI_Content_TagsRow
Get
Return CType(Me.Rows(index),DTI_Content_TagsRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_TagsRowChanging As DTI_Content_TagsRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_TagsRowChanged As DTI_Content_TagsRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_TagsRowDeleting As DTI_Content_TagsRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_TagsRowDeleted As DTI_Content_TagsRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddDTI_Content_TagsRow(ByVal row As DTI_Content_TagsRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddDTI_Content_TagsRow(ByVal Tag_Name As String, ByVal Main_Id As String) As DTI_Content_TagsRow
Dim rowDTI_Content_TagsRow As DTI_Content_TagsRow = CType(Me.NewRow,DTI_Content_TagsRow)
Dim columnValuesArray() As Object = New Object() {Nothing, Tag_Name, Main_Id}
rowDTI_Content_TagsRow.ItemArray = columnValuesArray
Me.Rows.Add(rowDTI_Content_TagsRow)
Return rowDTI_Content_TagsRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function FindById(ByVal Id As Integer) As DTI_Content_TagsRow
Return CType(Me.Rows.Find(New Object() {Id}),DTI_Content_TagsRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overridable Function GetEnumerator() As Global.System.Collections.IEnumerator Implements Global.System.Collections.IEnumerable.GetEnumerator
Return Me.Rows.GetEnumerator
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As DTI_Content_TagsDataTable = CType(MyBase.Clone,DTI_Content_TagsDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New DTI_Content_TagsDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columnId = MyBase.Columns("Id")
Me.columnTag_Name = MyBase.Columns("Tag_Name")
Me.columnMain_Id = MyBase.Columns("Main_Id")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columnId = New Global.System.Data.DataColumn("Id", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnId)
Me.columnTag_Name = New Global.System.Data.DataColumn("Tag_Name", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnTag_Name)
Me.columnMain_Id = New Global.System.Data.DataColumn("Main_Id", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnMain_Id)
Me.Constraints.Add(New Global.System.Data.UniqueConstraint("Constraint1", New Global.System.Data.DataColumn() {Me.columnId}, true))
Me.columnId.AutoIncrement = true
Me.columnId.AllowDBNull = false
Me.columnId.Unique = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewDTI_Content_TagsRow() As DTI_Content_TagsRow
Return CType(Me.NewRow,DTI_Content_TagsRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New DTI_Content_TagsRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(DTI_Content_TagsRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.DTI_Content_TagsRowChangedEvent) Is Nothing) Then
RaiseEvent DTI_Content_TagsRowChanged(Me, New DTI_Content_TagsRowChangeEvent(CType(e.Row,DTI_Content_TagsRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.DTI_Content_TagsRowChangingEvent) Is Nothing) Then
RaiseEvent DTI_Content_TagsRowChanging(Me, New DTI_Content_TagsRowChangeEvent(CType(e.Row,DTI_Content_TagsRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.DTI_Content_TagsRowDeletedEvent) Is Nothing) Then
RaiseEvent DTI_Content_TagsRowDeleted(Me, New DTI_Content_TagsRowChangeEvent(CType(e.Row,DTI_Content_TagsRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.DTI_Content_TagsRowDeletingEvent) Is Nothing) Then
RaiseEvent DTI_Content_TagsRowDeleting(Me, New DTI_Content_TagsRowChangeEvent(CType(e.Row,DTI_Content_TagsRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemoveDTI_Content_TagsRow(ByVal row As DTI_Content_TagsRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As dsTagger = New dsTagger()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "DTI_Content_TagsDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents the strongly named DataTable class.
'''</summary>
<Global.System.Serializable(), _
Global.System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")> _
Partial Public Class DTI_Content_Tag_PivotDataTable
Inherits Global.System.Data.DataTable
Implements Global.System.Collections.IEnumerable
Private columnId As Global.System.Data.DataColumn
Private columnComponent_Type As Global.System.Data.DataColumn
Private columnContent_Id As Global.System.Data.DataColumn
Private columnTag_Id As Global.System.Data.DataColumn
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New()
MyBase.New
Me.TableName = "DTI_Content_Tag_Pivot"
Me.BeginInit
Me.InitClass
Me.EndInit
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal table As Global.System.Data.DataTable)
MyBase.New
Me.TableName = table.TableName
If (table.CaseSensitive <> table.DataSet.CaseSensitive) Then
Me.CaseSensitive = table.CaseSensitive
End If
If (table.Locale.ToString <> table.DataSet.Locale.ToString) Then
Me.Locale = table.Locale
End If
If (table.Namespace <> table.DataSet.Namespace) Then
Me.Namespace = table.Namespace
End If
Me.Prefix = table.Prefix
Me.MinimumCapacity = table.MinimumCapacity
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Sub New(ByVal info As Global.System.Runtime.Serialization.SerializationInfo, ByVal context As Global.System.Runtime.Serialization.StreamingContext)
MyBase.New(info, context)
Me.InitVars
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property IdColumn() As Global.System.Data.DataColumn
Get
Return Me.columnId
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Component_TypeColumn() As Global.System.Data.DataColumn
Get
Return Me.columnComponent_Type
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Content_IdColumn() As Global.System.Data.DataColumn
Get
Return Me.columnContent_Id
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Tag_IdColumn() As Global.System.Data.DataColumn
Get
Return Me.columnTag_Id
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0"), _
Global.System.ComponentModel.Browsable(false)> _
Public ReadOnly Property Count() As Integer
Get
Return Me.Rows.Count
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Default ReadOnly Property Item(ByVal index As Integer) As DTI_Content_Tag_PivotRow
Get
Return CType(Me.Rows(index),DTI_Content_Tag_PivotRow)
End Get
End Property
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_Tag_PivotRowChanging As DTI_Content_Tag_PivotRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_Tag_PivotRowChanged As DTI_Content_Tag_PivotRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_Tag_PivotRowDeleting As DTI_Content_Tag_PivotRowChangeEventHandler
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Event DTI_Content_Tag_PivotRowDeleted As DTI_Content_Tag_PivotRowChangeEventHandler
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Sub AddDTI_Content_Tag_PivotRow(ByVal row As DTI_Content_Tag_PivotRow)
Me.Rows.Add(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overloads Function AddDTI_Content_Tag_PivotRow(ByVal Component_Type As String, ByVal Content_Id As Integer, ByVal Tag_Id As Integer) As DTI_Content_Tag_PivotRow
Dim rowDTI_Content_Tag_PivotRow As DTI_Content_Tag_PivotRow = CType(Me.NewRow,DTI_Content_Tag_PivotRow)
Dim columnValuesArray() As Object = New Object() {Nothing, Component_Type, Content_Id, Tag_Id}
rowDTI_Content_Tag_PivotRow.ItemArray = columnValuesArray
Me.Rows.Add(rowDTI_Content_Tag_PivotRow)
Return rowDTI_Content_Tag_PivotRow
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function FindById(ByVal Id As Integer) As DTI_Content_Tag_PivotRow
Return CType(Me.Rows.Find(New Object() {Id}),DTI_Content_Tag_PivotRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overridable Function GetEnumerator() As Global.System.Collections.IEnumerator Implements Global.System.Collections.IEnumerable.GetEnumerator
Return Me.Rows.GetEnumerator
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Overrides Function Clone() As Global.System.Data.DataTable
Dim cln As DTI_Content_Tag_PivotDataTable = CType(MyBase.Clone,DTI_Content_Tag_PivotDataTable)
cln.InitVars
Return cln
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function CreateInstance() As Global.System.Data.DataTable
Return New DTI_Content_Tag_PivotDataTable()
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub InitVars()
Me.columnId = MyBase.Columns("Id")
Me.columnComponent_Type = MyBase.Columns("Component_Type")
Me.columnContent_Id = MyBase.Columns("Content_Id")
Me.columnTag_Id = MyBase.Columns("Tag_Id")
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Private Sub InitClass()
Me.columnId = New Global.System.Data.DataColumn("Id", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnId)
Me.columnComponent_Type = New Global.System.Data.DataColumn("Component_Type", GetType(String), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnComponent_Type)
Me.columnContent_Id = New Global.System.Data.DataColumn("Content_Id", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnContent_Id)
Me.columnTag_Id = New Global.System.Data.DataColumn("Tag_Id", GetType(Integer), Nothing, Global.System.Data.MappingType.Element)
MyBase.Columns.Add(Me.columnTag_Id)
Me.Constraints.Add(New Global.System.Data.UniqueConstraint("Constraint1", New Global.System.Data.DataColumn() {Me.columnId}, true))
Me.columnId.AutoIncrement = true
Me.columnId.AllowDBNull = false
Me.columnId.Unique = true
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function NewDTI_Content_Tag_PivotRow() As DTI_Content_Tag_PivotRow
Return CType(Me.NewRow,DTI_Content_Tag_PivotRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function NewRowFromBuilder(ByVal builder As Global.System.Data.DataRowBuilder) As Global.System.Data.DataRow
Return New DTI_Content_Tag_PivotRow(builder)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Function GetRowType() As Global.System.Type
Return GetType(DTI_Content_Tag_PivotRow)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanged(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanged(e)
If (Not (Me.DTI_Content_Tag_PivotRowChangedEvent) Is Nothing) Then
RaiseEvent DTI_Content_Tag_PivotRowChanged(Me, New DTI_Content_Tag_PivotRowChangeEvent(CType(e.Row,DTI_Content_Tag_PivotRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowChanging(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowChanging(e)
If (Not (Me.DTI_Content_Tag_PivotRowChangingEvent) Is Nothing) Then
RaiseEvent DTI_Content_Tag_PivotRowChanging(Me, New DTI_Content_Tag_PivotRowChangeEvent(CType(e.Row,DTI_Content_Tag_PivotRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleted(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleted(e)
If (Not (Me.DTI_Content_Tag_PivotRowDeletedEvent) Is Nothing) Then
RaiseEvent DTI_Content_Tag_PivotRowDeleted(Me, New DTI_Content_Tag_PivotRowChangeEvent(CType(e.Row,DTI_Content_Tag_PivotRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Protected Overrides Sub OnRowDeleting(ByVal e As Global.System.Data.DataRowChangeEventArgs)
MyBase.OnRowDeleting(e)
If (Not (Me.DTI_Content_Tag_PivotRowDeletingEvent) Is Nothing) Then
RaiseEvent DTI_Content_Tag_PivotRowDeleting(Me, New DTI_Content_Tag_PivotRowChangeEvent(CType(e.Row,DTI_Content_Tag_PivotRow), e.Action))
End If
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub RemoveDTI_Content_Tag_PivotRow(ByVal row As DTI_Content_Tag_PivotRow)
Me.Rows.Remove(row)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Shared Function GetTypedTableSchema(ByVal xs As Global.System.Xml.Schema.XmlSchemaSet) As Global.System.Xml.Schema.XmlSchemaComplexType
Dim type As Global.System.Xml.Schema.XmlSchemaComplexType = New Global.System.Xml.Schema.XmlSchemaComplexType()
Dim sequence As Global.System.Xml.Schema.XmlSchemaSequence = New Global.System.Xml.Schema.XmlSchemaSequence()
Dim ds As dsTagger = New dsTagger()
Dim any1 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any1.Namespace = "http://www.w3.org/2001/XMLSchema"
any1.MinOccurs = New Decimal(0)
any1.MaxOccurs = Decimal.MaxValue
any1.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any1)
Dim any2 As Global.System.Xml.Schema.XmlSchemaAny = New Global.System.Xml.Schema.XmlSchemaAny()
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1"
any2.MinOccurs = New Decimal(1)
any2.ProcessContents = Global.System.Xml.Schema.XmlSchemaContentProcessing.Lax
sequence.Items.Add(any2)
Dim attribute1 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute1.Name = "namespace"
attribute1.FixedValue = ds.Namespace
type.Attributes.Add(attribute1)
Dim attribute2 As Global.System.Xml.Schema.XmlSchemaAttribute = New Global.System.Xml.Schema.XmlSchemaAttribute()
attribute2.Name = "tableTypeName"
attribute2.FixedValue = "DTI_Content_Tag_PivotDataTable"
type.Attributes.Add(attribute2)
type.Particle = sequence
Dim dsSchema As Global.System.Xml.Schema.XmlSchema = ds.GetSchemaSerializable
If xs.Contains(dsSchema.TargetNamespace) Then
Dim s1 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Dim s2 As Global.System.IO.MemoryStream = New Global.System.IO.MemoryStream()
Try
Dim schema As Global.System.Xml.Schema.XmlSchema = Nothing
dsSchema.Write(s1)
Dim schemas As Global.System.Collections.IEnumerator = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator
Do While schemas.MoveNext
schema = CType(schemas.Current,Global.System.Xml.Schema.XmlSchema)
s2.SetLength(0)
schema.Write(s2)
If (s1.Length = s2.Length) Then
s1.Position = 0
s2.Position = 0
Do While ((s1.Position <> s1.Length) _
AndAlso (s1.ReadByte = s2.ReadByte))
Loop
If (s1.Position = s1.Length) Then
Return type
End If
End If
Loop
Finally
If (Not (s1) Is Nothing) Then
s1.Close
End If
If (Not (s2) Is Nothing) Then
s2.Close
End If
End Try
End If
xs.Add(dsSchema)
Return type
End Function
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class DTI_Content_TagsRow
Inherits Global.System.Data.DataRow
Private tableDTI_Content_Tags As DTI_Content_TagsDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tableDTI_Content_Tags = CType(Me.Table,DTI_Content_TagsDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Id() As Integer
Get
Return CType(Me(Me.tableDTI_Content_Tags.IdColumn),Integer)
End Get
Set
Me(Me.tableDTI_Content_Tags.IdColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Tag_Name() As String
Get
Try
Return CType(Me(Me.tableDTI_Content_Tags.Tag_NameColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Tag_Name' in table 'DTI_Content_Tags' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableDTI_Content_Tags.Tag_NameColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Main_Id() As String
Get
Try
Return CType(Me(Me.tableDTI_Content_Tags.Main_IdColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Main_Id' in table 'DTI_Content_Tags' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableDTI_Content_Tags.Main_IdColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsTag_NameNull() As Boolean
Return Me.IsNull(Me.tableDTI_Content_Tags.Tag_NameColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetTag_NameNull()
Me(Me.tableDTI_Content_Tags.Tag_NameColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsMain_IdNull() As Boolean
Return Me.IsNull(Me.tableDTI_Content_Tags.Main_IdColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetMain_IdNull()
Me(Me.tableDTI_Content_Tags.Main_IdColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Represents strongly named DataRow class.
'''</summary>
Partial Public Class DTI_Content_Tag_PivotRow
Inherits Global.System.Data.DataRow
Private tableDTI_Content_Tag_Pivot As DTI_Content_Tag_PivotDataTable
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Friend Sub New(ByVal rb As Global.System.Data.DataRowBuilder)
MyBase.New(rb)
Me.tableDTI_Content_Tag_Pivot = CType(Me.Table,DTI_Content_Tag_PivotDataTable)
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Id() As Integer
Get
Return CType(Me(Me.tableDTI_Content_Tag_Pivot.IdColumn),Integer)
End Get
Set
Me(Me.tableDTI_Content_Tag_Pivot.IdColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Component_Type() As String
Get
Try
Return CType(Me(Me.tableDTI_Content_Tag_Pivot.Component_TypeColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Component_Type' in table 'DTI_Content_Tag_Pivot' is DBNull."& _
"", e)
End Try
End Get
Set
Me(Me.tableDTI_Content_Tag_Pivot.Component_TypeColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Content_Id() As Integer
Get
Try
Return CType(Me(Me.tableDTI_Content_Tag_Pivot.Content_IdColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Content_Id' in table 'DTI_Content_Tag_Pivot' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableDTI_Content_Tag_Pivot.Content_IdColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property Tag_Id() As Integer
Get
Try
Return CType(Me(Me.tableDTI_Content_Tag_Pivot.Tag_IdColumn),Integer)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'Tag_Id' in table 'DTI_Content_Tag_Pivot' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableDTI_Content_Tag_Pivot.Tag_IdColumn) = value
End Set
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsComponent_TypeNull() As Boolean
Return Me.IsNull(Me.tableDTI_Content_Tag_Pivot.Component_TypeColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetComponent_TypeNull()
Me(Me.tableDTI_Content_Tag_Pivot.Component_TypeColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsContent_IdNull() As Boolean
Return Me.IsNull(Me.tableDTI_Content_Tag_Pivot.Content_IdColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetContent_IdNull()
Me(Me.tableDTI_Content_Tag_Pivot.Content_IdColumn) = Global.System.Convert.DBNull
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Function IsTag_IdNull() As Boolean
Return Me.IsNull(Me.tableDTI_Content_Tag_Pivot.Tag_IdColumn)
End Function
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub SetTag_IdNull()
Me(Me.tableDTI_Content_Tag_Pivot.Tag_IdColumn) = Global.System.Convert.DBNull
End Sub
End Class
'''<summary>
'''Row event argument class
'''</summary>
<System.ComponentModel.Description("Row event argument class"),Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class DTI_Content_TagsRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As DTI_Content_TagsRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As DTI_Content_TagsRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As DTI_Content_TagsRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
'''<summary>
'''Row event argument class
'''</summary>
<System.ComponentModel.Description("Row event argument class"),Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Class DTI_Content_Tag_PivotRowChangeEvent
Inherits Global.System.EventArgs
Private eventRow As DTI_Content_Tag_PivotRow
Private eventAction As Global.System.Data.DataRowAction
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Sub New(ByVal row As DTI_Content_Tag_PivotRow, ByVal action As Global.System.Data.DataRowAction)
MyBase.New
Me.eventRow = row
Me.eventAction = action
End Sub
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Row() As DTI_Content_Tag_PivotRow
Get
Return Me.eventRow
End Get
End Property
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public ReadOnly Property Action() As Global.System.Data.DataRowAction
Get
Return Me.eventAction
End Get
End Property
End Class
End Class
|
Micmaz/DTIControls
|
DTITagManager/dsTagger.Designer.vb
|
Visual Basic
|
mit
| 63,856
|
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.PowerPacks
Friend Class frmMonthendBudget
Inherits System.Windows.Forms.Form
Dim WithEvents adoPrimaryRS As ADODB.Recordset
Dim mbChangedByCode As Boolean
Dim mvBookMark As Integer
Dim mbEditFlag As Boolean
Dim mbAddNewFlag As Boolean
Dim mbDataChanged As Boolean
Dim txtInteger As New List(Of TextBox)
Dim txtFloat As New List(Of TextBox)
Dim gID As Integer
Private Sub loadLanguage()
'frmMonthendBudget = No Code [Edit Month Budget]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then frmMonthendBudget.Caption = rsLang("LanguageLayoutLnk_Description"): MonthendBudget.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1074 'Undo|
If rsLang.RecordCount Then cmdCancel.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdCancel.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1004 'Exit|Checked
If rsLang.RecordCount Then cmdClose.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : cmdClose.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 1010 'General|Checked
If rsLang.RecordCount Then _lbl_5.Text = rsLang.Fields("LanguageLayoutLnk_Description").Value : _lbl_5.RightToLeft = rsLang.Fields("LanguageLayoutLnk_RightTL").Value
'lblLabels(38) = No Code [Month End]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then lblLabels(38).Caption = rsLang("LanguageLayoutLnk_Description"): lblLabels(38).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lblLabels_0 = No Code [Number of expected Day Ends in the Month]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lblLabels_0.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lblLabels_1 = No Code [Total Budget of Purchases for the Month]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lblLabels_1.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
'_lblLabels_2 = No Code [Total Budget of Sales for the Month]
'rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
'If rsLang.RecordCount Then _lblLabels_2.Caption = rsLang("LanguageLayoutLnk_Description"): _lblLabels_2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
rsHelp.filter = "Help_Section=0 AND Help_Form='" & Me.Name & "'"
'UPGRADE_ISSUE: Form property frmMonthendBudget.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
If rsHelp.RecordCount Then Me.ToolTip1 = rsHelp.Fields("Help_ContextID").Value
End Sub
Private Sub buildDataControls()
' doDataControl Me.cmbChannel, "SELECT ChannelID, Channel_Name FROM Channel ORDER BY ChannelID", "Customer_ChannelID", "ChannelID", "Channel_Name"
End Sub
Private Sub doDataControl(ByRef dataControl As System.Windows.Forms.Control, ByRef sql As String, ByRef DataField As String, ByRef boundColumn As String, ByRef listField As String)
'Dim rs As ADODB.Recordset
'rs = getRS(sql)
'UPGRADE_WARNING: Couldn't resolve default property of object dataControl.DataSource. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'dataControl.DataSource = rs
'UPGRADE_ISSUE: Control method dataControl.DataSource was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
'dataControl.DataSource = adoPrimaryRS
'UPGRADE_ISSUE: Control method dataControl.DataField was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
'dataControl.DataField = DataField
'UPGRADE_WARNING: Couldn't resolve default property of object dataControl.boundColumn. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'dataControl.boundColumn = boundColumn
'UPGRADE_WARNING: Couldn't resolve default property of object dataControl.listField. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
'dataControl.listField = listField
End Sub
Public Sub loadItem(ByRef id As Integer)
Dim oText As System.Windows.Forms.TextBox
adoPrimaryRS = getRS("SELECT MonthEnd.MonthEndID, IIf([MonthEndID]=[Company_MonthEndID],'Current',[Company_MonthEndID]-[MonthEndID] & ' month/s ago') AS theMonth, MonthEnd.MonthEnd_Days, MonthEnd.MonthEnd_BudgetSales, MonthEnd.MonthEnd_BudgetPurchases From MonthEnd, Company Where MonthEnd.MonthEndID = " & id)
setup()
Me.lblMonth.Text = adoPrimaryRS.Fields("theMonth").Value
' For Each oText In Me.txtFields
' Set oText.DataBindings.Add(adoPrimaryRS)
' oText.MaxLength = adoPrimaryRS(oText.DataField).DefinedSize
' Next
For Each oText In txtInteger
oText.DataBindings.Add(adoPrimaryRS)
AddHandler oText.Leave, AddressOf txtInteger_Leave
'txtInteger_Leave(txtInteger.Item((oText.Index)), New System.EventArgs())
Next oText
For Each oText In txtFloat
oText.DataBindings.Add(adoPrimaryRS)
If oText.Text = "" Then oText.Text = "0"
oText.Text = CStr(CDbl(oText.Text) * 100)
AddHandler oText.Leave, AddressOf txtFloat_Leave
'txtFloat_Leave(txtFloat.Item((oText.Index)), New System.EventArgs())
Next oText
' For Each oText In Me.txtFloatNegative
' Set oText.DataBindings.Add(adoPrimaryRS)
' If oText.Text = "" Then oText.Text = "0"
' oText.Text = oText.Text * 100
' txtFloatNegative_LostFocus oText.Index
' Next
'Bind the check boxes to the data provider
' For Each oCheck In Me.chkFields
' Set oCheck.DataBindings.Add(adoPrimaryRS)
' Next
buildDataControls()
mbDataChanged = False
loadLanguage()
ShowDialog()
End Sub
Private Sub setup()
End Sub
Private Sub frmMonthendBudget_Load(sender As Object, e As System.EventArgs) Handles Me.Load
txtFloat.AddRange(New TextBox() {_txtFloat_0, _txtFloat_1})
txtInteger.AddRange(New TextBox() {_txtInteger_0})
Dim tb As New TextBox
For Each tb In txtFloat
AddHandler tb.Enter, AddressOf txtFloat_Enter
AddHandler tb.KeyPress, AddressOf txtFloat_KeyPress
Next
For Each tb In txtInteger
AddHandler tb.Enter, AddressOf txtInteger_Enter
AddHandler tb.KeyPress, AddressOf txtInteger_KeyPress
Next
End Sub
'UPGRADE_WARNING: Event frmMonthendBudget.Resize may fire when form is initialized. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="88B12AE1-6DE0-48A0-86F1-60C0686C026A"'
Private Sub frmMonthendBudget_Resize(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Resize
Dim cmdLast As New Button
Dim cmdnext As New Button
Dim lblStatus As New Label
On Error Resume Next
lblStatus.Width = pixelToTwips(Me.Width, True) - 1500
cmdnext.Left = lblStatus.Width + 700
cmdLast.Left = cmdnext.Left + 340
End Sub
Private Sub frmMonthendBudget_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
If mbEditFlag Or mbAddNewFlag Then GoTo EventExitSub
Select Case KeyAscii
Case System.Windows.Forms.Keys.Escape
KeyAscii = 0
cmdClose.Focus()
System.Windows.Forms.Application.DoEvents()
adoPrimaryRS.Move(0)
cmdClose_Click(cmdClose, New System.EventArgs())
End Select
EventExitSub:
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub frmMonthendBudget_FormClosed(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
End Sub
Private Sub adoPrimaryRS_MoveComplete(ByVal adReason As ADODB.EventReasonEnum, ByVal pError As ADODB.Error, ByRef adStatus As ADODB.EventStatusEnum, ByVal pRecordset As ADODB.Recordset) Handles adoPrimaryRS.MoveComplete
'This will display the current record position for this recordset
End Sub
Private Sub adoPrimaryRS_WillChangeRecord(ByVal adReason As ADODB.EventReasonEnum, ByVal cRecords As Integer, ByRef adStatus As ADODB.EventStatusEnum, ByVal pRecordset As ADODB.Recordset) Handles adoPrimaryRS.WillChangeRecord
'This is where you put validation code
'This event gets called when the following actions occur
Dim bCancel As Boolean
Select Case adReason
Case ADODB.EventReasonEnum.adRsnAddNew
Case ADODB.EventReasonEnum.adRsnClose
Case ADODB.EventReasonEnum.adRsnDelete
Case ADODB.EventReasonEnum.adRsnFirstChange
Case ADODB.EventReasonEnum.adRsnMove
Case ADODB.EventReasonEnum.adRsnRequery
Case ADODB.EventReasonEnum.adRsnResynch
Case ADODB.EventReasonEnum.adRsnUndoAddNew
Case ADODB.EventReasonEnum.adRsnUndoDelete
Case ADODB.EventReasonEnum.adRsnUndoUpdate
Case ADODB.EventReasonEnum.adRsnUpdate
End Select
If bCancel Then adStatus = ADODB.EventStatusEnum.adStatusCancel
End Sub
Private Sub cmdCancel_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdCancel.Click
On Error Resume Next
If mbAddNewFlag Then
Me.Close()
Else
mbEditFlag = False
mbAddNewFlag = False
adoPrimaryRS.CancelUpdate()
If mvBookMark > 0 Then
adoPrimaryRS.Bookmark = mvBookMark
Else
adoPrimaryRS.MoveFirst()
End If
mbDataChanged = False
End If
End Sub
Private Function update_Renamed() As Boolean
On Error GoTo UpdateErr
update_Renamed = True
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll)
If mbAddNewFlag Then
adoPrimaryRS.MoveLast() 'move to the new record
End If
mbEditFlag = False
mbAddNewFlag = False
mbDataChanged = False
Exit Function
UpdateErr:
MsgBox(Err.Description)
update_Renamed = False
End Function
Private Sub cmdClose_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles cmdClose.Click
cmdClose.Focus()
System.Windows.Forms.Application.DoEvents()
If update_Renamed() Then
Me.Close()
End If
End Sub
Private Sub txtFields_MyGotFocus(ByRef Index As Short)
' GotFocus txtFields(Index)
End Sub
Private Sub txtInteger_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim txtBox As New TextBox
txtBox = DirectCast(eventSender, TextBox)
Dim Index As Integer = GetIndexer(txtBox, txtInteger)
MyGotFocusNumeric(txtInteger(Index))
End Sub
Private Sub txtInteger_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs)
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
'Dim Index As Short = txtInteger.GetIndex(eventSender)
MyKeyPress(KeyAscii)
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub txtInteger_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim txtBox As New TextBox
txtBox = DirectCast(eventSender, TextBox)
Dim Index As Integer = GetIndexer(txtBox, txtInteger)
MyLostFocus(txtInteger(Index), 0)
End Sub
Private Sub txtFloat_Enter(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim txtBox As New TextBox
txtBox = DirectCast(eventSender, TextBox)
Dim Index As Integer = GetIndexer(txtBox, txtFloat)
MyGotFocusNumeric(txtFloat(Index))
End Sub
Private Sub txtFloat_KeyPress(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.KeyPressEventArgs)
Dim KeyAscii As Short = Asc(eventArgs.KeyChar)
'Dim Index As Short = txtFloat.GetIndex(eventSender)
MyKeyPress(KeyAscii)
eventArgs.KeyChar = Chr(KeyAscii)
If KeyAscii = 0 Then
eventArgs.Handled = True
End If
End Sub
Private Sub txtFloat_Leave(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
Dim txtBox As New TextBox
txtBox = DirectCast(eventSender, TextBox)
Dim Index As Integer = GetIndexer(txtBox, txtFloat)
MyLostFocus(txtFloat(Index), 2)
End Sub
Private Sub txtFloatNegative_MyGotFocus(ByRef Index As Short)
' MyGotFocusNumeric txtFloatNegative(Index)
End Sub
Private Sub txtFloatNegative_KeyPress(ByRef Index As Short, ByRef KeyAscii As Short)
' KeyPressNegative txtFloatNegative(Index), KeyAscii
End Sub
Private Sub txtFloatNegative_MyLostFocus(ByRef Index As Short)
' LostFocus txtFloatNegative(Index), 2
End Sub
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmMonthendBudget.vb
|
Visual Basic
|
mit
| 13,731
|
'------------------------------------------------------------------------------
' <auto-generated>
' 此代码由工具生成。
' 运行时版本:4.0.30319.18408
'
' 对此文件的更改可能会导致不正确的行为,并且如果
' 重新生成代码,这些更改将会丢失。
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
|
yyc12345/bus_rode_windows
|
bus_rode_compression/My Project/Application.Designer.vb
|
Visual Basic
|
mit
| 445
|
Imports LiteDB
Imports Markdig
Partial Class OrganizationPage
Inherits Page
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim orgName = Request.QueryString("org")
If orgName Is Nothing Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
Dim orgId As Integer
If Not Integer.TryParse(orgName, orgId) Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
Dim orgTbl = db.GetCollection(Of Organization)("Organizations")
Dim buyTbl = db.GetCollection(Of Purchase)("Purchases")
Dim gigTbl = db.GetCollection(Of JobProposal)("Proposals")
Dim usrTbl = db.GetCollection(Of User)("Users")
Dim org = orgTbl.FindById(orgId)
If org Is Nothing Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
If DateTime.Now.Year <> org.LastUpdatedYear OrElse DateTime.Now.Month <> org.LastUpdatedMonth Then
org.Points = org.MonthlyPoints + 1
org.LastUpdatedMonth = DateTime.Now.Month
org.LastUpdatedYear = DateTime.Now.Year
orgTbl.Update(org)
End If
Dim jobs = gigTbl.FindAll.Where(Function(x) Not x.Disabled AndAlso x.OffererOrg IsNot Nothing AndAlso x.OffererOrg = org.Id)
If jobs.Count = 0 Then
lblJobs.Text = "This organization has no jobs available"
Else
lblJobs.Text = "<table style='table-layout: fixed; width: 100%;' cellpadding='10px'>"
For Each job In jobs
lblJobs.Text &= RowOf(job.ImageURLs(0), job.Title, job.ShortDescription, "JobPage.aspx?job=" & job.Id)
Next
lblJobs.Text &= "</table>"
End If
Dim interactions = buyTbl.FindAll().Select(Function(x) New Tuple(Of Purchase, JobProposal)(x, gigTbl.FindById(x.Proposal))).Where(Function(x) x.Item2.Type = GigType.OfferJob AndAlso x.Item2.OffererOrg = org.Id)
Dim interactionsNum = interactions.Where(Function(x) x.Item1.HasBeenDelivered AndAlso x.Item1.HasBeenPaid).Count
Dim inn = interactions.Count
Dim rating As Decimal = 0.0
For Each i In interactions
If i.Item1.Rating < 1 Then
inn -= 1
End If
rating += i.Item1.Rating
Next
If inn = 0 Then
rating = 0
Else
rating /= interactionsNum
End If
Dim pipeline = New MarkdownPipelineBuilder().UseAdvancedExtensions().Build()
lblAbout.Text = Markdown.ToHtml(org.Description, pipeline)
lblAddress.Text = org.Position.Address
lblCash.Text = org.MonthlyPoints
lblEXP.Text = org.RequestMonthlyUsers
lblOrgName.Text = org.OrganizationName
lblInteractions.Text = "Successful interactions - " & interactionsNum ' TODO: implement interactions & interaction counter
lblOpeningHours.Text = "Opened:" & org.OpeningHours
lblAudience.Text = "For: " & org.Audience
lblRating.Text = rating & " <span style=""color: gold"">" & New String("★", Math.Ceiling(rating))
Image1.ImageUrl = org.ImageLoc
If org.Rejected Then
pnlRejected.Visible = True
ElseIf Not org.Approved Then
pnlNotApproved.Visible = True
End If
Dim owner = db.GetCollection(Of User)("Users").FindById(org.OwnerID)
If (Not org.Approved) AndAlso (Session("UserID") Is Nothing OrElse (Session("UserID") <> owner.Id AndAlso db.GetCollection(Of User)("Users").FindById(New BsonValue(Session("UserID"))).UserLevel < 2)) Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
If Not Session("UserID") Is Nothing AndAlso ((Not owner Is Nothing AndAlso Session("UserID") = owner.Id) OrElse db.GetCollection(Of User)("Users").FindById(New BsonValue(Session("UserID"))).UserLevel > 1) Then
btnEdit.Visible = True
Else
btnEdit.Visible = False
End If
If Not Session("UserID") Is Nothing AndAlso (db.GetCollection(Of User)("Users").FindById(New BsonValue(Session("UserID"))).UserLevel > UserType.Regular) Then
If Not (org.Approved OrElse org.Rejected) Then
pnlApprRej.Visible = True
ElseIf org.Rejected Then
pnlReAppr.Visible = True
End If
End If
End Using
End Sub
Public Sub Edit(ByVal sender As Object, ByVal e As EventArgs) Handles btnEdit.Click
Dim orgId As Integer
If Request.QueryString("org") Is Nothing OrElse Not Integer.TryParse(Request.QueryString("org"), orgId) Then
Utils.Alert("Something went wrong2... ")
Return
End If
Using db As LiteDatabase = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
Dim tblUsers As LiteCollection(Of User) = db.GetCollection(Of User)("Users")
Dim tblOrgs = db.GetCollection(Of Organization)("Organizations")
Dim org = tblOrgs.FindById(orgId)
Dim curuser As User = tblUsers.FindById(Integer.Parse(Session("UserID")))
If curuser Is Nothing Or org Is Nothing Then
Utils.Alert("Something went wrong... ")
Return
End If
If Session("UserID") = org.OwnerID OrElse curuser.UserLevel > UserType.Regular Then
Response.Redirect("/EditOrganization.aspx?org=" & orgId)
Else
Utils.Alert("You don't have the permission to edit this organization.")
End If
End Using
End Sub
Public Sub Message(sender As Object, e As EventArgs) Handles btnMsg.Click
Using db = New LiteDatabase(Server.MapPath("~/App_Data/Database.accdb"))
Dim orgName = Request.QueryString("org")
If orgName Is Nothing Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
Dim orgId As Integer
If Not Integer.TryParse(orgName, orgId) Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
Dim orgTbl = db.GetCollection(Of Organization)("Organizations")
Dim org = orgTbl.FindById(orgId)
If org Is Nothing Then
pnlUser.Visible = False
pnlNotFound.Visible = True
Return
End If
Response.Redirect("Conversation.aspx?to=" & org.OwnerID)
End Using
End Sub
Public Function RowOf(img As String, title As String, desc As String, href As String) As String
Return String.Format("<tr><td style='width: 20%;'><img src='{0}' style='width: 100%; height: auto;'/></td><td><a href='{1}'><h2 style='color: black'>{2}</h2></a><span style='color: darkgray'>{3}</span></td></tr>", img, href, title, desc)
End Function
End Class
|
yotam180/DeedCoin
|
OrganizationPage.aspx.vb
|
Visual Basic
|
mit
| 7,508
|
Imports SFDL.NET3.NativeMethods
Public Class StandyHandler
Public Shared Function PreventStandby() As NativeMethods.EXECUTION_STATE
Try
Return NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED Or EXECUTION_STATE.ES_CONTINUOUS Or EXECUTION_STATE.ES_DISPLAY_REQUIRED)
Catch ex As Exception
Return NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
End Try
End Function
Public Shared Function Reset() As NativeMethods.EXECUTION_STATE
Try
Return NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
Catch ex As Exception
Return NativeMethods.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS)
End Try
End Function
Public Shared Sub SetStandby()
SetSuspendState(False, True, True)
End Sub
End Class
|
n0ix/SFDL.NET
|
SFDL.NET 3/Classes/StandbyHandler.vb
|
Visual Basic
|
mit
| 893
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("VBCreateContactWithCustomProperty")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Independentsoft")>
<Assembly: AssemblyProduct("VBCreateContactWithCustomProperty")>
<Assembly: AssemblyCopyright("Copyright © Independentsoft 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d925bc01-3f3b-4794-88e4-61d7a72d9b79")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBCreateContactWithCustomProperty/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,214
|
#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 TradeWright.Trading.Utils.Contracts
Imports TradeWright.Trading.Utils.Sessions
Public Interface IStrategyHostModel
Property Clock As TWUtilities40.Clock
Property Contract As IContract
Property ContractStorePrimary As IContractStore
Property ContractStoreSecondary As IContractStore
Property HistoricalDataStoreInput As HistDataUtils27.IHistoricalDataStore
Property IsTickReplay As Boolean
Property LogDummyProfitProfile As Boolean
Property LogParameters As Boolean
Property LogProfitProfile As Boolean
Property OrderSubmitterFactoryLive As OrderUtils27.IOrderSubmitterFactory
Property OrderSubmitterFactorySimulated As OrderUtils27.IOrderSubmitterFactory
Property RealtimeTickers As TickerUtils27.Tickers
Property ResultsPath As String
Property SeparateSessions As Boolean
Property Session As Session
Property ShowChart As Boolean
Property StopStrategyFactoryClassName As String
Property StrategyClassName As String
Property StudyLibraryManager As StudyUtils27.StudyLibraryManager
Property Symbol As IContractSpecifier
Property Ticker As TickerUtils27.Ticker
Property TickFileSpecifiers As TickfileUtils27.TickFileSpecifiers
Property TickfileStoreInput As TickfileUtils27.ITickfileStore
Property UseLiveBroker As Boolean
Property UseMoneyManagement As Boolean
End Interface
|
tradewright/tradebuild-platform.net
|
src/StrategyUtils/IStrategyHostModel.vb
|
Visual Basic
|
mit
| 2,570
|
' 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.Completion
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
Public Class ObjectInitializerCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Public Sub New(workspaceFixture As VisualBasicTestWorkspaceFixture)
MyBase.New(workspaceFixture)
End Sub
Protected Overrides Async Function VerifyWorkerAsync(
code As String, position As Integer,
expectedItemOrNull As String, expectedDescriptionOrNull As String,
sourceCodeKind As SourceCodeKind, usePreviousCharAsTrigger As Boolean,
checkForAbsence As Boolean, glyph As Integer?, matchPriority As Integer?,
hasSuggestionItem As Boolean?, displayTextSuffix As String, inlineDescription As String) As Task
' Script/interactive support removed for now.
' TODO: Re-enable these when interactive is back in the product.
If sourceCodeKind <> SourceCodeKind.Regular Then
Return
End If
Await BaseVerifyWorkerAsync(
code, position, expectedItemOrNull, expectedDescriptionOrNull,
sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph,
matchPriority, hasSuggestionItem, displayTextSuffix, inlineDescription)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNothingToShow() As Task
Dim text = <a>Public Class C
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Class</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<WorkItem(530075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530075")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNotInArgumentList() As Task
Dim text = <a>Public Class C
Property A As Integer
End Class
Class Program
Sub goo()
Dim a = new C(1, .$$
End Sub
End Class</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOneItem() As Task
Dim text = <a>Public Class C
Public bar as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldAndProperty() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "goo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestFieldAndPropertyBaseTypes() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Public Class D
Inherits C
End Class
Class Program
Sub goo()
Dim a as D = new D With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "goo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestMembersFromObjectInitializerSyntax() As Task
Dim text = <a>Public Class C
End Class
Public Class D
Inherits C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a as C = new D With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "goo")
End Function
<WorkItem(24612, "https://github.com/dotnet/roslyn/issues/24612")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectInitializerOfGenericTypeСonstraint1() As Task
Dim text = <a>Class C
Public Function testSub(Of T As {IExample, New})()
Return New T With { .$$
End Function
End Class
Interface IExample
Property A As String
Property B As String
End Interface</a>.Value
Await VerifyItemExistsAsync(text, "A")
Await VerifyItemExistsAsync(text, "B")
End Function
<WorkItem(24612, "https://github.com/dotnet/roslyn/issues/24612")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectInitializerOfGenericTypeСonstraint2() As Task
Dim text = <a>Class C
Public Function testSub(Of T As {New})()
Return New T With { .$$
End Function
End Class
</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<WorkItem(24612, "https://github.com/dotnet/roslyn/issues/24612")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectInitializerOfGenericTypeСonstraint3() As Task
Dim text = <a>Class C
Public Function testSub(Of T As {Structure})()
Return New T With {.$$
End Function
End Class
</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestOneItemAfterComma() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .goo = 3, .b$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemIsAbsentAsync(text, "goo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNothingLeftToShow() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .goo = 3, .bar = 3, .$$
End Sub
End Program</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestWithoutAsClause() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a = new C With { .$$
End Sub
End Program</a>.Value
Await VerifyItemExistsAsync(text, "bar")
Await VerifyItemExistsAsync(text, "goo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestWithoutAsClauseNothingLeftToShow() As Task
Dim text = <a>Public Class C
Public bar as Integer
Public Property goo as Integer
End Class
Class Program
Sub goo()
Dim a = new C With { .goo = 3, .bar = 3, .$$
End Sub
End Program</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<WorkItem(544326, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544326")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestInactiveInRValue() As Task
Dim text = <a>Class C
Public X As Long = 1
Public Y As Long = 2
End Class
Module Program
Sub Main(args As String())
Dim a As C = New C() With {.X = .$$}
End Sub
End Module</a>.Value
Await VerifyNoItemsExistAsync(text)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoBackingFields() As Task
Dim text = <a>Class C
Public Property Goo As Integer
Sub M()
Dim c As New C With { .$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "Goo")
Await VerifyItemIsAbsentAsync(text, "_Goo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestReadOnlyPropertiesAreNotPresentOnLeftSide() As Task
Dim text = <a>Class C
Public Property Goo As Integer
Public ReadOnly Property Bar As Integer
Get
Return 0
End Get
End Property
Sub M()
Dim c As New C With { .$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "Goo")
Await VerifyItemIsAbsentAsync(text, "Bar")
End Function
<WorkItem(545881, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545881")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoReadonlyFieldsOrProperties() As Task
Dim text = <a>Module M
Sub Main()
Dim x = New Exception With { .$$
End Sub
End Module
</a>.Value
Await VerifyItemIsAbsentAsync(text, "Data")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoParameterizedProperties() As Task
Dim text = <a>Module M
Module M
Sub Main()
Dim y = New List(Of Integer()) With {.Capacity = 10, .$$
End Sub
End Module
</a>.Value
Await VerifyItemIsAbsentAsync(text, "Item")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestShowParameterizedPropertiesWithAllOptionalArguments() As Task
Dim text = <a>Imports System
Public Class AImpl
Property P(Optional x As Integer = 3, Optional y As Integer = 2) As Object
Get
Console.WriteLine("P[{0}, {1}].get", x, y)
Return Nothing
End Get
Set(value As Object)
Console.WriteLine("P[{0}, {1}].set", x, y)
End Set
End Property
Sub Goo()
Dim z = New AImpl With {.$$
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "P")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestDoNotShowParameterizedPropertiesWithSomeMandatoryArguments() As Task
Dim text = <a>Imports System
Public Class AImpl
Property P(x As Integer, Optional y As Integer = 2) As Object
Get
Console.WriteLine("P[{0}, {1}].get", x, y)
Return Nothing
End Get
Set(value As Object)
Console.WriteLine("P[{0}, {1}].set", x, y)
End Set
End Property
Sub Goo()
Dim z = New AImpl With {.$$
End Sub
End Class</a>.Value
Await VerifyItemIsAbsentAsync(text, "P")
End Function
<WorkItem(545844, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545844")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestParameterizedPropertiesWithParamArrays() As Task
Dim text = <a>Option Strict On
Class C
Property P(ParamArray args As Object()) As Object
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
Property Q(o As Object, ParamArray args As Object()) As Object
Get
Return Nothing
End Get
Set(value As Object)
End Set
End Property
Shared Sub M()
Dim o As C
o = New C With {.$$
End Sub
End Class
</a>.Value
Await VerifyItemExistsAsync(text, "P")
Await VerifyItemIsAbsentAsync(text, "Q")
End Function
<WorkItem(530491, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530491")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestObjectInitializerOnInterface() As Task
Dim text = <a><![CDATA[Option Strict On
Imports System.Runtime.InteropServices
Module Program
Sub Main(args As String())
Dim x = New I With {.$$}
End Sub
End Module
<ComImport>
<Guid("EAA4976A-45C3-4BC5-BC0B-E474F4C3C83F")>
<CoClass(GetType(C))>
Interface I
Property c As Integer
End Interface
Class C
Public Property c As Integer
End Class
]]></a>.Value
Await VerifyItemExistsAsync(text, "c")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function IsCommitCharacterTest() As Task
Const code = "
Public Class C
Public bar as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Program"
Await VerifyCommonCommitCharactersAsync(code, textTypedSoFar:="")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestIsExclusive() As Task
Dim text = <Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="VBDocument">
Public Class C
Public bar as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Program</Document>
</Project>
</Workspace>
Using workspace = TestWorkspace.Create(text)
Dim hostDocument = workspace.Documents.First()
Dim caretPosition = hostDocument.CursorPosition.Value
Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id)
Dim service = GetCompletionService(workspace)
Dim completionList = Await GetCompletionListAsync(service, document, caretPosition, CompletionTrigger.Invoke)
Assert.True(completionList Is Nothing OrElse completionList.GetTestAccessor().IsExclusive, "Expected always exclusive")
End Using
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function SendEnterThroughToEditorTest() As Task
Const code = "
Public Class C
Public bar as Integer
End Class
Class Program
Sub goo()
Dim a as C = new C With { .$$
End Sub
End Program"
Await VerifySendEnterThroughToEditorAsync(code, "bar", expected:=False)
End Function
<WorkItem(26560, "https://github.com/dotnet/roslyn/issues/26560")>
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestKeywordsEscaped() As Task
Dim text = <a>Class C
Public Property [Wend] As Integer
Public Property [New] As Integer
Public Property A As Integer
End Class
Class Program
Sub Main()
Dim c As New C With { .$$ }
End Sub
End Class</a>.Value
Await VerifyItemExistsAsync(text, "[Wend]")
Await VerifyItemExistsAsync(text, "[New]")
Await VerifyItemExistsAsync(text, "A")
Await VerifyItemIsAbsentAsync(text, "Wend")
Await VerifyItemIsAbsentAsync(text, "New")
End Function
Friend Overrides Function CreateCompletionProvider() As CompletionProvider
Return New ObjectInitializerCompletionProvider()
End Function
End Class
End Namespace
|
swaroop-sridhar/roslyn
|
src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/ObjectInitializerCompletionProviderTests.vb
|
Visual Basic
|
apache-2.0
| 16,125
|
' 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.EncapsulateField
Imports Microsoft.CodeAnalysis.Formatting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.EncapsulateField
<ExportLanguageService(GetType(AbstractEncapsulateFieldService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicEncapsulateFieldService
Inherits AbstractEncapsulateFieldService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overrides Async Function RewriteFieldNameAndAccessibilityAsync(originalFieldName As String,
makePrivate As Boolean,
document As Document,
declarationAnnotation As SyntaxAnnotation,
cancellationToken As CancellationToken) As Task(Of SyntaxNode)
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim fieldIdentifier = root.GetAnnotatedNodes(Of ModifiedIdentifierSyntax)(declarationAnnotation).FirstOrDefault()
' There may be no field to rewrite if this document is part of a set of linked files
' and the declaration is not conditionally compiled in this document's project.
If fieldIdentifier Is Nothing Then
Return root
End If
Dim identifier = fieldIdentifier.Identifier
Dim annotation = New SyntaxAnnotation()
Dim escapedName = originalFieldName.EscapeIdentifier()
Dim newIdentifier = SyntaxFactory.Identifier(
text:=escapedName,
isBracketed:=escapedName <> originalFieldName,
identifierText:=originalFieldName,
typeCharacter:=TypeCharacter.None)
root = root.ReplaceNode(fieldIdentifier, fieldIdentifier.WithIdentifier(newIdentifier).WithAdditionalAnnotations(annotation, Formatter.Annotation))
fieldIdentifier = root.GetAnnotatedNodes(Of ModifiedIdentifierSyntax)(annotation).First()
If (DirectCast(fieldIdentifier.Parent, VariableDeclaratorSyntax).Names.Count = 1) Then
Dim fieldDeclaration = DirectCast(fieldIdentifier.Parent.Parent, FieldDeclarationSyntax)
Dim modifierKinds = {SyntaxKind.FriendKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.PrintStatement, SyntaxKind.PublicKeyword}
If makePrivate Then
Dim useableModifiers = fieldDeclaration.Modifiers.Where(Function(m) Not modifierKinds.Contains(m.Kind))
Dim newModifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)).Concat(useableModifiers)
Dim updatedDeclaration = fieldDeclaration.WithModifiers(SyntaxFactory.TokenList(newModifiers)) _
.WithLeadingTrivia(fieldDeclaration.GetLeadingTrivia()) _
.WithTrailingTrivia(fieldDeclaration.GetTrailingTrivia()) _
.WithAdditionalAnnotations(Formatter.Annotation)
Return root.ReplaceNode(fieldDeclaration, updatedDeclaration)
End If
End If
Return root
End Function
Protected Overrides Async Function GetFieldsAsync(document As Document, span As TextSpan, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of IFieldSymbol))
Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False)
Dim semanticModel = Await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(False)
Dim fields = root.DescendantNodes(Function(n) n.Span.IntersectsWith(span)) _
.OfType(Of FieldDeclarationSyntax)() _
.Where(Function(n) n.Span.IntersectsWith(span) AndAlso CanEncapsulate(n))
Dim names As IEnumerable(Of ModifiedIdentifierSyntax)
If span.IsEmpty Then
' no selection, get all variables
names = fields.SelectMany(Function(f) f.Declarators.SelectMany(Function(d) d.Names))
Else
' has selection, get only the ones that are included in the selection
names = fields.SelectMany(Function(f) f.Declarators.SelectMany(Function(d) d.Names.Where(Function(n) n.Span.IntersectsWith(span))))
End If
Return names.Select(Function(n) semanticModel.GetDeclaredSymbol(n)).
OfType(Of IFieldSymbol)().
WhereNotNull().
Where(Function(f) f.Name.Length > 0).
ToImmutableArray()
End Function
Private Function CanEncapsulate(field As FieldDeclarationSyntax) As Boolean
Return TypeOf field.Parent Is TypeBlockSyntax
End Function
Protected Function MakeUnique(baseName As String, originalFieldName As String, containingType As INamedTypeSymbol, Optional willChangeFieldName As Boolean = True) As String
If willChangeFieldName Then
Return NameGenerator.GenerateUniqueName(baseName, containingType.MemberNames.Where(Function(x) x <> originalFieldName).ToSet(), StringComparer.OrdinalIgnoreCase)
Else
Return NameGenerator.GenerateUniqueName(baseName, containingType.MemberNames.ToSet(), StringComparer.OrdinalIgnoreCase)
End If
End Function
Protected Overrides Function GenerateFieldAndPropertyNames(field As IFieldSymbol) As (fieldName As String, propertyName As String)
' If the field is marked shadows, it will keep its name.
If field.DeclaredAccessibility = Accessibility.Private OrElse IsShadows(field) Then
Dim propertyName = GeneratePropertyName(field.Name)
propertyName = MakeUnique(propertyName, field)
Return (field.Name, propertyName)
Else
Dim propertyName = GeneratePropertyName(field.Name)
Dim containingTypeMemberNames = field.ContainingType.GetAccessibleMembersInThisAndBaseTypes(Of ISymbol)(field.ContainingType).Select(Function(s) s.Name)
propertyName = NameGenerator.GenerateUniqueName(propertyName, containingTypeMemberNames.Where(Function(m) m <> field.Name).ToSet(), StringComparer.OrdinalIgnoreCase)
Dim newFieldName = MakeUnique("_" + Char.ToLower(propertyName(0)) + propertyName.Substring(1), field)
Return (newFieldName, propertyName)
End If
End Function
Private Function IsShadows(field As IFieldSymbol) As Boolean
Return field.DeclaringSyntaxReferences.Any(Function(d) d.GetSyntax().GetAncestor(Of FieldDeclarationSyntax)().Modifiers.Any(SyntaxKind.ShadowsKeyword))
End Function
Private Function MakeUnique(propertyName As String, field As IFieldSymbol) As String
Dim containingTypeMemberNames = field.ContainingType.GetAccessibleMembersInThisAndBaseTypes(Of ISymbol)(field.ContainingType).Select(Function(s) s.Name)
Return NameGenerator.GenerateUniqueName(propertyName, containingTypeMemberNames.ToSet(), StringComparer.OrdinalIgnoreCase)
End Function
Friend Overrides Function GetConstructorNodes(containingType As INamedTypeSymbol) As IEnumerable(Of SyntaxNode)
Return containingType.Constructors.SelectMany(Function(c As IMethodSymbol)
Return c.DeclaringSyntaxReferences.Select(Function(d) d.GetSyntax().Parent)
End Function)
End Function
End Class
End Namespace
|
reaction1989/roslyn
|
src/Features/VisualBasic/Portable/EncapsulateField/VisualBasicEncapsulateFieldService.vb
|
Visual Basic
|
apache-2.0
| 8,504
|
' 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.Editor.Implementation.Outlining
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Outlining
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class DelegateDeclarationOutlinerTests
Inherits AbstractVisualBasicSyntaxNodeOutlinerTests(Of DelegateStatementSyntax)
Friend Overrides Function CreateOutliner() As AbstractSyntaxOutliner
Return New DelegateDeclarationOutliner()
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function TestDelegateWithComments() As Task
Const code = "
{|span:'Hello
'World|}
Delegate Sub $$Foo()
"
Await VerifyRegionsAsync(code,
Region("span", "' Hello ...", autoCollapse:=True))
End Function
End Class
End Namespace
|
VPashkov/roslyn
|
src/EditorFeatures/VisualBasicTest/Outlining/DelegateDeclarationOutlinerTests.vb
|
Visual Basic
|
apache-2.0
| 1,095
|
'*******************************************************************************************'
' '
' 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 Bytescout.Spreadsheet
Imports Bytescout.Spreadsheet.Constants
Imports System.IO
Module Module1
Sub Main()
' Create new Spreadsheet
Dim document As New Spreadsheet()
document.LoadFromFile("Data.xls")
' Get worksheet by name
Dim worksheet As Worksheet = document.Workbook.Worksheets.ByName("Sample")
' Check dates
For i As Integer = 0 To 7
For j As Integer = 0 To 1
' Set current cell
Dim currentCell As Cell = worksheet.Cell(i, j)
' Get format type
Dim formatType As NumberFormatType = currentCell.ValueDataTypeByNumberFormatString
' Write line
Console.Write("Cell({0}:{1}) type is {2}. Value : ", i, j, formatType.ToString())
Select Case formatType
Case formatType.DateTime
' Read datetime
Dim datm As DateTime = currentCell.ValueAsDateTime
' Write date to console output
Console.Write(datm.ToString())
Case formatType.General
' Write value to console output
Console.Write(currentCell.Value)
End Select
Console.WriteLine()
Next
Next
' Close document
document.Close()
Console.ReadKey()
End Sub
End Module
|
bytescout/ByteScout-SDK-SourceCode
|
Spreadsheet SDK/VB.NET/Read Number Format In Cell/Module1.vb
|
Visual Basic
|
apache-2.0
| 2,459
|
' 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.Outlining
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Outlining
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining
Public Class OverallOutliningTests
Inherits AbstractSyntaxOutlinerTests
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Friend Overrides Async Function GetRegionsAsync(document As Document, position As Integer) As Task(Of OutliningSpan())
Dim outliningService = document.Project.LanguageServices.GetService(Of IOutliningService)()
Return (Await outliningService.GetOutliningSpansAsync(document, CancellationToken.None)) _
.WhereNotNull() _
.ToArray()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Outlining)>
Public Async Function DirectivesAtEndOfFile() As Task
Const code = "
$${|span1:Class C
End Class|}
{|span2:#Region ""Something""
#End Region|}
"
Await VerifyRegionsAsync(code,
Region("span1", "Class C ...", autoCollapse:=False),
Region("span2", "Something", autoCollapse:=False, isDefaultCollapsed:=True))
End Function
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/EditorFeatures/VisualBasicTest/Outlining/OverallOutliningTests.vb
|
Visual Basic
|
apache-2.0
| 1,546
|
' 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 Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.PDB
Public Class PDBObjectInitializerTests
Inherits BasicTestBase
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ObjectInitializerAsRefTypeEquals()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Public Class RefType
Public Field1 as Integer
Public Field2 as Integer
End Class
Class C1
Public Shared Sub Main()
Dim inst as RefType = new RefType() With {.Field1 = 23, .Field2 = 42}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="78" document="1"/>
<entry offset="0x17" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="inst" il_index="0" il_start="0x0" il_end="0x18" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ObjectInitializerAsNewRefType()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Public Class RefType
Public Field1 as Integer
Public Field2 as Integer
End Class
Class C1
Public Shared Sub Main()
Dim inst as new RefType() With {.Field1 = 23, .Field2 = 42}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="68" document="1"/>
<entry offset="0x17" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x18">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="inst" il_index="0" il_start="0x0" il_end="0x18" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ObjectInitializerNested()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Public Class RefType
Public Field1 as RefType
End Class
Class C1
Public Shared Sub Main()
Dim inst as new RefType() With {.Field1 = new RefType() With {.Field1 = nothing}}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="13" startColumn="5" endLine="13" endColumn="29" document="1"/>
<entry offset="0x1" startLine="14" startColumn="13" endLine="14" endColumn="90" document="1"/>
<entry offset="0x19" startLine="15" startColumn="5" endLine="15" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x1a">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="inst" il_index="0" il_start="0x0" il_end="0x1a" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
<ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)>
Public Sub ObjectInitializerAsNewRefTypeMultipleVariables()
Dim source =
<compilation>
<file>
Option Strict On
Option Infer Off
Option Explicit Off
Imports System
Imports System.Collections.Generic
Public Class RefType
Public Field1 as Integer
Public Field2 as Integer
End Class
Class C1
Public Shared Sub Main()
Dim inst1, inst2 as new RefType() With {.Field1 = 23, .Field2 = 42}
End Sub
End Class
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe)
compilation.VerifyPdb("C1.Main",
<symbols>
<files>
<file id="1" name="" language="VB"/>
</files>
<entryPoint declaringType="C1" methodName="Main"/>
<methods>
<method containingType="C1" name="Main">
<customDebugInfo>
<encLocalSlotMap>
<slot kind="0" offset="4"/>
<slot kind="0" offset="11"/>
</encLocalSlotMap>
</customDebugInfo>
<sequencePoints>
<entry offset="0x0" startLine="14" startColumn="5" endLine="14" endColumn="29" document="1"/>
<entry offset="0x1" startLine="15" startColumn="13" endLine="15" endColumn="18" document="1"/>
<entry offset="0x17" startLine="15" startColumn="20" endLine="15" endColumn="25" document="1"/>
<entry offset="0x2d" startLine="16" startColumn="5" endLine="16" endColumn="12" document="1"/>
</sequencePoints>
<scope startOffset="0x0" endOffset="0x2e">
<namespace name="System" importlevel="file"/>
<namespace name="System.Collections.Generic" importlevel="file"/>
<currentnamespace name=""/>
<local name="inst1" il_index="0" il_start="0x0" il_end="0x2e" attributes="0"/>
<local name="inst2" il_index="1" il_start="0x0" il_end="0x2e" attributes="0"/>
</scope>
</method>
</methods>
</symbols>)
End Sub
End Class
End Namespace
|
DustinCampbell/roslyn
|
src/Compilers/VisualBasic/Test/Emit/PDB/PDBObjectInitializerTests.vb
|
Visual Basic
|
apache-2.0
| 8,258
|
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
' This code is licensed under the MIT License (MIT).
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
Imports System
Imports Windows.ApplicationModel.DataTransfer
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Namespace Global.SDKTemplate
Public NotInheritable Partial Class OtherScenarios
Inherits Page
Dim rootPage As MainPage = MainPage.Current
Private Shared registerContentChanged As Boolean
Public Sub New()
Me.InitializeComponent()
Me.Init()
End Sub
Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
RegisterClipboardContentChanged.IsChecked = OtherScenarios.registerContentChanged
End Sub
#Region " Scenario Specific Code "
Sub Init()
AddHandler ShowFormatButton.Click, New RoutedEventHandler(AddressOf ShowFormatButton_Click)
AddHandler EmptyClipboardButton.Click, New RoutedEventHandler(AddressOf EmptyClipboardButton_Click)
AddHandler RegisterClipboardContentChanged.Click, New RoutedEventHandler(AddressOf RegisterClipboardContentChanged_Click)
AddHandler ClearOutputButton.Click, New RoutedEventHandler(AddressOf ClearOutputButton_Click)
End Sub
#End Region
#Region " Button Click "
Sub ShowFormatButton_Click(sender As Object, e As RoutedEventArgs)
Me.DisplayFormats()
End Sub
Sub EmptyClipboardButton_Click(sender As Object, e As RoutedEventArgs)
Try
Windows.ApplicationModel.DataTransfer.Clipboard.Clear()
OutputText.Text = "Clipboard has been emptied."
Catch ex As Exception
rootPage.NotifyUser("Error emptying Clipboard: " & ex.Message & ". Try again", NotifyType.ErrorMessage)
End Try
End Sub
Sub RegisterClipboardContentChanged_Click(sender As Object, e As RoutedEventArgs)
If OtherScenarios.registerContentChanged <> RegisterClipboardContentChanged.IsChecked.Value Then
Me.ClearOutput()
OtherScenarios.registerContentChanged = RegisterClipboardContentChanged.IsChecked.Value
rootPage.EnableClipboardContentChangedNotifications(OtherScenarios.registerContentChanged)
If OtherScenarios.registerContentChanged Then
OutputText.Text = "Successfully registered for clipboard update notification."
Else
OutputText.Text = "Successfully un-registered for clipboard update notification."
End If
End If
End Sub
Sub ClearOutputButton_Click(sender As Object, e As RoutedEventArgs)
Me.ClearOutput()
End Sub
#End Region
#Region " Private helper methods "
Private Sub ClearOutput()
rootPage.NotifyUser("", NotifyType.StatusMessage)
OutputText.Text = ""
End Sub
Private Sub DisplayFormats()
rootPage.NotifyUser("", NotifyType.StatusMessage)
OutputText.Text = rootPage.BuildClipboardFormatsOutputString()
End Sub
#End Region
End Class
End Namespace
|
spratmannc/Windows-universal-samples
|
Samples/Clipboard/vb/Others.xaml.vb
|
Visual Basic
|
mit
| 3,528
|
' 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.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
Public Class ImplementedByGraphQueryTests
<Fact, Trait(Traits.Feature, Traits.Features.Progression)>
Public Async Function TestImplementedBy1() As Task
Using testState = Await ProgressionTestState.CreateAsync(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
interface $$IBlah {
}
abstract class Base
{
public abstract int CompareTo(object obj);
}
class Foo : Base, IComparable, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
class Foo2 : Base, IBlah
{
public override int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementedByGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Foo)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo"/>
<Node Id="(@1 Type=Foo2)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="Foo2" Icon="Microsoft.VisualStudio.Class.Internal" Label="Foo2"/>
<Node Id="(@1 Type=IBlah)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsInternal="True" CommonLabel="IBlah" Icon="Microsoft.VisualStudio.Interface.Internal" Label="IBlah"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Foo)" Target="(@1 Type=IBlah)" Category="Implements"/>
<Link Source="(@1 Type=Foo2)" Target="(@1 Type=IBlah)" Category="Implements"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
|
bbarry/roslyn
|
src/VisualStudio/Core/Test/Progression/ImplementedByGraphQueryTests.vb
|
Visual Basic
|
apache-2.0
| 3,021
|
' 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.Collections
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Imports System.Text
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend MustInherit Class SyntaxList
Inherits VisualBasicSyntaxNode
Protected Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation())
MyBase.New(SyntaxKind.List, errors, annotations)
End Sub
Friend Sub New(reader As ObjectReader)
MyBase.New(reader)
End Sub
Protected Sub New()
MyBase.New(SyntaxKind.List)
End Sub
Friend Shared Function List(child As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Return child
End Function
Friend Shared Function List(child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode) As WithTwoChildren
Dim hash As Integer
Dim cached As GreenNode = SyntaxNodeCache.TryGetNode(SyntaxKind.List, child0, child1, hash)
If cached IsNot Nothing Then
Return DirectCast(cached, WithTwoChildren)
End If
Dim result = New WithTwoChildren(child0, child1)
If hash >= 0 Then
SyntaxNodeCache.AddNode(result, hash)
End If
Return result
End Function
Friend Shared Function List(child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode, child2 As VisualBasicSyntaxNode) As WithThreeChildren
Dim hash As Integer
Dim cached As GreenNode = SyntaxNodeCache.TryGetNode(SyntaxKind.List, child0, child1, child2, hash)
If cached IsNot Nothing Then
Return DirectCast(cached, WithThreeChildren)
End If
Dim result = New WithThreeChildren(child0, child1, child2)
If hash >= 0 Then
SyntaxNodeCache.AddNode(result, hash)
End If
Return result
End Function
Friend Shared Function List(nodes As ArrayElement(Of VisualBasicSyntaxNode)()) As SyntaxList
' "WithLotsOfChildren" list will allocate a separate array to hold
' precomputed node offsets. It may not be worth it for smallish lists.
If nodes.Length < 10 Then
Return New WithManyChildren(nodes)
Else
Return New WithLotsOfChildren(nodes)
End If
End Function
Friend Shared Function List(nodes As VisualBasicSyntaxNode()) As SyntaxList
Return List(nodes, nodes.Length)
End Function
Friend Shared Function List(nodes As VisualBasicSyntaxNode(), count As Integer) As SyntaxList
Dim array = New ArrayElement(Of VisualBasicSyntaxNode)(count - 1) {}
Debug.Assert(array.Length = count)
For i = 0 To count - 1
array(i).Value = nodes(i)
Debug.Assert(array(i).Value IsNot Nothing)
Next
Return List(array)
End Function
Friend MustOverride Sub CopyTo(array As ArrayElement(Of VisualBasicSyntaxNode)(), offset As Integer)
Friend Shared Function Concat(left As VisualBasicSyntaxNode, right As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
If (left Is Nothing) Then
Return right
End If
If (right Is Nothing) Then
Return left
End If
Dim tmp As ArrayElement(Of VisualBasicSyntaxNode)()
Dim leftList As SyntaxList = TryCast(left, SyntaxList)
Dim rightList As SyntaxList = TryCast(right, SyntaxList)
If leftList IsNot Nothing Then
If rightList IsNot Nothing Then
tmp = New ArrayElement(Of VisualBasicSyntaxNode)(left.SlotCount + right.SlotCount - 1) {}
leftList.CopyTo(tmp, 0)
rightList.CopyTo(tmp, left.SlotCount)
Return SyntaxList.List(tmp)
End If
tmp = New ArrayElement(Of VisualBasicSyntaxNode)((left.SlotCount + 1) - 1) {}
leftList.CopyTo(tmp, 0)
tmp(left.SlotCount).Value = right
Return SyntaxList.List(tmp)
End If
If rightList IsNot Nothing Then
tmp = New ArrayElement(Of VisualBasicSyntaxNode)((rightList.SlotCount + 1) - 1) {}
tmp(0).Value = left
rightList.CopyTo(tmp, 1)
Return SyntaxList.List(tmp)
End If
Return SyntaxList.List(left, right)
End Function
Friend NotInheritable Class WithTwoChildren
Inherits SyntaxList
Private ReadOnly _child0 As VisualBasicSyntaxNode
Private ReadOnly _child1 As VisualBasicSyntaxNode
Private Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation(), child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode)
MyBase.New(errors, annotations)
MyBase._slotCount = 2
MyBase.AdjustFlagsAndWidth(child0)
Me._child0 = child0
MyBase.AdjustFlagsAndWidth(child1)
Me._child1 = child1
End Sub
Friend Sub New(child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode)
MyBase.New()
MyBase._slotCount = 2
MyBase.AdjustFlagsAndWidth(child0)
Me._child0 = child0
MyBase.AdjustFlagsAndWidth(child1)
Me._child1 = child1
End Sub
Friend Sub New(reader As ObjectReader)
MyBase.New(reader)
MyBase._slotCount = 2
Me._child0 = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
MyBase.AdjustFlagsAndWidth(_child0)
Me._child1 = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
MyBase.AdjustFlagsAndWidth(_child1)
End Sub
Friend Overrides Function GetReader() As Func(Of ObjectReader, Object)
Return Function(r) New WithTwoChildren(r)
End Function
Friend Overrides Sub WriteTo(writer As ObjectWriter)
MyBase.WriteTo(writer)
writer.WriteValue(Me._child0)
writer.WriteValue(Me._child1)
End Sub
Friend Overrides Sub CopyTo(array As ArrayElement(Of VisualBasicSyntaxNode)(), offset As Integer)
array(offset).Value = Me._child0
array((offset + 1)).Value = Me._child1
End Sub
Friend Overrides Function GetSlot(index As Integer) As GreenNode
Select Case index
Case 0
Return Me._child0
Case 1
Return Me._child1
End Select
Return Nothing
End Function
Friend Overrides Function CreateRed(parent As SyntaxNode, startLocation As Integer) As SyntaxNode
Return New VisualBasic.Syntax.SyntaxList.WithTwoChildren(Me, parent, startLocation)
End Function
Friend Overrides Function SetDiagnostics(errors() As DiagnosticInfo) As GreenNode
Return New WithTwoChildren(errors, Me.GetAnnotations(), Me._child0, Me._child1)
End Function
Friend Overrides Function SetAnnotations(annotations() As SyntaxAnnotation) As GreenNode
Return New WithTwoChildren(Me.GetDiagnostics(), annotations, Me._child0, Me._child1)
End Function
End Class
Friend NotInheritable Class WithThreeChildren
Inherits SyntaxList
Private ReadOnly _child0 As VisualBasicSyntaxNode
Private ReadOnly _child1 As VisualBasicSyntaxNode
Private ReadOnly _child2 As VisualBasicSyntaxNode
Private Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation(), child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode, child2 As VisualBasicSyntaxNode)
MyBase.New(errors, annotations)
MyBase._slotCount = 3
MyBase.AdjustFlagsAndWidth(child0)
Me._child0 = child0
MyBase.AdjustFlagsAndWidth(child1)
Me._child1 = child1
MyBase.AdjustFlagsAndWidth(child2)
Me._child2 = child2
End Sub
Friend Sub New(child0 As VisualBasicSyntaxNode, child1 As VisualBasicSyntaxNode, child2 As VisualBasicSyntaxNode)
MyBase.New()
MyBase._slotCount = 3
MyBase.AdjustFlagsAndWidth(child0)
Me._child0 = child0
MyBase.AdjustFlagsAndWidth(child1)
Me._child1 = child1
MyBase.AdjustFlagsAndWidth(child2)
Me._child2 = child2
End Sub
Friend Sub New(reader As ObjectReader)
MyBase.New(reader)
MyBase._slotCount = 3
Me._child0 = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
MyBase.AdjustFlagsAndWidth(_child0)
Me._child1 = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
MyBase.AdjustFlagsAndWidth(_child1)
Me._child2 = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
MyBase.AdjustFlagsAndWidth(_child2)
End Sub
Friend Overrides Function GetReader() As Func(Of ObjectReader, Object)
Return Function(r) New WithThreeChildren(r)
End Function
Friend Overrides Sub WriteTo(writer As ObjectWriter)
MyBase.WriteTo(writer)
writer.WriteValue(Me._child0)
writer.WriteValue(Me._child1)
writer.WriteValue(Me._child2)
End Sub
Friend Overrides Sub CopyTo(array As ArrayElement(Of VisualBasicSyntaxNode)(), offset As Integer)
array(offset).Value = Me._child0
array(offset + 1).Value = Me._child1
array(offset + 2).Value = Me._child2
End Sub
Friend Overrides Function GetSlot(index As Integer) As GreenNode
Select Case index
Case 0
Return Me._child0
Case 1
Return Me._child1
Case 2
Return Me._child2
End Select
Return Nothing
End Function
Friend Overrides Function CreateRed(parent As SyntaxNode, startLocation As Integer) As SyntaxNode
Return New VisualBasic.Syntax.SyntaxList.WithThreeChildren(Me, parent, startLocation)
End Function
Friend Overrides Function SetDiagnostics(errors() As DiagnosticInfo) As GreenNode
Return New WithThreeChildren(errors, Me.GetAnnotations(), Me._child0, Me._child1, Me._child2)
End Function
Friend Overrides Function SetAnnotations(annotations() As SyntaxAnnotation) As GreenNode
Return New WithThreeChildren(Me.GetDiagnostics(), annotations, Me._child0, Me._child1, Me._child2)
End Function
End Class
Friend MustInherit Class WithManyChildrenBase
Inherits SyntaxList
Protected ReadOnly _children As ArrayElement(Of VisualBasicSyntaxNode)()
Protected Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation(), children As ArrayElement(Of VisualBasicSyntaxNode)())
MyBase.New(errors, annotations)
Me._children = children
InitChildren()
End Sub
Friend Sub New(children As ArrayElement(Of VisualBasicSyntaxNode)())
MyBase.New()
Me._children = children
InitChildren()
End Sub
Private Sub InitChildren()
Dim n = _children.Length
If (n < Byte.MaxValue) Then
Me._slotCount = CByte(n)
Else
Me._slotCount = Byte.MaxValue
End If
For i = 0 To _children.Length - 1
Dim child = _children(i)
MyBase.AdjustFlagsAndWidth(child)
Next i
End Sub
Protected Overrides Function GetSlotCount() As Integer
Return Me._children.Length
End Function
Protected Sub New(reader As ObjectReader)
MyBase.New(reader)
Dim length = reader.ReadInt32()
Me._children = New ArrayElement(Of VisualBasicSyntaxNode)(length - 1) {}
For i = 0 To length - 1
Me._children(i).Value = DirectCast(reader.ReadValue(), VisualBasicSyntaxNode)
Next
InitChildren()
End Sub
Friend Overrides Sub WriteTo(writer As ObjectWriter)
MyBase.WriteTo(writer)
' PERF Write the array out manually.Profiling shows that this Is cheaper than converting to
' an array in order to use writer.WriteValue.
writer.WriteInt32(Me._children.Length)
For i = 0 To Me._children.Length - 1
writer.WriteValue(Me._children(i).Value)
Next
End Sub
Friend Overrides Sub CopyTo(nodes As ArrayElement(Of VisualBasicSyntaxNode)(), offset As Integer)
Array.Copy(Me._children, 0, nodes, offset, Me._children.Length)
End Sub
Friend Overrides Function GetSlot(index As Integer) As GreenNode
Return Me._children(index)
End Function
'TODO: weakening heuristic may need some tuning.
Private Shared Function ShouldMakeWeakList(parent As SyntaxNode) As Boolean
Return parent IsNot Nothing AndAlso TypeOf parent Is VisualBasic.Syntax.MethodBlockBaseSyntax
End Function
Friend Overrides Function CreateRed(parent As SyntaxNode, startLocation As Integer) As SyntaxNode
Dim isSeparated = SlotCount > 1 AndAlso HasNodeTokenPattern()
If ShouldMakeWeakList(parent) Then
If isSeparated Then
Return New VisualBasic.Syntax.SyntaxList.WeakSeparatedWithManyChildren(Me, parent, startLocation)
End If
Return New VisualBasic.Syntax.SyntaxList.WeakWithManyChildren(Me, parent, startLocation)
Else
If isSeparated Then
Return New VisualBasic.Syntax.SyntaxList.SeparatedWithManyChildren(Me, parent, startLocation)
End If
Return New VisualBasic.Syntax.SyntaxList.WithManyChildren(Me, parent, startLocation)
End If
End Function
Private Function HasNodeTokenPattern() As Boolean
For i = 0 To Me.SlotCount - 1
' even slots must not be tokens and odd slots must be
If Me.GetSlot(i).IsToken = ((i And 1) = 0) Then
Return False
End If
Next
Return True
End Function
Friend MustOverride Overrides Function SetDiagnostics(newErrors() As DiagnosticInfo) As GreenNode
Friend MustOverride Overrides Function SetAnnotations(annotations() As SyntaxAnnotation) As GreenNode
End Class
Friend NotInheritable Class WithManyChildren
Inherits WithManyChildrenBase
Friend Sub New(children As ArrayElement(Of VisualBasicSyntaxNode)())
MyBase.New(children)
End Sub
Private Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation(), children As ArrayElement(Of VisualBasicSyntaxNode)())
MyBase.New(errors, annotations, children)
End Sub
Friend Sub New(reader As ObjectReader)
MyBase.New(reader)
End Sub
Friend Overrides Function GetReader() As Func(Of ObjectReader, Object)
Return Function(r) New WithManyChildren(r)
End Function
Friend Overrides Function SetDiagnostics(errors() As DiagnosticInfo) As GreenNode
Return New WithManyChildren(errors, Me.GetAnnotations(), Me._children)
End Function
Friend Overrides Function SetAnnotations(annotations() As SyntaxAnnotation) As GreenNode
Return New WithManyChildren(Me.GetDiagnostics(), annotations, Me._children)
End Function
End Class
Friend NotInheritable Class WithLotsOfChildren
Inherits WithManyChildrenBase
Private ReadOnly _childOffsets As Integer()
Friend Sub New(children As ArrayElement(Of VisualBasicSyntaxNode)())
MyBase.New(children)
_childOffsets = CalculateOffsets(children)
End Sub
Private Sub New(errors As DiagnosticInfo(), annotations As SyntaxAnnotation(), children As ArrayElement(Of VisualBasicSyntaxNode)(), childOffsets As Integer())
MyBase.New(errors, annotations, children)
_childOffsets = childOffsets
End Sub
Friend Sub New(reader As ObjectReader)
MyBase.New(reader)
_childOffsets = CalculateOffsets(_children)
End Sub
Friend Overrides Function GetReader() As Func(Of ObjectReader, Object)
Return Function(r) New WithLotsOfChildren(r)
End Function
Public Overrides Function GetSlotOffset(index As Integer) As Integer
Return _childOffsets(index)
End Function
''' <summary>
''' Find the slot that contains the given offset.
''' </summary>
''' <param name="offset">The target offset. Must be between 0 and <see cref="GreenNode.FullWidth"/>.</param>
''' <returns>The slot index of the slot containing the given offset.</returns>
''' <remarks>
''' This implementation uses a binary search to find the first slot that contains
''' the given offset.
''' </remarks>
Public Overrides Function FindSlotIndexContainingOffset(offset As Integer) As Integer
Debug.Assert(offset >= 0 AndAlso offset < FullWidth)
Return _childOffsets.BinarySearchUpperBound(offset) - 1
End Function
Friend Overrides Function SetDiagnostics(errors() As DiagnosticInfo) As GreenNode
Return New WithLotsOfChildren(errors, Me.GetAnnotations(), Me._children, Me._childOffsets)
End Function
Friend Overrides Function SetAnnotations(annotations() As SyntaxAnnotation) As GreenNode
Return New WithLotsOfChildren(Me.GetDiagnostics(), annotations, Me._children, Me._childOffsets)
End Function
Private Shared Function CalculateOffsets(children As ArrayElement(Of VisualBasicSyntaxNode)()) As Integer()
Dim n = children.Length
Dim childOffsets = New Integer(n - 1) {}
Dim offset = 0
For i = 0 To n - 1
childOffsets(i) = offset
offset += children(i).Value.FullWidth
Next
Return childOffsets
End Function
End Class
End Class
Friend Class SyntaxListBuilder
Private _count As Integer
Private _nodes As ArrayElement(Of VisualBasicSyntaxNode)()
Public Shared Function Create() As SyntaxListBuilder
Return New SyntaxListBuilder(8)
End Function
Public Sub New(size As Integer)
Me._nodes = New ArrayElement(Of VisualBasicSyntaxNode)(size - 1) {}
End Sub
Public Function Add(item As VisualBasicSyntaxNode) As SyntaxListBuilder
EnsureAdditionalCapacity(1)
Return Me.AddUnsafe(item)
End Function
Private Function AddUnsafe(item As GreenNode) As SyntaxListBuilder
Debug.Assert(item IsNot Nothing)
Me._nodes(Me._count).Value = DirectCast(item, VisualBasicSyntaxNode)
Me._count += 1
Return Me
End Function
Public Function AddRange(Of TNode As VisualBasicSyntaxNode)(list As SyntaxList(Of TNode)) As SyntaxListBuilder
Return Me.AddRange(Of TNode)(list, 0, list.Count)
End Function
Public Function AddRange(Of TNode As VisualBasicSyntaxNode)(list As SyntaxList(Of TNode), offset As Integer, length As Integer) As SyntaxListBuilder
EnsureAdditionalCapacity(length - offset)
Dim oldCount = Me._count
For i = offset To offset + length - 1
AddUnsafe(list.ItemUntyped(i))
Next i
Me.Validate(oldCount, Me._count)
Return Me
End Function
Public Function Any(kind As SyntaxKind) As Boolean
Dim i As Integer
For i = 0 To Me._count - 1
If (Me._nodes(i).Value.Kind = kind) Then
Return True
End If
Next i
Return False
End Function
Friend Sub RemoveLast()
Me._count -= 1
Me._nodes(Me._count) = Nothing
End Sub
Public Sub Clear()
Me._count = 0
End Sub
Private Sub EnsureAdditionalCapacity(additionalCount As Integer)
Dim currentSize As Integer = Me._nodes.Length
Dim requiredSize As Integer = Me._count + additionalCount
If requiredSize <= currentSize Then
Return
End If
Dim newSize As Integer =
If(requiredSize < 8, 8,
If(requiredSize >= Integer.MaxValue / 2, Integer.MaxValue,
Math.Max(requiredSize, currentSize * 2))) ' Guaranteed to at least double
Debug.Assert(newSize >= requiredSize)
Array.Resize(Me._nodes, newSize)
End Sub
Friend Function ToArray() As ArrayElement(Of VisualBasicSyntaxNode)()
Dim dst As ArrayElement(Of VisualBasicSyntaxNode)() = New ArrayElement(Of VisualBasicSyntaxNode)(Me._count - 1) {}
'TODO: workaround for range check hoisting bug
' <<< FOR LOOP
Dim i As Integer = 0
GoTo enter
Do
dst(i) = Me._nodes(i)
i += 1
enter:
Loop While i < dst.Length
' >>> FOR LOOP
Return dst
End Function
Friend Function ToListNode() As VisualBasicSyntaxNode
Select Case Me._count
Case 0
Return Nothing
Case 1
Return Me._nodes(0)
Case 2
Return SyntaxList.List(Me._nodes(0), Me._nodes(1))
Case 3
Return SyntaxList.List(Me._nodes(0), Me._nodes(1), Me._nodes(2))
End Select
Return SyntaxList.List(Me.ToArray)
End Function
<Conditional("DEBUG")>
Private Sub Validate(start As Integer, [end] As Integer)
Dim i As Integer
For i = start To [end] - 1
Debug.Assert(Me._nodes(i).Value IsNot Nothing)
Next i
End Sub
Public ReadOnly Property Count As Integer
Get
Return Me._count
End Get
End Property
Default Public Property Item(index As Integer) As VisualBasicSyntaxNode
Get
Return Me._nodes(index)
End Get
Set(value As VisualBasicSyntaxNode)
Me._nodes(index).Value = value
End Set
End Property
Public Function ToList() As SyntaxList(Of VisualBasicSyntaxNode)
Return New SyntaxList(Of VisualBasicSyntaxNode)(ToListNode)
End Function
Public Function ToList(Of TDerived As VisualBasicSyntaxNode)() As SyntaxList(Of TDerived)
Return New SyntaxList(Of TDerived)(ToListNode)
End Function
End Class
Friend Structure SyntaxListBuilder(Of TNode As VisualBasicSyntaxNode)
Private ReadOnly _builder As SyntaxListBuilder
Public Shared Function Create() As SyntaxListBuilder(Of TNode)
Return New SyntaxListBuilder(Of TNode)(8)
End Function
Public Sub New(size As Integer)
Me.New(New SyntaxListBuilder(size))
End Sub
Friend Sub New(builder As SyntaxListBuilder)
Me._builder = builder
End Sub
Public ReadOnly Property IsNull As Boolean
Get
Return (Me._builder Is Nothing)
End Get
End Property
Public ReadOnly Property Count As Integer
Get
Return Me._builder.Count
End Get
End Property
Default Public Property Item(index As Integer) As TNode
Get
Return DirectCast(Me._builder.Item(index), TNode)
End Get
Set(value As TNode)
Me._builder.Item(index) = value
End Set
End Property
Friend Sub RemoveLast()
Me._builder.RemoveLast()
End Sub
Public Sub Clear()
Me._builder.Clear()
End Sub
Public Sub Add(node As TNode)
Me._builder.Add(node)
End Sub
Public Sub AddRange(nodes As SyntaxList(Of TNode))
Me._builder.AddRange(Of TNode)(nodes)
End Sub
Public Sub AddRange(nodes As SyntaxList(Of TNode), offset As Integer, length As Integer)
Me._builder.AddRange(Of TNode)(nodes, offset, length)
End Sub
Public Function Any(kind As SyntaxKind) As Boolean
Return Me._builder.Any(kind)
End Function
Public Function ToList() As SyntaxList(Of TNode)
Debug.Assert(Me._builder IsNot Nothing)
Return Me._builder.ToList(Of TNode)()
End Function
Public Function ToList(Of TDerivedNode As TNode)() As SyntaxList(Of TDerivedNode)
Debug.Assert(Me._builder IsNot Nothing)
Return Me._builder.ToList(Of TDerivedNode)()
End Function
Public Shared Widening Operator CType(builder As SyntaxListBuilder(Of TNode)) As SyntaxListBuilder
Return builder._builder
End Operator
Public Shared Widening Operator CType(builder As SyntaxListBuilder(Of TNode)) As SyntaxList(Of TNode)
Return builder.ToList
End Operator
End Structure
Friend Structure SeparatedSyntaxListBuilder(Of TNode As VisualBasicSyntaxNode)
Private ReadOnly _builder As SyntaxListBuilder
Public Sub New(size As Integer)
Me.New(New SyntaxListBuilder(size))
End Sub
Friend Sub New(builder As SyntaxListBuilder)
Me._builder = builder
End Sub
Public ReadOnly Property IsNull As Boolean
Get
Return (Me._builder Is Nothing)
End Get
End Property
Public ReadOnly Property Count As Integer
Get
Return Me._builder.Count
End Get
End Property
Default Public Property Item(index As Integer) As VisualBasicSyntaxNode
Get
Return Me._builder.Item(index)
End Get
Set(value As VisualBasicSyntaxNode)
Me._builder.Item(index) = value
End Set
End Property
Public Sub Clear()
Me._builder.Clear()
End Sub
Public Sub Add(node As TNode)
Me._builder.Add(node)
End Sub
Friend Sub AddSeparator(separatorToken As SyntaxToken)
Me._builder.Add(separatorToken)
End Sub
Friend Sub AddRange(nodes As SeparatedSyntaxList(Of TNode), count As Integer)
Dim list = nodes.GetWithSeparators
Me._builder.AddRange(list, Me.Count, Math.Min(count * 2, list.Count))
End Sub
Friend Sub RemoveLast()
Me._builder.RemoveLast()
End Sub
Public Function Any(kind As SyntaxKind) As Boolean
Return Me._builder.Any(kind)
End Function
Public Function ToList() As SeparatedSyntaxList(Of TNode)
Return New SeparatedSyntaxList(Of TNode)(New SyntaxList(Of VisualBasicSyntaxNode)(Me._builder.ToListNode))
End Function
Public Function ToList(Of TDerivedNode As TNode)() As SeparatedSyntaxList(Of TDerivedNode)
Return New SeparatedSyntaxList(Of TDerivedNode)(New SyntaxList(Of VisualBasicSyntaxNode)(Me._builder.ToListNode))
End Function
Public Shared Widening Operator CType(builder As SeparatedSyntaxListBuilder(Of TNode)) As SyntaxListBuilder
Return builder._builder
End Operator
End Structure
Friend Structure SyntaxList(Of TNode As VisualBasicSyntaxNode)
Implements IEquatable(Of SyntaxList(Of TNode))
Private ReadOnly _node As GreenNode
Friend Sub New(node As GreenNode)
Me._node = node
End Sub
Friend ReadOnly Property Node As VisualBasicSyntaxNode
Get
Return DirectCast(Me._node, VisualBasicSyntaxNode)
End Get
End Property
Public ReadOnly Property Count As Integer
Get
Return If((Me._node Is Nothing), 0, If(Me._node.IsList, Me._node.SlotCount, 1))
End Get
End Property
Public ReadOnly Property Last As TNode
Get
Dim node = Me._node
If node.IsList Then
Return DirectCast(node.GetSlot(node.SlotCount - 1), TNode)
End If
Return DirectCast(node, TNode)
End Get
End Property
Default Public ReadOnly Property Item(index As Integer) As TNode
Get
Dim node = Me._node
If node.IsList Then
Return DirectCast(node.GetSlot(index), TNode)
End If
Debug.Assert(index = 0)
Return DirectCast(node, TNode)
End Get
End Property
Friend ReadOnly Property ItemUntyped(index As Integer) As GreenNode
Get
Dim node = Me._node
If node.IsList Then
Return node.GetSlot(index)
End If
Debug.Assert(index = 0)
Return node
End Get
End Property
Public Function Any() As Boolean
Return Me._node IsNot Nothing
End Function
Public Function Any(kind As SyntaxKind) As Boolean
For i = 0 To Me.Count - 1
Dim element = Me.ItemUntyped(i)
If (element.RawKind = kind) Then
Return True
End If
Next
Return False
End Function
Friend ReadOnly Property Nodes As TNode()
Get
Dim arr = New TNode(Me.Count - 1) {}
For i = 0 To Me.Count - 1
arr(i) = Me.Item(i)
Next
Return arr
End Get
End Property
Public Shared Operator =(left As SyntaxList(Of TNode), right As SyntaxList(Of TNode)) As Boolean
Return (left._node Is right._node)
End Operator
Public Shared Operator <>(left As SyntaxList(Of TNode), right As SyntaxList(Of TNode)) As Boolean
Return (Not left._node Is right._node)
End Operator
Public Overrides Function Equals(obj As Object) As Boolean
Return (TypeOf obj Is SyntaxList(Of TNode) AndAlso Me.Equals(DirectCast(obj, SyntaxList(Of TNode))))
End Function
Public Overloads Function Equals(other As SyntaxList(Of TNode)) As Boolean Implements IEquatable(Of SyntaxList(Of TNode)).Equals
Return Me._node Is other._node
End Function
Public Overrides Function GetHashCode() As Integer
Return If((Not Me._node Is Nothing), Me._node.GetHashCode, 0)
End Function
Friend Function AsSeparatedList(Of TOther As VisualBasicSyntaxNode)() As SeparatedSyntaxList(Of TOther)
Return New SeparatedSyntaxList(Of TOther)(New SyntaxList(Of TOther)(Me._node))
End Function
Public Shared Widening Operator CType(node As TNode) As SyntaxList(Of TNode)
Return New SyntaxList(Of TNode)(node)
End Operator
Public Shared Widening Operator CType(nodes As SyntaxList(Of TNode)) As SyntaxList(Of VisualBasicSyntaxNode)
Return New SyntaxList(Of VisualBasicSyntaxNode)(nodes._node)
End Operator
End Structure
End Namespace
|
REALTOBIZ/roslyn
|
src/Compilers/VisualBasic/Portable/Syntax/InternalSyntax/SyntaxList.vb
|
Visual Basic
|
apache-2.0
| 33,745
|
Imports System.Windows.Forms.DataVisualization
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.Drawing
Imports System.Windows.Forms
Public Class frmPlaceVote
Public _id As String
Private cbAnswers(20) As CheckBox
Public Function ProperCase(sCase As String) As String
If Len(sCase) > 1 Then sCase = UCase(Mid(sCase, 1, 1)) + Mid(sCase, 2, Len(sCase))
Return sCase
End Function
Public Function PlaceVote(sTitle As String) As String
Dim sData As String = GetPollData(sTitle)
sData = Replace(sData, "_", " ")
Dim sExpiration As String = ExtractXML(sData, "<EXPIRATION>")
Dim sShareType As String = ExtractXML(sData, "<SHARETYPE>")
Dim sQuestion As String = ExtractXML(sData, "<QUESTION>")
Dim sAnswers As String = ExtractXML(sData, "<ANSWERS>")
Dim sURL As String = ExtractXML(sData, "<URL>")
'Array of answers
Dim sArrayOfAnswers As String = ExtractXML(sData, "<ARRAYANSWERS>")
Dim vAnswers() As String = Split(sArrayOfAnswers, "<RESERVED>")
Dim sTotalParticipants As String = ExtractXML(sData, "<TOTALPARTICIPANTS>")
Dim sTotalShares As String = ExtractXML(sData, "<TOTALSHARES>")
Dim sBestAnswer As String = ExtractXML(sData, "<BESTANSWER>")
'Display each answer
Dim yOffset As Long = lblQuestion.Top + 25
Dim iRow As Long
For x As Integer = 0 To vAnswers.Length - 1
Dim sAnswer As String = ExtractXML(vAnswers(x), "<ANSWERNAME>")
If Len(sAnswer) > 0 Then
iRow = iRow + 1
Dim cbAnswer As New CheckBox
cbAnswer.BackColor = Color.Black
cbAnswer.ForeColor = Color.LightGreen
cbAnswer.Font = New Font("Arial", 14)
cbAnswer.Text = Trim(iRow) + ". " + sAnswer
cbAnswer.Width = Me.Width * 0.75
cbAnswer.Top = iRow * 34 + yOffset
cbAnswer.Left = lblQuestion.Left + 50
cbAnswer.Name = "cb" + Trim(iRow)
cbAnswer.Tag = sAnswer
AddHandler cbAnswer.Click, AddressOf ClickCheckbox
cbAnswers(iRow) = cbAnswer
Me.Controls.Add(cbAnswer)
End If
Next
lblQuestion.Text = "Q: " + sQuestion
lblTitle.Text = ProperCase(sTitle)
lnkURL.Text = sURL
Return ""
End Function
Private Sub ClickCheckbox(ByVal sender As Object, ByVal e As System.EventArgs)
Dim cb As CheckBox = sender
'Allow Multiple Choice
For x As Integer = 1 To 20
If Not cbAnswers(x) Is Nothing Then
If cbAnswers(x).Name <> cb.Name Then
'cbAnswers(x).Checked = False
End If
End If
Next
End Sub
Private Function GetVoteValue() As String
Dim sAnswer As String = ""
For x As Integer = 1 To 20
If Not cbAnswers(x) Is Nothing Then
If cbAnswers(x).Checked Then sAnswer += cbAnswers(x).Tag + ";"
End If
Next
If Len(sAnswer) > 2 Then sAnswer = Mid(sAnswer, 1, Len(sAnswer) - 1)
Return sAnswer
End Function
Function GetPollData(sTitle As String) As String
If Not msGenericDictionary.ContainsKey("POLLS") Then
MsgBox("No voting data exists.")
Exit Function
End If
Dim sVoting As String = msGenericDictionary("POLLS")
If Len(sVoting) = 0 Then Exit Function
Dim vPolls() As String = Split(sVoting, "<POLL>")
For y As Integer = 0 To vPolls.Length - 1
Dim sTitle1 As String = ExtractXML(vPolls(y), "<TITLE>", "</TITLE>")
Dim sURL As String = ExtractXML(vPolls(y), "<URL>", "</URL>")
sTitle1 = Replace(sTitle1, "_", " ")
sURL = Replace(sURL, "_", " ")
If LCase(sTitle1) = LCase(sTitle) Then
Return vPolls(y)
End If
Next y
Return ""
End Function
Private Sub frmChartVotes_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.Escape Then
Me.Hide()
End If
End Sub
Private Sub btnVote_Click(sender As System.Object, e As System.EventArgs) Handles btnVote.Click
Dim sVote As String = GetVoteValue()
If sVote = "" Then
MsgBox("You must select an answer first.", MsgBoxStyle.Critical, "Gridcoin Voting System")
Exit Sub
End If
Dim sTitle As String = lblTitle.Text
sVote = Replace(sVote, " ", "_")
sTitle = Replace(sTitle, " ", "_")
Dim sResult As String = ExecuteRPCCommand("vote", sTitle, sVote, "", "", "", "")
MsgBox(sResult, MsgBoxStyle.Information, "Gridcoin Voting System")
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim sTitle As String = lblTitle.Text
Dim sVote As String = "TEST"
sTitle = Replace(sTitle, " ", "_")
Dim sResult As String = ExecuteRPCCommand("vote", sTitle, sVote, "", "", "", "")
MsgBox(sResult, MsgBoxStyle.Information, "Gridcoin Voting System")
End Sub
Private Sub lnkURL_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lnkURL.LinkClicked
Process.Start(lnkURL.Text)
End Sub
End Class
|
icede/Gridcoin-Research
|
contrib/Installer/boinc/boinc/frmPlaceVote.vb
|
Visual Basic
|
mit
| 5,517
|
Imports System.Data
Partial Class fComprobantes_Diario
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(" SELECT Comprobantes.Documento, ")
loComandoSeleccionar.AppendLine(" YEAR(Comprobantes.Fec_Ini) AS Anno, ")
loComandoSeleccionar.AppendLine(" MONTH(Comprobantes.Fec_Ini) AS Mes, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Fec_Ini, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Fec_Fin, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Resumen, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Tipo, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Origen, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Integracion, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Status, ")
loComandoSeleccionar.AppendLine(" Comprobantes.Notas, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Renglon, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Cue, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Cen, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Gas, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Act, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Tip, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Cla, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Mon, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Tasa, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Mon_Deb, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Mon_Hab, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Comentario, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Tip_Ori, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Doc_Ori, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes.Cod_Reg ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes01 ")
loComandoSeleccionar.AppendLine(" FROM Comprobantes, ")
loComandoSeleccionar.AppendLine(" Renglones_Comprobantes ")
loComandoSeleccionar.AppendLine(" WHERE Comprobantes.Documento = Renglones_Comprobantes.Documento ")
loComandoSeleccionar.AppendLine(" AND Comprobantes.Adicional = Renglones_Comprobantes.Adicional ")
loComandoSeleccionar.AppendLine(" AND " & cusAplicacion.goFormatos.pcCondicionPrincipal)
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes01.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes01.Cod_Cue = '' THEN '' ELSE SUBSTRING(Cuentas_Contables.Nom_Cue,1,35) END) AS Nom_Cue ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes02 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes01 LEFT JOIN Cuentas_Contables ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes01.Cod_Cue = Cuentas_Contables.Cod_Cue ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes02.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes02.Cod_Cen = '' THEN '' ELSE Centros_Costos.Nom_Cen END) AS Nom_Cen ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes03 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes02 LEFT JOIN Centros_Costos ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes02.Cod_Cen = Centros_Costos.Cod_Cen ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes03.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes03.Cod_Gas = '' THEN '' ELSE Cuentas_Gastos.Nom_Gas END) AS Nom_Gas ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes04 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes03 LEFT JOIN Cuentas_Gastos ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes03.Cod_Gas = Cuentas_Gastos.Cod_Gas ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes04.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes04.Cod_Act = '' THEN '' ELSE Activos_Fijos.Nom_Act END) AS Nom_Act ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes05 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes04 LEFT JOIN Activos_Fijos ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes04.Cod_Act = Activos_Fijos.Cod_Act ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes05.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes05.Cod_Tip = '' THEN '' ELSE Tipos_Documentos.Nom_Tip END) AS Nom_Tip ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes06 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes05 LEFT JOIN Tipos_Documentos ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes05.Cod_Tip = Tipos_Documentos.Cod_Tip ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes06.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes06.Cod_Cla = '' THEN '' ELSE Clasificadores.Nom_Cla END) AS Nom_Cla ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes07 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes06 LEFT JOIN Clasificadores ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes06.Cod_Cla = Clasificadores.Cod_Cla ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes07.*, ")
loComandoSeleccionar.AppendLine(" (CASE WHEN #tmpComprobantes07.Cod_Mon = '' THEN '' ELSE Monedas.Nom_Mon END) AS Nom_Mon ")
loComandoSeleccionar.AppendLine(" INTO #tmpComprobantes08 ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes07 LEFT JOIN Monedas ")
loComandoSeleccionar.AppendLine(" ON #tmpComprobantes07.Cod_Mon = Monedas.Cod_Mon ")
loComandoSeleccionar.AppendLine(" SELECT #tmpComprobantes08.* ")
loComandoSeleccionar.AppendLine(" FROM #tmpComprobantes08 ")
loComandoSeleccionar.AppendLine(" ORDER BY Documento, Renglon ")
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")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fComprobantes_Diario", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfComprobantes_Diario.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo '
'-------------------------------------------------------------------------------------------'
' JJD: 24/02/09: Codigo inicial '
'-------------------------------------------------------------------------------------------'
' MAT: 03/03/11: Mejora en la vista de diseño '
'-------------------------------------------------------------------------------------------'
' MAT: 04/03/11: Se aplicaron los metodos carga de imagen y validacion de registro cero. '
'-------------------------------------------------------------------------------------------'
' RJG: 19/01/12: Se agregó el campo Adicional a la unión entre el encabezado y los renglones'
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
Reportes - Contabilidad/fComprobantes_Diario.aspx.vb
|
Visual Basic
|
mit
| 10,265
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("TestPlugin")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("TestPlugin")>
<Assembly: AssemblyCopyright("Copyright © 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("54102f41-f84c-42eb-98d5-eb34f18d0422")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
deandob/HAConsole
|
TestPlugin/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,138
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("BindingTester")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("County")>
<Assembly: AssemblyProduct("BindingTester")>
<Assembly: AssemblyCopyright("Copyright © County 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("ff7f9757-3db6-4fd4-9100-bfd726bdcb2f")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
Micmaz/DTIControls
|
Binding/BindingTester/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,155
|
Imports NUnit.Framework
Imports ChrisLaco.Siphon
<TestFixture(Description:="DataItem Tests")> _
Public Class DataItemsTests
<Test(Description:="Generic String Data Item")> _
Public Sub StringDataItem()
Dim item As IDataItem(Of String) = New DataItem(Of String)("Name", "Data")
Assert.AreEqual("Name", item.Name)
Assert.AreEqual("Data", item.GetString)
Assert.AreEqual("Data", item.Data)
Assert.AreEqual(DataItemStatus.New, item.Status)
item.Status = DataItemStatus.CompletedProcessing
Assert.AreEqual(DataItemStatus.CompletedProcessing, item.Status)
End Sub
End Class
|
claco/siphon
|
SiphonTests/Monitors/DataItemTests.vb
|
Visual Basic
|
mit
| 644
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Edit_form
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(Edit_form))
Me.tb_section = New System.Windows.Forms.TextBox()
Me.tb_author = New System.Windows.Forms.TextBox()
Me.tb_title = New System.Windows.Forms.TextBox()
Me.lbl_section = New System.Windows.Forms.Label()
Me.lbl_title = New System.Windows.Forms.Label()
Me.lbl_author = New System.Windows.Forms.Label()
Me.lbl_units = New System.Windows.Forms.Label()
Me.btn_update = New System.Windows.Forms.Button()
Me.btn_cancel = New System.Windows.Forms.Button()
Me.tb_collection = New System.Windows.Forms.TextBox()
Me.Label1 = New System.Windows.Forms.Label()
Me.tb_units = New System.Windows.Forms.NumericUpDown()
CType(Me.tb_units, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'tb_section
'
Me.tb_section.Location = New System.Drawing.Point(108, 122)
Me.tb_section.Name = "tb_section"
Me.tb_section.Size = New System.Drawing.Size(516, 20)
Me.tb_section.TabIndex = 11
'
'tb_author
'
Me.tb_author.Location = New System.Drawing.Point(108, 82)
Me.tb_author.Name = "tb_author"
Me.tb_author.Size = New System.Drawing.Size(516, 20)
Me.tb_author.TabIndex = 10
'
'tb_title
'
Me.tb_title.Location = New System.Drawing.Point(108, 39)
Me.tb_title.Name = "tb_title"
Me.tb_title.Size = New System.Drawing.Size(516, 20)
Me.tb_title.TabIndex = 9
'
'lbl_section
'
Me.lbl_section.AutoSize = True
Me.lbl_section.ImeMode = System.Windows.Forms.ImeMode.NoControl
Me.lbl_section.Location = New System.Drawing.Point(56, 125)
Me.lbl_section.Name = "lbl_section"
Me.lbl_section.Size = New System.Drawing.Size(43, 13)
Me.lbl_section.TabIndex = 8
Me.lbl_section.Text = "Section"
'
'lbl_title
'
Me.lbl_title.AutoSize = True
Me.lbl_title.ImeMode = System.Windows.Forms.ImeMode.NoControl
Me.lbl_title.Location = New System.Drawing.Point(72, 42)
Me.lbl_title.Name = "lbl_title"
Me.lbl_title.Size = New System.Drawing.Size(27, 13)
Me.lbl_title.TabIndex = 7
Me.lbl_title.Text = "Title"
'
'lbl_author
'
Me.lbl_author.AutoSize = True
Me.lbl_author.ImeMode = System.Windows.Forms.ImeMode.NoControl
Me.lbl_author.Location = New System.Drawing.Point(61, 85)
Me.lbl_author.Name = "lbl_author"
Me.lbl_author.Size = New System.Drawing.Size(38, 13)
Me.lbl_author.TabIndex = 6
Me.lbl_author.Text = "Author"
'
'lbl_units
'
Me.lbl_units.AutoSize = True
Me.lbl_units.ImeMode = System.Windows.Forms.ImeMode.NoControl
Me.lbl_units.Location = New System.Drawing.Point(68, 199)
Me.lbl_units.Name = "lbl_units"
Me.lbl_units.Size = New System.Drawing.Size(31, 13)
Me.lbl_units.TabIndex = 12
Me.lbl_units.Text = "Units"
'
'btn_update
'
Me.btn_update.Location = New System.Drawing.Point(137, 244)
Me.btn_update.Name = "btn_update"
Me.btn_update.Size = New System.Drawing.Size(156, 38)
Me.btn_update.TabIndex = 14
Me.btn_update.Text = "Update"
Me.btn_update.UseVisualStyleBackColor = True
'
'btn_cancel
'
Me.btn_cancel.Location = New System.Drawing.Point(416, 244)
Me.btn_cancel.Name = "btn_cancel"
Me.btn_cancel.Size = New System.Drawing.Size(156, 38)
Me.btn_cancel.TabIndex = 15
Me.btn_cancel.Text = "Cancel"
Me.btn_cancel.UseVisualStyleBackColor = True
'
'tb_collection
'
Me.tb_collection.Location = New System.Drawing.Point(108, 159)
Me.tb_collection.Name = "tb_collection"
Me.tb_collection.Size = New System.Drawing.Size(516, 20)
Me.tb_collection.TabIndex = 17
'
'Label1
'
Me.Label1.AutoSize = True
Me.Label1.ImeMode = System.Windows.Forms.ImeMode.NoControl
Me.Label1.Location = New System.Drawing.Point(46, 162)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(53, 13)
Me.Label1.TabIndex = 16
Me.Label1.Text = "Collection"
'
'tb_units
'
Me.tb_units.Location = New System.Drawing.Point(108, 197)
Me.tb_units.Name = "tb_units"
Me.tb_units.Size = New System.Drawing.Size(107, 20)
Me.tb_units.TabIndex = 18
'
'Edit_form
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(691, 304)
Me.Controls.Add(Me.tb_units)
Me.Controls.Add(Me.tb_collection)
Me.Controls.Add(Me.Label1)
Me.Controls.Add(Me.btn_cancel)
Me.Controls.Add(Me.btn_update)
Me.Controls.Add(Me.lbl_units)
Me.Controls.Add(Me.tb_section)
Me.Controls.Add(Me.tb_author)
Me.Controls.Add(Me.tb_title)
Me.Controls.Add(Me.lbl_section)
Me.Controls.Add(Me.lbl_title)
Me.Controls.Add(Me.lbl_author)
Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
Me.Name = "Edit_form"
Me.Text = "Edit book"
CType(Me.tb_units, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
Friend WithEvents tb_section As TextBox
Friend WithEvents tb_author As TextBox
Friend WithEvents tb_title As TextBox
Friend WithEvents lbl_section As Label
Friend WithEvents lbl_title As Label
Friend WithEvents lbl_author As Label
Friend WithEvents lbl_units As Label
Friend WithEvents btn_update As Button
Friend WithEvents btn_cancel As Button
Friend WithEvents tb_collection As TextBox
Friend WithEvents Label1 As Label
Friend WithEvents tb_units As NumericUpDown
End Class
|
gomezportillo/Athena
|
Athena/Edit_form.Designer.vb
|
Visual Basic
|
mit
| 7,175
|
' 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.Concurrent
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.RuntimeMembers
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' A NamedTypeBinder provides the context for a type symbol; e.g., looking up names
''' inside the type.
''' </summary>
Friend Class NamedTypeBinder
Inherits Binder
Private ReadOnly _typeSymbol As NamedTypeSymbol
Public Sub New(containingBinder As Binder, typeSymbol As NamedTypeSymbol)
MyBase.New(containingBinder)
Debug.Assert(typeSymbol IsNot Nothing)
' The constraints apply during normal binding, but not in the expression compiler.
' Debug.Assert(Not (TypeOf typeSymbol Is Symbols.Metadata.PE.PENamedTypeSymbol))
' Debug.Assert(typeSymbol.IsFromCompilation(Me.Compilation))
_typeSymbol = typeSymbol
End Sub
''' <summary>
''' Some nodes have special binder's for their contents
''' </summary>
Public Overrides Function GetBinder(node As SyntaxNode) As Binder
' TODO (tomat): this is a temporary workaround, we need a special script class binder
' Return Me so that identifiers in top-level statements bind to the members of the script class.
Return If(_typeSymbol.IsScriptClass, Me, m_containingBinder.GetBinder(node))
End Function
Public Overrides Function GetBinder(stmtList As SyntaxList(Of StatementSyntax)) As Binder
' TODO (tomat): this is a temporary workaround, we need a special script class binder
' Return Me so that identifiers in top-level statements bind to the members of the script class.
Return If(_typeSymbol.IsScriptClass, Me, m_containingBinder.GetBinder(stmtList))
End Function
Public Overrides ReadOnly Property ContainingNamespaceOrType As NamespaceOrTypeSymbol
Get
Return _typeSymbol
End Get
End Property
''' <summary>
''' Gets all symbols of the particular name as
''' a) members of this type
''' b) members of base types
''' c) type parameters in this type (but not outer or base types)
''' In that order.
'''
''' Note, that section "11.4.4 Simple Name Expression" of VB Language spec
''' implies that type parameters are examined first, and only then members
''' of the type are examined. But this is inconsistent with Dev10 behavior.
'''
''' Returns all members of that name, or empty list if none.
''' </summary>
Friend Overrides Sub LookupInSingleBinder(lookupResult As LookupResult,
name As String,
arity As Integer,
options As LookupOptions,
originalBinder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
Debug.Assert(lookupResult.IsClear)
' 1. look for members. This call automatically gets members of base types.
originalBinder.LookupMember(lookupResult, _typeSymbol, name, arity, options, useSiteDiagnostics)
If lookupResult.StopFurtherLookup Then
Return ' short cut result
End If
' 2. Lookup type parameter.
Dim typeParameterLookupResult = LookupResult.GetInstance()
LookupTypeParameter(typeParameterLookupResult, name, arity, options, originalBinder, useSiteDiagnostics)
lookupResult.MergePrioritized(typeParameterLookupResult)
typeParameterLookupResult.Free()
End Sub
''' <summary>
''' Collect extension methods with the given name that are in scope in this binder.
''' The passed in ArrayBuilder must be empty. Extension methods from the same containing type
''' must be grouped together.
''' </summary>
Protected Overrides Sub CollectProbableExtensionMethodsInSingleBinder(name As String,
methods As ArrayBuilder(Of MethodSymbol),
originalBinder As Binder)
Debug.Assert(methods.Count = 0)
_typeSymbol.AppendProbableExtensionMethods(name, methods)
End Sub
Protected Overrides Sub AddExtensionMethodLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder)
_typeSymbol.AddExtensionMethodLookupSymbolsInfo(nameSet, options, originalBinder)
End Sub
Friend Overrides Sub AddLookupSymbolsInfoInSingleBinder(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder)
' 1. Add all type parameters.
' UNDONE: filter using options.
If _typeSymbol.Arity > 0 Then
For Each tp In _typeSymbol.TypeParameters
If originalBinder.CanAddLookupSymbolInfo(tp, options, nameSet, Nothing) Then
nameSet.AddSymbol(tp, tp.Name, 0)
End If
Next
End If
' 2. Add member names on the type.
originalBinder.AddMemberLookupSymbolsInfo(nameSet, _typeSymbol, options)
End Sub
' Look in all type parameters of the given name in the instance type.
' Since there are typically just one or two, using a dictionary/ILookup would be overkill.
Private Sub LookupTypeParameter(lookupResult As LookupResult,
name As String,
arity As Integer,
options As LookupOptions,
originalBinder As Binder,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo))
Debug.Assert(name IsNot Nothing)
Debug.Assert(lookupResult.IsClear)
If _typeSymbol.Arity > 0 Then
For Each tp In _typeSymbol.TypeParameters
If IdentifierComparison.Equals(tp.Name, name) Then
lookupResult.SetFrom(originalBinder.CheckViability(tp, arity, options, Nothing, useSiteDiagnostics))
End If
Next
End If
Return
End Sub
Public Overrides Function CheckAccessibility(sym As Symbol,
<[In], Out> ByRef useSiteDiagnostics As HashSet(Of DiagnosticInfo),
Optional accessThroughType As TypeSymbol = Nothing,
Optional basesBeingResolved As BasesBeingResolved = Nothing) As AccessCheckResult
Return If(IgnoresAccessibility,
AccessCheckResult.Accessible,
AccessCheck.CheckSymbolAccessibility(sym, _typeSymbol, accessThroughType, useSiteDiagnostics, basesBeingResolved))
End Function
Public Overrides ReadOnly Property ContainingType As NamedTypeSymbol
Get
Return _typeSymbol
End Get
End Property
Public Overrides ReadOnly Property ContainingMember As Symbol
Get
Return _typeSymbol
End Get
End Property
Public Overrides ReadOnly Property AdditionalContainingMembers As ImmutableArray(Of Symbol)
Get
Return ImmutableArray(Of Symbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsInQuery As Boolean
Get
Return False
End Get
End Property
End Class
End Namespace
|
aelij/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/NamedTypeBinder.vb
|
Visual Basic
|
apache-2.0
| 8,884
|
' 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.Classification
Imports Microsoft.CodeAnalysis.Classification.Classifiers
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Classification.Classifiers
Friend Class NameSyntaxClassifier
Inherits AbstractNameSyntaxClassifier
Public Overrides ReadOnly Property SyntaxNodeTypes As ImmutableArray(Of Type) = ImmutableArray.Create(
GetType(NameSyntax),
GetType(ModifiedIdentifierSyntax),
GetType(MethodStatementSyntax),
GetType(LabelSyntax))
Public Overrides Sub AddClassifications(
workspace As Workspace,
syntax As SyntaxNode,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim nameSyntax = TryCast(syntax, NameSyntax)
If nameSyntax IsNot Nothing Then
ClassifyNameSyntax(nameSyntax, semanticModel, result, cancellationToken)
Return
End If
Dim modifiedIdentifier = TryCast(syntax, ModifiedIdentifierSyntax)
If modifiedIdentifier IsNot Nothing Then
ClassifyModifiedIdentifier(modifiedIdentifier, semanticModel, result, cancellationToken)
Return
End If
Dim methodStatement = TryCast(syntax, MethodStatementSyntax)
If methodStatement IsNot Nothing Then
ClassifyMethodStatement(methodStatement, semanticModel, result, cancellationToken)
Return
End If
Dim labelSyntax = TryCast(syntax, LabelSyntax)
If labelSyntax IsNot Nothing Then
ClassifyLabelSyntax(labelSyntax, semanticModel, result, cancellationToken)
Return
End If
End Sub
Protected Overrides Function GetRightmostNameArity(node As SyntaxNode) As Integer?
If TypeOf (node) Is ExpressionSyntax Then
Return DirectCast(node, ExpressionSyntax).GetRightmostName()?.Arity
End If
Return Nothing
End Function
Protected Overrides Function IsParentAnAttribute(node As SyntaxNode) As Boolean
Return node.IsParentKind(SyntaxKind.Attribute)
End Function
Private Sub ClassifyNameSyntax(
node As NameSyntax,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
Dim classifiedSpan As ClassifiedSpan
Dim symbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken)
Dim symbol = TryGetSymbol(node, symbolInfo, semanticModel)
If symbol Is Nothing Then
If TryClassifyIdentifier(node, symbol, semanticModel, cancellationToken, classifiedSpan) Then
result.Add(classifiedSpan)
End If
Return
End If
If TryClassifyMyNamespace(node, symbol, semanticModel, cancellationToken, classifiedSpan) Then
result.Add(classifiedSpan)
ElseIf TryClassifySymbol(node, symbol, semanticModel, cancellationToken, classifiedSpan) Then
result.Add(classifiedSpan)
' Additionally classify static symbols
TryClassifyStaticSymbol(symbol, classifiedSpan.TextSpan, result)
End If
End Sub
Private Function TryClassifySymbol(
node As NameSyntax,
symbol As ISymbol,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
ByRef classifiedSpan As ClassifiedSpan) As Boolean
Select Case symbol.Kind
Case SymbolKind.Namespace
' Do not classify the Global namespace. It is already syntactically classified as a keyword.
' Also, we ignore QualifiedNameSyntax nodes since we want to classify individual name parts.
If Not node.IsKind(SyntaxKind.GlobalName) AndAlso TypeOf node Is IdentifierNameSyntax Then
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.NamespaceName)
Return True
End If
Case SymbolKind.Method
Dim classification = GetClassificationForMethod(node, DirectCast(symbol, IMethodSymbol))
If classification IsNot Nothing Then
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification)
Return True
End If
Case SymbolKind.Event
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.EventName)
Return True
Case SymbolKind.Property
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.PropertyName)
Return True
Case SymbolKind.Field
Dim classification = GetClassificationForField(DirectCast(symbol, IFieldSymbol))
If classification IsNot Nothing Then
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification)
Return True
End If
Case SymbolKind.Parameter
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.ParameterName)
Return True
Case SymbolKind.Local
Dim classification = GetClassificationForLocal(DirectCast(symbol, ILocalSymbol))
If classification IsNot Nothing Then
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, classification)
Return True
End If
End Select
Dim type = TryCast(symbol, ITypeSymbol)
If type IsNot Nothing Then
Dim classification = GetClassificationForType(type)
If classification IsNot Nothing Then
Dim token = GetNameToken(node)
classifiedSpan = New ClassifiedSpan(token.Span, classification)
Return True
End If
End If
Return False
End Function
Private Function TryClassifyMyNamespace(
node As NameSyntax,
symbol As ISymbol,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
ByRef classifiedSpan As ClassifiedSpan) As Boolean
If symbol.IsMyNamespace(semanticModel.Compilation) Then
classifiedSpan = New ClassifiedSpan(GetNameToken(node).Span, ClassificationTypeNames.Keyword)
Return True
End If
Return False
End Function
Private Function TryClassifyIdentifier(
node As NameSyntax,
symbol As ISymbol,
semanticModel As SemanticModel,
cancellationToken As CancellationToken,
ByRef classifiedSpan As ClassifiedSpan) As Boolean
' Okay, it doesn't bind to anything.
Dim identifierName = TryCast(node, IdentifierNameSyntax)
If identifierName IsNot Nothing Then
Dim token = identifierName.Identifier
If token.HasMatchingText(SyntaxKind.FromKeyword) AndAlso
semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then
' Optimistically classify "From" as a keyword in expression contexts
classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword)
Return True
ElseIf token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse
token.HasMatchingText(SyntaxKind.IteratorKeyword) Then
' Optimistically classify "Async" or "Iterator" as a keyword in expression contexts
If semanticModel.SyntaxTree.IsExpressionContext(token.SpanStart, cancellationToken, semanticModel) Then
classifiedSpan = New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword)
Return True
End If
End If
End If
Return False
End Function
Private Function GetClassificationForField(fieldSymbol As IFieldSymbol) As String
If fieldSymbol.IsConst Then
Return If(fieldSymbol.ContainingType.IsEnumType(), ClassificationTypeNames.EnumMemberName, ClassificationTypeNames.ConstantName)
End If
Return ClassificationTypeNames.FieldName
End Function
Private Function GetClassificationForLocal(localSymbol As ILocalSymbol) As String
Return If(localSymbol.IsConst,
ClassificationTypeNames.ConstantName,
ClassificationTypeNames.LocalName)
End Function
Private Function GetClassificationForMethod(node As NameSyntax, methodSymbol As IMethodSymbol) As String
Select Case methodSymbol.MethodKind
Case MethodKind.Constructor
' If node is member access or qualified name with explicit New on the right side, we should classify New as a keyword.
If node.IsNewOnRightSideOfDotOrBang() Then
Return ClassificationTypeNames.Keyword
Else
' We bound to a constructor, but we weren't something like the 'New' in 'X.New'.
' This can happen when we're actually just binding the full node 'X.New'. In this
' case, don't return anything for this full node. We'll end up hitting the
' 'New' node as the worker walks down, and we'll classify it then.
Return Nothing
End If
Case MethodKind.BuiltinOperator,
MethodKind.UserDefinedOperator
' Operators are already classified syntactically.
Return Nothing
End Select
Return If(methodSymbol.IsReducedExtension(),
ClassificationTypeNames.ExtensionMethodName,
ClassificationTypeNames.MethodName)
End Function
Private Sub ClassifyModifiedIdentifier(
modifiedIdentifier As ModifiedIdentifierSyntax,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
If modifiedIdentifier.ArrayBounds IsNot Nothing OrElse
modifiedIdentifier.ArrayRankSpecifiers.Count > 0 OrElse
modifiedIdentifier.Nullable.Kind <> SyntaxKind.None Then
Return
End If
If modifiedIdentifier.IsParentKind(SyntaxKind.VariableDeclarator) AndAlso
modifiedIdentifier.Parent.IsParentKind(SyntaxKind.FieldDeclaration) Then
If DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).AsClause Is Nothing AndAlso
DirectCast(modifiedIdentifier.Parent, VariableDeclaratorSyntax).Initializer Is Nothing Then
Dim token = modifiedIdentifier.Identifier
If token.HasMatchingText(SyntaxKind.AsyncKeyword) OrElse
token.HasMatchingText(SyntaxKind.IteratorKeyword) Then
' Optimistically classify "Async" or "Iterator" as a keyword
result.Add(New ClassifiedSpan(token.Span, ClassificationTypeNames.Keyword))
Return
End If
End If
End If
End Sub
Private Function GetNameToken(node As NameSyntax) As SyntaxToken
Select Case node.Kind
Case SyntaxKind.IdentifierName
Return DirectCast(node, IdentifierNameSyntax).Identifier
Case SyntaxKind.GenericName
Return DirectCast(node, GenericNameSyntax).Identifier
Case SyntaxKind.QualifiedName
Return DirectCast(node, QualifiedNameSyntax).Right.Identifier
Case Else
Throw New NotSupportedException()
End Select
End Function
Private Sub ClassifyMethodStatement(methodStatement As MethodStatementSyntax, semanticModel As SemanticModel, result As ArrayBuilder(Of ClassifiedSpan), cancellationToken As CancellationToken)
' Ensure that extension method declarations are classified properly.
' Note that the method statement name is likely already classified as a method name
' by the syntactic classifier. However, there isn't away to determine whether a VB
' method declaration is an extension method syntactically.
Dim methodSymbol = semanticModel.GetDeclaredSymbol(methodStatement)
If methodSymbol IsNot Nothing AndAlso methodSymbol.IsExtensionMethod Then
result.Add(New ClassifiedSpan(methodStatement.Identifier.Span, ClassificationTypeNames.ExtensionMethodName))
End If
End Sub
Private Sub ClassifyLabelSyntax(
node As LabelSyntax,
semanticModel As SemanticModel,
result As ArrayBuilder(Of ClassifiedSpan),
cancellationToken As CancellationToken)
result.Add(New ClassifiedSpan(node.LabelToken.Span, ClassificationTypeNames.LabelName))
End Sub
End Class
End Namespace
|
abock/roslyn
|
src/Workspaces/VisualBasic/Portable/Classification/SyntaxClassification/NameSyntaxClassifier.vb
|
Visual Basic
|
mit
| 14,379
|
' 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.Editing
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.InitializeParameter
Friend Class InitializeParameterHelpers
Public Shared Function GetBody(containingMember As MethodBlockBaseSyntax) As SyntaxNode
Return containingMember
End Function
Public Shared Function IsImplicitConversion(compilation As Compilation, source As ITypeSymbol, destination As ITypeSymbol) As Boolean
Return compilation.ClassifyConversion(source:=source, destination:=destination).IsWidening
End Function
Public Shared Sub InsertStatement(
editor As SyntaxEditor,
body As SyntaxNode,
statementToAddAfterOpt As SyntaxNode,
statement As StatementSyntax)
Dim methodBlock = DirectCast(body, MethodBlockBaseSyntax)
Dim statements = methodBlock.Statements
If statementToAddAfterOpt IsNot Nothing Then
editor.InsertAfter(statementToAddAfterOpt, statement)
Else
Dim newStatements = statements.Insert(0, statement)
editor.SetStatements(body, newStatements)
End If
End Sub
End Class
End Namespace
|
amcasey/roslyn
|
src/Features/VisualBasic/Portable/InitializeParameter/InitializeParameterHelpers.vb
|
Visual Basic
|
apache-2.0
| 1,458
|
' 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
Imports Microsoft.CodeAnalysis.ExtractMethod
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Friend Class VisualBasicSelectionValidator
Inherits SelectionValidator
Public Sub New(document As SemanticDocument,
textSpan As TextSpan,
options As OptionSet)
MyBase.New(document, textSpan, options)
End Sub
Public Overrides Async Function GetValidSelectionAsync(cancellationToken As CancellationToken) As Task(Of SelectionResult)
If Not ContainsValidSelection Then
Return NullSelection
End If
Dim text = Me.SemanticDocument.Text
Dim root = SemanticDocument.Root
Dim model = Me.SemanticDocument.SemanticModel
Dim selectionInfo = GetInitialSelectionInfo(root, cancellationToken)
selectionInfo = AssignInitialFinalTokens(selectionInfo, root, cancellationToken)
selectionInfo = AdjustFinalTokensBasedOnContext(selectionInfo, model, cancellationToken)
selectionInfo = AdjustFinalTokensIfNextStatement(selectionInfo, model, cancellationToken)
selectionInfo = FixUpFinalTokensAndAssignFinalSpan(selectionInfo, root, cancellationToken)
selectionInfo = CheckErrorCasesAndAppendDescriptions(selectionInfo, model, cancellationToken)
If selectionInfo.Status.Failed() Then
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim controlFlowSpan = GetControlFlowSpan(selectionInfo)
If Not selectionInfo.SelectionInExpression Then
Dim statementRange = GetStatementRangeContainedInSpan(Of StatementSyntax)(root, controlFlowSpan, cancellationToken)
If statementRange Is Nothing Then
With selectionInfo
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.can_t_determine_valid_range_of_statements_to_extract_out)
End With
Return New ErrorSelectionResult(selectionInfo.Status)
End If
Dim isFinalSpanSemanticallyValid = IsFinalSpanSemanticallyValidSpan(model, controlFlowSpan, statementRange, cancellationToken)
If Not isFinalSpanSemanticallyValid Then
' check control flow only if we are extracting statement level, not expression level.
' you can't have goto that moves control out of scope in expression level (even in lambda)
With selectionInfo
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Not_all_code_paths_return)
End With
End If
End If
Return Await VisualBasicSelectionResult.CreateResultAsync(selectionInfo.Status,
selectionInfo.OriginalSpan,
selectionInfo.FinalSpan,
Me.Options,
selectionInfo.SelectionInExpression,
Me.SemanticDocument,
selectionInfo.FirstTokenInFinalSpan,
selectionInfo.LastTokenInFinalSpan,
cancellationToken).ConfigureAwait(False)
End Function
Private Function GetControlFlowSpan(selectionInfo As SelectionInfo) As TextSpan
Return TextSpan.FromBounds(selectionInfo.FirstTokenInFinalSpan.SpanStart, selectionInfo.LastTokenInFinalSpan.Span.End)
End Function
Private Function CheckErrorCasesAndAppendDescriptions(selectionInfo As SelectionInfo, semanticModel As SemanticModel, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.FirstTokenInFinalSpan.IsMissing OrElse selectionInfo.LastTokenInFinalSpan.IsMissing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.contains_invalid_selection)
End With
End If
' get the node that covers the selection
Dim commonNode = GetFinalTokenCommonRoot(selectionInfo)
If (selectionInfo.SelectionInExpression OrElse selectionInfo.SelectionInSingleStatement) AndAlso commonNode.HasDiagnostics() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.the_selection_contains_syntactic_errors)
End With
End If
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim tokens = root.DescendantTokens(selectionInfo.FinalSpan)
If tokens.ContainPreprocessorCrossOver(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_be_crossed_over_preprocessors)
End With
End If
' TODO : check behavior of control flow analysis engine around exception and exception handling.
If tokens.ContainArgumentlessThrowWithoutEnclosingCatch(selectionInfo.FinalSpan) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Selection_can_t_contain_throw_without_enclosing_catch_block)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.PartOfConstantInitializerExpression() Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_can_t_be_parts_of_constant_initializer_expression)
End With
End If
If selectionInfo.SelectionInExpression AndAlso commonNode.IsArgumentForByRefParameter(semanticModel, cancellationToken) Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Argument_used_for_ByRef_parameter_can_t_be_extracted_out)
End With
End If
Dim containsAllStaticLocals = ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo, semanticModel, cancellationToken)
If Not containsAllStaticLocals Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.all_static_local_usages_defined_in_the_selection_must_be_included_in_the_selection)
End With
End If
' if it is multiple statement case.
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If commonNode.GetAncestorOrThis(Of WithBlockSyntax)() IsNot Nothing Then
If commonNode.GetImplicitMemberAccessExpressions(selectionInfo.FinalSpan).Any() Then
With clone
.Status = .Status.With(OperationStatusFlag.BestEffort, VBFeaturesResources.Implicit_member_access_can_t_be_included_in_the_selection_without_containing_statement)
End With
End If
End If
End If
If Not selectionInfo.SelectionInExpression AndAlso Not selectionInfo.SelectionInSingleStatement Then
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing OrElse
selectionInfo.LastTokenInFinalSpan.GetAncestor(Of ExecutableStatementSyntax)() Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.Selection_must_be_part_of_executable_statements)
End With
End If
End If
If SelectionChanged(selectionInfo) Then
With clone
.Status = .Status.MarkSuggestion()
End With
End If
Return clone
End Function
Private Function SelectionChanged(selectionInfo As SelectionInfo) As Boolean
' get final token that doesn't pointing to empty token
Dim finalFirstToken = If(selectionInfo.FirstTokenInFinalSpan.Width = 0,
selectionInfo.FirstTokenInFinalSpan.GetNextToken(),
selectionInfo.FirstTokenInFinalSpan)
Dim finalLastToken = If(selectionInfo.LastTokenInFinalSpan.Width = 0,
selectionInfo.LastTokenInFinalSpan.GetPreviousToken(),
selectionInfo.LastTokenInFinalSpan)
' adjust original tokens to point to statement terminator token if needed
Dim originalFirstToken = selectionInfo.FirstTokenInOriginalSpan
Dim originalLastToken = selectionInfo.LastTokenInOriginalSpan
Return originalFirstToken <> finalFirstToken OrElse originalLastToken <> finalLastToken
End Function
Private Function ContainsAllStaticLocalUsagesDefinedInSelectionIfExist(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As Boolean
If selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of FieldDeclarationSyntax)() IsNot Nothing OrElse
selectionInfo.FirstTokenInFinalSpan.GetAncestor(Of PropertyStatementSyntax)() IsNot Nothing Then
' static local can't exist in field initializer
Return True
End If
Dim result As DataFlowAnalysis
If selectionInfo.SelectionInExpression Then
Dim expression = GetFinalTokenCommonRoot(selectionInfo).GetAncestorOrThis(Of ExpressionSyntax)()
result = semanticModel.AnalyzeDataFlow(expression)
Else
Dim range = GetStatementRangeContainedInSpan(Of StatementSyntax)(
semanticModel.SyntaxTree.GetRoot(cancellationToken), GetControlFlowSpan(selectionInfo), cancellationToken)
' we can't determine valid range of statements, don't bother to do the analysis
If range Is Nothing Then
Return True
End If
result = semanticModel.AnalyzeDataFlow(range.Item1, range.Item2)
End If
For Each symbol In result.VariablesDeclared
Dim local = TryCast(symbol, ILocalSymbol)
If local Is Nothing Then
Continue For
End If
If Not local.IsStatic Then
Continue For
End If
If result.WrittenOutside().Any(Function(s) s Is local) OrElse
result.ReadOutside().Any(Function(s) s Is local) Then
Return False
End If
Next
Return True
End Function
Private Function GetFinalTokenCommonRoot(selection As SelectionInfo) As SyntaxNode
Return GetCommonRoot(selection.FirstTokenInFinalSpan, selection.LastTokenInFinalSpan)
End Function
Private Function GetCommonRoot(token1 As SyntaxToken, token2 As SyntaxToken) As SyntaxNode
Return token1.GetCommonRoot(token2)
End Function
Private Function FixUpFinalTokensAndAssignFinalSpan(selectionInfo As SelectionInfo,
root As SyntaxNode,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' make sure we include statement terminator token if selection contains them
Dim firstToken = selectionInfo.FirstTokenInFinalSpan
Dim lastToken = selectionInfo.LastTokenInFinalSpan
' set final span
Dim start = If(selectionInfo.OriginalSpan.Start <= firstToken.SpanStart, selectionInfo.OriginalSpan.Start, firstToken.FullSpan.Start)
Dim [end] = If(lastToken.Span.End <= selectionInfo.OriginalSpan.End, selectionInfo.OriginalSpan.End, lastToken.Span.End)
With clone
.FinalSpan = GetAdjustedSpan(root, TextSpan.FromBounds(start, [end]))
.FirstTokenInFinalSpan = firstToken
.LastTokenInFinalSpan = lastToken
End With
Return clone
End Function
Private Function AdjustFinalTokensIfNextStatement(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' if last statement is next statement, make sure its corresponding loop statement is
' included
Dim nextStatement = selectionInfo.LastTokenInFinalSpan.GetAncestor(Of NextStatementSyntax)()
If nextStatement Is Nothing OrElse nextStatement.ControlVariables.Count < 2 Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
Dim outmostControlVariable = nextStatement.ControlVariables.Last
Dim symbolInfo = semanticModel.GetSymbolInfo(outmostControlVariable, cancellationToken)
Dim symbol = symbolInfo.GetBestOrAllSymbols().FirstOrDefault()
' can't find symbol for the control variable. don't provide extract method
If symbol Is Nothing OrElse
symbol.Locations.Length <> 1 OrElse
Not symbol.Locations.First().IsInSource OrElse
symbol.Locations.First().SourceTree IsNot semanticModel.SyntaxTree Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim startPosition = symbol.Locations.First().SourceSpan.Start
Dim root = semanticModel.SyntaxTree.GetRoot(cancellationToken)
Dim forBlock = root.FindToken(startPosition).GetAncestor(Of ForOrForEachBlockSyntax)()
If forBlock Is Nothing Then
With clone
.Status = .Status.With(OperationStatusFlag.None, VBFeaturesResources.next_statement_control_variable_doesn_t_have_matching_declaration_statement)
End With
Return clone
End If
Dim firstStatement = forBlock.ForOrForEachStatement
With clone
.SelectionInExpression = False
.SelectionInSingleStatement = forBlock.Span.Contains(nextStatement.Span)
.FirstTokenInFinalSpan = firstStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = nextStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Function AdjustFinalTokensBasedOnContext(selectionInfo As SelectionInfo,
semanticModel As SemanticModel,
cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
' don't need to adjust anything if it is multi-statements case
If (Not selectionInfo.SelectionInExpression) AndAlso (Not selectionInfo.SelectionInSingleStatement) Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
' get the node that covers the selection
Dim node = GetFinalTokenCommonRoot(selectionInfo)
Dim validNode = Check(semanticModel, node, cancellationToken)
If validNode Then
Return selectionInfo
End If
Dim firstValidNode = node.GetAncestors(Of SyntaxNode)().FirstOrDefault(
Function(n) Check(semanticModel, n, cancellationToken))
If firstValidNode Is Nothing Then
' couldn't find any valid node
With clone
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Selection_doesn_t_contain_any_valid_node)
.FirstTokenInFinalSpan = Nothing
.LastTokenInFinalSpan = Nothing
End With
Return clone
End If
With clone
.SelectionInExpression = TypeOf firstValidNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf firstValidNode Is StatementSyntax
.FirstTokenInFinalSpan = firstValidNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = firstValidNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Function AssignInitialFinalTokens(selectionInfo As SelectionInfo, root As SyntaxNode, cancellationToken As CancellationToken) As SelectionInfo
If selectionInfo.Status.Failed() Then
Return selectionInfo
End If
Dim clone = selectionInfo.Clone()
If selectionInfo.SelectionInExpression Then
' prefer outer statement or expression if two has same span
Dim outerNode = selectionInfo.CommonRootFromOriginalSpan.GetOutermostNodeWithSameSpan(Function(n) TypeOf n Is StatementSyntax OrElse TypeOf n Is ExpressionSyntax)
' simple expression case
With clone
.SelectionInExpression = TypeOf outerNode Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf outerNode Is StatementSyntax
.FirstTokenInFinalSpan = outerNode.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = outerNode.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
Dim range = GetStatementRangeContainingSpan(Of StatementSyntax)(
root, TextSpan.FromBounds(selectionInfo.FirstTokenInOriginalSpan.SpanStart, selectionInfo.LastTokenInOriginalSpan.Span.End),
cancellationToken)
If range Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
Dim statement1 = DirectCast(range.Item1, StatementSyntax)
Dim statement2 = DirectCast(range.Item2, StatementSyntax)
If statement1 Is statement2 Then
' check one more time to see whether it is an expression case
Dim expression = selectionInfo.CommonRootFromOriginalSpan.GetAncestor(Of ExpressionSyntax)()
If expression IsNot Nothing AndAlso statement1.Span.Contains(expression.Span) Then
With clone
.SelectionInExpression = True
.FirstTokenInFinalSpan = expression.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = expression.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' single statement case
' current way to find out a statement that can be extracted out
Dim singleStatement = statement1.GetAncestorsOrThis(Of StatementSyntax)().FirstOrDefault(
Function(s) s.Parent IsNot Nothing AndAlso s.Parent.IsStatementContainerNode() AndAlso s.Parent.ContainStatement(s))
If singleStatement Is Nothing Then
With clone
.Status = clone.Status.With(OperationStatusFlag.None, VBFeaturesResources.no_valid_statement_range_to_extract_out)
End With
Return clone
End If
With clone
.SelectionInSingleStatement = True
.FirstTokenInFinalSpan = singleStatement.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = singleStatement.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End If
' Special check for vb
' either statement1 or statement2 is pointing to header and end of a block node
' return the block instead of each node
If statement1.Parent.IsStatementContainerNode() Then
Dim contain1 = statement1.Parent.ContainStatement(statement1)
Dim contain2 = statement2.Parent.ContainStatement(statement2)
If Not contain1 OrElse Not contain2 Then
Dim parent = statement1.Parent _
.GetAncestorsOrThis(Of SyntaxNode)() _
.Where(Function(n) TypeOf n Is ExpressionSyntax OrElse TypeOf n Is StatementSyntax) _
.First()
' single statement case
With clone
.SelectionInExpression = TypeOf parent Is ExpressionSyntax
.SelectionInSingleStatement = TypeOf parent Is StatementSyntax
.FirstTokenInFinalSpan = parent.GetFirstToken()
.LastTokenInFinalSpan = parent.GetLastToken()
End With
Return clone
End If
End If
With clone
.FirstTokenInFinalSpan = statement1.GetFirstToken(includeZeroWidth:=True)
.LastTokenInFinalSpan = statement2.GetLastToken(includeZeroWidth:=True)
End With
Return clone
End Function
Private Function GetInitialSelectionInfo(root As SyntaxNode, cancellationToken As CancellationToken) As SelectionInfo
Dim adjustedSpan = GetAdjustedSpan(root, Me.OriginalSpan)
Dim firstTokenInSelection = root.FindTokenOnRightOfPosition(adjustedSpan.Start, includeSkipped:=False)
Dim lastTokenInSelection = root.FindTokenOnLeftOfPosition(adjustedSpan.End, includeSkipped:=False)
If firstTokenInSelection.Kind = SyntaxKind.None OrElse lastTokenInSelection.Kind = SyntaxKind.None Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If firstTokenInSelection <> lastTokenInSelection AndAlso
firstTokenInSelection.Span.End > lastTokenInSelection.SpanStart Then
Return New SelectionInfo With {.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Invalid_selection), .OriginalSpan = adjustedSpan}
End If
If (Not adjustedSpan.Contains(firstTokenInSelection.Span)) AndAlso (Not adjustedSpan.Contains(lastTokenInSelection.Span)) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.Selection_doesn_t_contain_any_valid_token),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
If (Not firstTokenInSelection.UnderValidContext()) OrElse (Not lastTokenInSelection.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim commonRoot = GetCommonRoot(firstTokenInSelection, lastTokenInSelection)
If commonRoot Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.No_common_root_node_for_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Dim selectionInExpression = TypeOf commonRoot Is ExpressionSyntax AndAlso
commonRoot.GetFirstToken(includeZeroWidth:=True) = firstTokenInSelection AndAlso
commonRoot.GetLastToken(includeZeroWidth:=True) = lastTokenInSelection
If (Not selectionInExpression) AndAlso (Not commonRoot.UnderValidContext()) Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
' make sure type block enclosing the selection exist
If commonRoot.GetAncestor(Of TypeBlockSyntax)() Is Nothing Then
Return New SelectionInfo With
{
.Status = New OperationStatus(OperationStatusFlag.None, VBFeaturesResources.No_valid_selection_to_perform_extraction),
.OriginalSpan = adjustedSpan,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End If
Return New SelectionInfo With
{
.Status = OperationStatus.Succeeded,
.OriginalSpan = adjustedSpan,
.CommonRootFromOriginalSpan = commonRoot,
.SelectionInExpression = selectionInExpression,
.FirstTokenInOriginalSpan = firstTokenInSelection,
.LastTokenInOriginalSpan = lastTokenInSelection
}
End Function
Public Overrides Function ContainsNonReturnExitPointsStatements(jumpsOutOfRegion As IEnumerable(Of SyntaxNode)) As Boolean
Dim returnStatement = False
Dim exitStatement = False
For Each statement In jumpsOutOfRegion
If TypeOf statement Is ReturnStatementSyntax Then
returnStatement = True
ElseIf TypeOf statement Is ExitStatementSyntax Then
exitStatement = True
Else
Return True
End If
Next
If exitStatement Then
Return Not returnStatement
End If
Return False
End Function
Public Overrides Function GetOuterReturnStatements(commonRoot As SyntaxNode, jumpsOutOfRegionStatements As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SyntaxNode)
Dim returnStatements = jumpsOutOfRegionStatements.Where(Function(n) TypeOf n Is ReturnStatementSyntax OrElse TypeOf n Is ExitStatementSyntax)
Dim container = commonRoot.GetAncestorsOrThis(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return SpecializedCollections.EmptyEnumerable(Of SyntaxNode)()
End If
Dim returnableConstructPairs = returnStatements.
Select(Function(r) Tuple.Create(r, r.GetAncestors(Of SyntaxNode)().Where(Function(a) a.IsReturnableConstruct()).FirstOrDefault())).
Where(Function(p) p.Item2 IsNot Nothing)
' now filter return statements to only include the one under outmost container
Return returnableConstructPairs.Where(Function(p) p.Item2 Is container).Select(Function(p) p.Item1)
End Function
Public Overrides Function IsFinalSpanSemanticallyValidSpan(root As SyntaxNode,
textSpan As TextSpan,
returnStatements As IEnumerable(Of SyntaxNode),
cancellationToken As CancellationToken) As Boolean
' do quick check to make sure we are under sub (no return value) container. otherwise, there is no point to anymore checks.
If returnStatements.Any(Function(s)
Return s.TypeSwitch(
Function(e As ExitStatementSyntax) e.BlockKeyword.Kind <> SyntaxKind.SubKeyword,
Function(r As ReturnStatementSyntax) r.Expression IsNot Nothing,
Function(n As SyntaxNode) True)
End Function) Then
Return False
End If
' check whether selection reaches the end of the container
Dim lastToken = root.FindToken(textSpan.End)
If lastToken.Kind = SyntaxKind.None Then
Return False
End If
Dim nextToken = lastToken.GetNextToken(includeZeroWidth:=True)
Dim container = nextToken.GetAncestors(Of SyntaxNode).Where(Function(n) n.IsReturnableConstruct()).FirstOrDefault()
If container Is Nothing Then
Return False
End If
If Not container.TypeSwitch(Function(m As MethodBlockBaseSyntax) m.EndBlockStatement.EndKeyword = nextToken,
Function(m As MultiLineLambdaExpressionSyntax) m.EndSubOrFunctionStatement.EndKeyword = nextToken) Then
Return False
End If
Return container.TypeSwitch(Function(m As MethodBlockBaseSyntax) m.BlockStatement.Kind = SyntaxKind.SubStatement,
Function(m As MultiLineLambdaExpressionSyntax) m.SubOrFunctionHeader.Kind = SyntaxKind.SubLambdaHeader)
End Function
Private Shared Function GetAdjustedSpan(root As SyntaxNode, textSpan As TextSpan) As TextSpan
' quick exit
If textSpan.IsEmpty OrElse textSpan.End = 0 Then
Return textSpan
End If
' regular column 0 check
Dim line = root.GetText().Lines.GetLineFromPosition(textSpan.End)
If line.Start <> textSpan.End Then
Return textSpan
End If
' previous line
Contract.ThrowIfFalse(line.LineNumber > 0)
Dim previousLine = root.GetText().Lines(line.LineNumber - 1)
' check whether end of previous line is last token of a statement. if it is, don't do anything
If root.FindTokenOnLeftOfPosition(previousLine.End).IsLastTokenOfStatement() Then
Return textSpan
End If
' move end position of the selection
Return TextSpan.FromBounds(textSpan.Start, previousLine.End)
End Function
Private Class SelectionInfo
Public Property Status() As OperationStatus
Public Property OriginalSpan() As TextSpan
Public Property FinalSpan() As TextSpan
Public Property CommonRootFromOriginalSpan() As SyntaxNode
Public Property FirstTokenInOriginalSpan() As SyntaxToken
Public Property LastTokenInOriginalSpan() As SyntaxToken
Public Property FirstTokenInFinalSpan() As SyntaxToken
Public Property LastTokenInFinalSpan() As SyntaxToken
Public Property SelectionInExpression() As Boolean
Public Property SelectionInSingleStatement() As Boolean
Public Function Clone() As SelectionInfo
Return CType(Me.MemberwiseClone(), SelectionInfo)
End Function
End Class
End Class
End Namespace
|
MatthieuMEZIL/roslyn
|
src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicSelectionValidator.vb
|
Visual Basic
|
apache-2.0
| 34,152
|
' 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.Globalization
Imports System.Threading
Imports Microsoft.CodeAnalysis
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents an event of a tuple type (such as (int, byte).SomeEvent)
''' that is backed by an event within the tuple underlying type.
''' </summary>
Friend NotInheritable Class TupleEventSymbol
Inherits WrappedEventSymbol
Private ReadOnly _containingType As TupleTypeSymbol
Public Overrides ReadOnly Property IsTupleEvent As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property TupleUnderlyingEvent As EventSymbol
Get
Return Me._underlyingEvent
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return Me._containingType
End Get
End Property
Public Overrides ReadOnly Property Type As TypeSymbol
Get
Return Me._underlyingEvent.Type
End Get
End Property
Public Overrides ReadOnly Property AddMethod As MethodSymbol
Get
Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingEvent.AddMethod)
End Get
End Property
Public Overrides ReadOnly Property RemoveMethod As MethodSymbol
Get
Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingEvent.RemoveMethod)
End Get
End Property
Friend Overrides ReadOnly Property AssociatedField As FieldSymbol
Get
Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of FieldSymbol)(Me._underlyingEvent.AssociatedField)
End Get
End Property
Public Overrides ReadOnly Property RaiseMethod As MethodSymbol
Get
Return Me._containingType.GetTupleMemberSymbolForUnderlyingMember(Of MethodSymbol)(Me._underlyingEvent.RaiseMethod)
End Get
End Property
Friend Overrides ReadOnly Property IsExplicitInterfaceImplementation As Boolean
Get
Return Me._underlyingEvent.IsExplicitInterfaceImplementation
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of EventSymbol)
Get
Return Me._underlyingEvent.ExplicitInterfaceImplementations
End Get
End Property
Public Sub New(container As TupleTypeSymbol, underlyingEvent As EventSymbol)
MyBase.New(underlyingEvent)
Me._containingType = container
End Sub
Friend Overrides Function GetUseSiteErrorInfo() As DiagnosticInfo
Dim useSiteDiagnostic As DiagnosticInfo = MyBase.GetUseSiteErrorInfo
MyBase.MergeUseSiteErrorInfo(useSiteDiagnostic, Me._underlyingEvent.GetUseSiteErrorInfo())
Return useSiteDiagnostic
End Function
Public Overrides Function GetHashCode() As Integer
Return Me._underlyingEvent.GetHashCode()
End Function
Public Overrides Function Equals(obj As Object) As Boolean
Return Me.Equals(TryCast(obj, TupleEventSymbol))
End Function
Public Overloads Function Equals(other As TupleEventSymbol) As Boolean
Return other Is Me OrElse
(other IsNot Nothing AndAlso TypeSymbol.Equals(Me._containingType, other._containingType, TypeCompareKind.ConsiderEverything) AndAlso Me._underlyingEvent = other._underlyingEvent)
End Function
Public Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData)
Return Me._underlyingEvent.GetAttributes()
End Function
End Class
End Namespace
|
jmarolf/roslyn
|
src/Compilers/VisualBasic/Portable/Symbols/Tuples/TupleEventSymbol.vb
|
Visual Basic
|
mit
| 4,217
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.IO
Imports System.Text.RegularExpressions
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class AsyncTests
Inherits BasicTestBase
<WorkItem(1004348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1004348")>
<Fact>
Public Sub StructVsClass()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System.Threading.Tasks
Module Module1
Sub Main()
Goo(123).Wait()
End Sub
Public Async Function Goo(a As Integer) As Task
Await Task.Factory.StartNew(Sub() System.Console.WriteLine(a))
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences)
Dim options As VisualBasicCompilationOptions
options = TestOptions.ReleaseExe
Assert.False(options.EnableEditAndContinue)
CompileAndVerify(compilation.WithOptions(options),
expectedOutput:="123",
symbolValidator:=Sub(m As ModuleSymbol)
Dim stateMachine = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Module1").GetMember(Of NamedTypeSymbol)("VB$StateMachine_1_Goo")
Assert.Equal(TypeKind.Structure, stateMachine.TypeKind)
End Sub)
options = TestOptions.DebugExe
Assert.True(options.EnableEditAndContinue)
CompileAndVerify(compilation.WithOptions(options),
expectedOutput:="123",
symbolValidator:=Sub(m As ModuleSymbol)
Dim stateMachine = m.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Module1").GetMember(Of NamedTypeSymbol)("VB$StateMachine_1_Goo")
Assert.Equal(TypeKind.Class, stateMachine.TypeKind)
End Sub)
End Sub
<Fact()>
Public Sub Simple_Void()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public handle As New AutoResetEvent(False)
Sub Main()
Console.Write("0 ")
f()
handle.WaitOne(60000)
Console.Write("1 ")
End Sub
Async Sub f()
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
handle.Set()
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 1")
c.VerifyIL("Form1.Main", <![CDATA[
{
// Code size 42 (0x2a)
.maxstack 2
IL_0000: ldstr "0 "
IL_0005: call "Sub System.Console.Write(String)"
IL_000a: call "Sub Form1.f()"
IL_000f: ldsfld "Form1.handle As System.Threading.AutoResetEvent"
IL_0014: ldc.i4 0xea60
IL_0019: callvirt "Function System.Threading.WaitHandle.WaitOne(Integer) As Boolean"
IL_001e: pop
IL_001f: ldstr "1 "
IL_0024: call "Sub System.Console.Write(String)"
IL_0029: ret
}
]]>)
c.VerifyIL("Form1.f", <![CDATA[
{
// Code size 43 (0x2b)
.maxstack 2
.locals init (Form1.VB$StateMachine_3_f V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Form1.VB$StateMachine_3_f"
IL_0008: ldloca.s V_0
IL_000a: ldc.i4.m1
IL_000b: stfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_0010: ldloca.s V_0
IL_0012: call "Function System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create() As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0017: stfld "Form1.VB$StateMachine_3_f.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_001c: ldloca.s V_0
IL_001e: ldflda "Form1.VB$StateMachine_3_f.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0023: ldloca.s V_0
IL_0025: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start(Of Form1.VB$StateMachine_3_f)(ByRef Form1.VB$StateMachine_3_f)"
IL_002a: ret
}
]]>)
c.VerifyIL("Form1.VB$StateMachine_3_f.MoveNext", <![CDATA[
{
// Code size 197 (0xc5)
.maxstack 3
.locals init (Integer V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_004b
IL_000a: ldstr "2 "
IL_000f: call "Sub System.Console.Write(String)"
IL_0014: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0021: stloc.1
IL_0022: ldloca.s V_1
IL_0024: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0029: brtrue.s IL_0067
IL_002b: ldarg.0
IL_002c: ldc.i4.0
IL_002d: dup
IL_002e: stloc.0
IL_002f: stfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_0034: ldarg.0
IL_0035: ldloc.1
IL_0036: stfld "Form1.VB$StateMachine_3_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_003b: ldarg.0
IL_003c: ldflda "Form1.VB$StateMachine_3_f.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0041: ldloca.s V_1
IL_0043: ldarg.0
IL_0044: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Form1.VB$StateMachine_3_f)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Form1.VB$StateMachine_3_f)"
IL_0049: leave.s IL_00c4
IL_004b: ldarg.0
IL_004c: ldc.i4.m1
IL_004d: dup
IL_004e: stloc.0
IL_004f: stfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldfld "Form1.VB$StateMachine_3_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_005a: stloc.1
IL_005b: ldarg.0
IL_005c: ldflda "Form1.VB$StateMachine_3_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0061: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0067: ldloca.s V_1
IL_0069: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_006e: ldloca.s V_1
IL_0070: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0076: ldstr "3 "
IL_007b: call "Sub System.Console.Write(String)"
IL_0080: ldsfld "Form1.handle As System.Threading.AutoResetEvent"
IL_0085: callvirt "Function System.Threading.EventWaitHandle.Set() As Boolean"
IL_008a: pop
IL_008b: leave.s IL_00af
}
catch System.Exception
{
IL_008d: dup
IL_008e: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0093: stloc.3
IL_0094: ldarg.0
IL_0095: ldc.i4.s -2
IL_0097: stfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_009c: ldarg.0
IL_009d: ldflda "Form1.VB$StateMachine_3_f.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_00a2: ldloc.3
IL_00a3: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"
IL_00a8: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00ad: leave.s IL_00c4
}
IL_00af: ldarg.0
IL_00b0: ldc.i4.s -2
IL_00b2: dup
IL_00b3: stloc.0
IL_00b4: stfld "Form1.VB$StateMachine_3_f.$State As Integer"
IL_00b9: ldarg.0
IL_00ba: ldflda "Form1.VB$StateMachine_3_f.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_00bf: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"
IL_00c4: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_Test()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write(TestLocal({1}).Result.ToString + " ")
End Sub
Async Function TestLocal(p As Integer()) As Task(Of Integer)
Return M(p(0), Await F())
End Function
Public Async Function F() As Task(Of Integer)
Await Task.Yield
Return 1
End Function
Public Function M(ByRef x As Double, y As Integer) As Integer
Return x + y
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="2")
End Sub
<Fact()>
<WorkItem(13867, "https://github.com/dotnet/roslyn/issues/13867")>
Public Sub Simple_Test_ManyLocals()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Sub Main()
DoItAsync().Wait()
End Sub
public async Function DoItAsync() as Task
Dim var1 = 0
Dim var2 = 0
Dim var3 = 0
Dim var4 = 0
Dim var5 = 0
Dim var6 = 0
Dim var7 = 0
Dim var8 = 0
Dim var9 = 0
Dim var10 = 0
Dim var11 = 0
Dim var12 = 0
Dim var13 = 0
Dim var14 = 0
Dim var15 = 0
Dim var16 = 0
Dim var17 = 0
Dim var18 = 0
Dim var19 = 0
Dim var20 = 0
Dim var21 = 0
Dim var22 = 0
Dim var23 = 0
Dim var24 = 0
Dim var25 = 0
Dim var26 = 0
Dim var27 = 0
Dim var28 = 0
Dim var29 = 0
Dim var30 = 0
Dim var31 = 0
Dim s as string
if true
s = "a"
await Task.Yield()
else
s = "b"
end if
Console.WriteLine(if(s , "null")) ' should be "a" always, somehow is "null"
end Function
End Module
</file>
</compilation>, useLatestFramework:=True, options:=TestOptions.DebugExe, expectedOutput:="a")
End Sub
<Fact()>
<WorkItem(13867, "https://github.com/dotnet/roslyn/issues/13867")>
Public Sub Simple_Test_ManyLocals_Rel()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Sub Main()
DoItAsync().Wait()
End Sub
public async Function DoItAsync() as Task
Dim var1 = 0
Dim var2 = 0
Dim var3 = 0
Dim var4 = 0
Dim var5 = 0
Dim var6 = 0
Dim var7 = 0
Dim var8 = 0
Dim var9 = 0
Dim var10 = 0
Dim var11 = 0
Dim var12 = 0
Dim var13 = 0
Dim var14 = 0
Dim var15 = 0
Dim var16 = 0
Dim var17 = 0
Dim var18 = 0
Dim var19 = 0
Dim var20 = 0
Dim var21 = 0
Dim var22 = 0
Dim var23 = 0
Dim var24 = 0
Dim var25 = 0
Dim var26 = 0
Dim var27 = 0
Dim var28 = 0
Dim var29 = 0
Dim var30 = 0
Dim var31 = 0
Dim s as string
if true
s = "a"
await Task.Yield()
else
s = "b"
end if
Console.WriteLine(if(s , "null")) ' should be "a" always, somehow is "null"
end Function
End Module
</file>
</compilation>, useLatestFramework:=True, options:=TestOptions.ReleaseExe, expectedOutput:="a")
End Sub
<Fact()>
Public Sub Simple_Task()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
f().Wait(60000)
Console.Write("1 ")
End Sub
Async Function f() As Task
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 1").
VerifyIL("Form1.VB$StateMachine_1_f.MoveNext",
<![CDATA[
{
// Code size 186 (0xba)
.maxstack 3
.locals init (Integer V_0,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_1,
System.Runtime.CompilerServices.YieldAwaitable V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_004b
IL_000a: ldstr "2 "
IL_000f: call "Sub System.Console.Write(String)"
IL_0014: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0019: stloc.2
IL_001a: ldloca.s V_2
IL_001c: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0021: stloc.1
IL_0022: ldloca.s V_1
IL_0024: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0029: brtrue.s IL_0067
IL_002b: ldarg.0
IL_002c: ldc.i4.0
IL_002d: dup
IL_002e: stloc.0
IL_002f: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0034: ldarg.0
IL_0035: ldloc.1
IL_0036: stfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_003b: ldarg.0
IL_003c: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder"
IL_0041: ldloca.s V_1
IL_0043: ldarg.0
IL_0044: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Form1.VB$StateMachine_1_f)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Form1.VB$StateMachine_1_f)"
IL_0049: leave.s IL_00b9
IL_004b: ldarg.0
IL_004c: ldc.i4.m1
IL_004d: dup
IL_004e: stloc.0
IL_004f: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_005a: stloc.1
IL_005b: ldarg.0
IL_005c: ldflda "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0061: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0067: ldloca.s V_1
IL_0069: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_006e: ldloca.s V_1
IL_0070: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0076: ldstr "3 "
IL_007b: call "Sub System.Console.Write(String)"
IL_0080: leave.s IL_00a4
}
catch System.Exception
{
IL_0082: dup
IL_0083: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0088: stloc.3
IL_0089: ldarg.0
IL_008a: ldc.i4.s -2
IL_008c: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0091: ldarg.0
IL_0092: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder"
IL_0097: ldloc.3
IL_0098: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"
IL_009d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00a2: leave.s IL_00b9
}
IL_00a4: ldarg.0
IL_00a5: ldc.i4.s -2
IL_00a7: dup
IL_00a8: stloc.0
IL_00a9: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_00ae: ldarg.0
IL_00af: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder"
IL_00b4: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"
IL_00b9: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(f().Result.ToString() + " ")
Console.Write("1 ")
End Sub
Async Function f() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 123 1").
VerifyIL("Form1.VB$StateMachine_1_f.MoveNext",
<![CDATA[
{
// Code size 192 (0xc0)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_004b
IL_000a: ldstr "2 "
IL_000f: call "Sub System.Console.Write(String)"
IL_0014: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0019: stloc.3
IL_001a: ldloca.s V_3
IL_001c: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0021: stloc.2
IL_0022: ldloca.s V_2
IL_0024: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0029: brtrue.s IL_0067
IL_002b: ldarg.0
IL_002c: ldc.i4.0
IL_002d: dup
IL_002e: stloc.1
IL_002f: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0034: ldarg.0
IL_0035: ldloc.2
IL_0036: stfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_003b: ldarg.0
IL_003c: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0041: ldloca.s V_2
IL_0043: ldarg.0
IL_0044: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Form1.VB$StateMachine_1_f)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Form1.VB$StateMachine_1_f)"
IL_0049: leave.s IL_00bf
IL_004b: ldarg.0
IL_004c: ldc.i4.m1
IL_004d: dup
IL_004e: stloc.1
IL_004f: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_005a: stloc.2
IL_005b: ldarg.0
IL_005c: ldflda "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0061: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0067: ldloca.s V_2
IL_0069: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_006e: ldloca.s V_2
IL_0070: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0076: ldstr "3 "
IL_007b: call "Sub System.Console.Write(String)"
IL_0080: ldc.i4.s 123
IL_0082: stloc.0
IL_0083: leave.s IL_00a9
}
catch System.Exception
{
IL_0085: dup
IL_0086: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_008b: stloc.s V_4
IL_008d: ldarg.0
IL_008e: ldc.i4.s -2
IL_0090: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0095: ldarg.0
IL_0096: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_009b: ldloc.s V_4
IL_009d: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00a2: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00a7: leave.s IL_00bf
}
IL_00a9: ldarg.0
IL_00aa: ldc.i4.s -2
IL_00ac: dup
IL_00ad: stloc.1
IL_00ae: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_00b3: ldarg.0
IL_00b4: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00b9: ldloc.0
IL_00ba: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00bf: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_1()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write((Async Function() Await f())().Result.ToString() + " ")
Console.Write("1 ")
End Sub
Async Function f() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 123 1")
c.VerifyIL("Form1._Closure$__._Lambda$__0-0",
<![CDATA[
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (Form1._Closure$__.VB$StateMachine___Lambda$__0-0 V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Form1._Closure$__.VB$StateMachine___Lambda$__0-0"
IL_0008: ldloca.s V_0
IL_000a: ldarg.0
IL_000b: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$VB$NonLocal__Closure$__ As Form1._Closure$__"
IL_0010: ldloca.s V_0
IL_0012: ldc.i4.m1
IL_0013: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$State As Integer"
IL_0018: ldloca.s V_0
IL_001a: call "Function System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).Create() As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_001f: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0024: ldloca.s V_0
IL_0026: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_002b: ldloca.s V_0
IL_002d: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).Start(Of Form1._Closure$__.VB$StateMachine___Lambda$__0-0)(ByRef Form1._Closure$__.VB$StateMachine___Lambda$__0-0)"
IL_0032: ldloca.s V_0
IL_0034: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0039: call "Function System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).get_Task() As System.Threading.Tasks.Task(Of Integer)"
IL_003e: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_2()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Dim outer As Integer = 123
Console.Write("0 ")
Console.Write((Async Function()
Return Await f() + outer
End Function)().Result.ToString() + " ")
Console.Write("1 ")
End Sub
Async Function f() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 246 1")
c.VerifyIL("Form1._Closure$__0-0._Lambda$__0", <![CDATA[
{
// Code size 63 (0x3f)
.maxstack 2
.locals init (Form1._Closure$__0-0.VB$StateMachine___Lambda$__0 V_0)
IL_0000: ldloca.s V_0
IL_0002: initobj "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0"
IL_0008: ldloca.s V_0
IL_000a: ldarg.0
IL_000b: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__0-0 As Form1._Closure$__0-0"
IL_0010: ldloca.s V_0
IL_0012: ldc.i4.m1
IL_0013: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0018: ldloca.s V_0
IL_001a: call "Function System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).Create() As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_001f: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0024: ldloca.s V_0
IL_0026: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_002b: ldloca.s V_0
IL_002d: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).Start(Of Form1._Closure$__0-0.VB$StateMachine___Lambda$__0)(ByRef Form1._Closure$__0-0.VB$StateMachine___Lambda$__0)"
IL_0032: ldloca.s V_0
IL_0034: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0039: call "Function System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).get_Task() As System.Threading.Tasks.Task(Of Integer)"
IL_003e: ret
}
]]>)
c.VerifyIL("Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.MoveNext", <![CDATA[
{
// Code size 177 (0xb1)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_003e
IL_000a: call "Function Form1.f() As System.Threading.Tasks.Task(Of Integer)"
IL_000f: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0014: stloc.2
IL_0015: ldloca.s V_2
IL_0017: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_001c: brtrue.s IL_005a
IL_001e: ldarg.0
IL_001f: ldc.i4.0
IL_0020: dup
IL_0021: stloc.1
IL_0022: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0027: ldarg.0
IL_0028: ldloc.2
IL_0029: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_002e: ldarg.0
IL_002f: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0034: ldloca.s V_2
IL_0036: ldarg.0
IL_0037: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), Form1._Closure$__0-0.VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef Form1._Closure$__0-0.VB$StateMachine___Lambda$__0)"
IL_003c: leave.s IL_00b0
IL_003e: ldarg.0
IL_003f: ldc.i4.m1
IL_0040: dup
IL_0041: stloc.1
IL_0042: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0047: ldarg.0
IL_0048: ldfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_004d: stloc.2
IL_004e: ldarg.0
IL_004f: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0054: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005a: ldloca.s V_2
IL_005c: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0061: ldloca.s V_2
IL_0063: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0069: ldarg.0
IL_006a: ldfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__0-0 As Form1._Closure$__0-0"
IL_006f: ldfld "Form1._Closure$__0-0.$VB$Local_outer As Integer"
IL_0074: add.ovf
IL_0075: stloc.0
IL_0076: leave.s IL_009a
}
catch System.Exception
{
IL_0078: dup
IL_0079: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_007e: stloc.3
IL_007f: ldarg.0
IL_0080: ldc.i4.s -2
IL_0082: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0087: ldarg.0
IL_0088: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_008d: ldloc.3
IL_008e: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_0093: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0098: leave.s IL_00b0
}
IL_009a: ldarg.0
IL_009b: ldc.i4.s -2
IL_009d: dup
IL_009e: stloc.1
IL_009f: stfld "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00a4: ldarg.0
IL_00a5: ldflda "Form1._Closure$__0-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00aa: ldloc.0
IL_00ab: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00b0: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_3()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Call (Async Sub() f().Wait(60000))()
Console.Write("1 ")
Call (Async Sub()
f().Wait(60000)
End Sub)()
Console.Write("5 ")
End Sub
Async Function f() As Task
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 1 2 3 5")
c.VerifyIL("Form1._Closure$__.VB$StateMachine___Lambda$__0-1.MoveNext",
<![CDATA[
{
// Code size 81 (0x51)
.maxstack 3
.locals init (Integer V_0,
System.Exception V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-1.$State As Integer"
IL_0006: stloc.0
.try
{
IL_0007: call "Function Form1.f() As System.Threading.Tasks.Task"
IL_000c: ldc.i4 0xea60
IL_0011: callvirt "Function System.Threading.Tasks.Task.Wait(Integer) As Boolean"
IL_0016: pop
IL_0017: leave.s IL_003b
}
catch System.Exception
{
IL_0019: dup
IL_001a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_001f: stloc.1
IL_0020: ldarg.0
IL_0021: ldc.i4.s -2
IL_0023: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-1.$State As Integer"
IL_0028: ldarg.0
IL_0029: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-1.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_002e: ldloc.1
IL_002f: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"
IL_0034: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0039: leave.s IL_0050
}
IL_003b: ldarg.0
IL_003c: ldc.i4.s -2
IL_003e: dup
IL_003f: stloc.0
IL_0040: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-1.$State As Integer"
IL_0045: ldarg.0
IL_0046: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-1.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_004b: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"
IL_0050: ret
}
]]>)
c.VerifyIL("Form1._Closure$__.VB$StateMachine___Lambda$__0-0.MoveNext",
<![CDATA[
{
// Code size 81 (0x51)
.maxstack 3
.locals init (Integer V_0,
System.Exception V_1)
IL_0000: ldarg.0
IL_0001: ldfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$State As Integer"
IL_0006: stloc.0
.try
{
IL_0007: call "Function Form1.f() As System.Threading.Tasks.Task"
IL_000c: ldc.i4 0xea60
IL_0011: callvirt "Function System.Threading.Tasks.Task.Wait(Integer) As Boolean"
IL_0016: pop
IL_0017: leave.s IL_003b
}
catch System.Exception
{
IL_0019: dup
IL_001a: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_001f: stloc.1
IL_0020: ldarg.0
IL_0021: ldc.i4.s -2
IL_0023: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$State As Integer"
IL_0028: ldarg.0
IL_0029: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_002e: ldloc.1
IL_002f: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"
IL_0034: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0039: leave.s IL_0050
}
IL_003b: ldarg.0
IL_003c: ldc.i4.s -2
IL_003e: dup
IL_003f: stloc.0
IL_0040: stfld "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$State As Integer"
IL_0045: ldarg.0
IL_0046: ldflda "Form1._Closure$__.VB$StateMachine___Lambda$__0-0.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_004b: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"
IL_0050: ret
}
]]>)
End Sub
<Fact>
Public Sub Simple_TaskOfT_Lambda_4_nyi()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Console.Write((New CLAZZ()).F().Result.ToString + " ")
Console.Write("X2 ")
End Sub
End Module
Class CLAZZ
Public FX As Integer = 1
Public Async Function F() As Task(Of Integer)
Dim outer As Integer = 100
Console.Write("0 ")
Dim a = Async Function()
Return outer + Me.FX + (Await f2()) + outer + Me.FX
End Function
Console.Write("1 ")
Return Await a()
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 10
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="X1 0 1 2 3 212 X2")
c.VerifyIL("CLAZZ.VB$StateMachine_2_F.MoveNext",
<![CDATA[
{
// Code size 221 (0xdd)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "CLAZZ.VB$StateMachine_2_F.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0076
IL_000a: newobj "Sub CLAZZ._Closure$__2-0..ctor()"
IL_000f: dup
IL_0010: ldarg.0
IL_0011: ldfld "CLAZZ.VB$StateMachine_2_F.$VB$Me As CLAZZ"
IL_0016: stfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_001b: dup
IL_001c: ldc.i4.s 100
IL_001e: stfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_0023: ldstr "0 "
IL_0028: call "Sub System.Console.Write(String)"
IL_002d: ldftn "Function CLAZZ._Closure$__2-0._Lambda$__0() As System.Threading.Tasks.Task(Of Integer)"
IL_0033: newobj "Sub VB$AnonymousDelegate_0(Of System.Threading.Tasks.Task(Of Integer))..ctor(Object, System.IntPtr)"
IL_0038: ldstr "1 "
IL_003d: call "Sub System.Console.Write(String)"
IL_0042: callvirt "Function VB$AnonymousDelegate_0(Of System.Threading.Tasks.Task(Of Integer)).Invoke() As System.Threading.Tasks.Task(Of Integer)"
IL_0047: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_004c: stloc.2
IL_004d: ldloca.s V_2
IL_004f: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_0054: brtrue.s IL_0092
IL_0056: ldarg.0
IL_0057: ldc.i4.0
IL_0058: dup
IL_0059: stloc.1
IL_005a: stfld "CLAZZ.VB$StateMachine_2_F.$State As Integer"
IL_005f: ldarg.0
IL_0060: ldloc.2
IL_0061: stfld "CLAZZ.VB$StateMachine_2_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0066: ldarg.0
IL_0067: ldflda "CLAZZ.VB$StateMachine_2_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_006c: ldloca.s V_2
IL_006e: ldarg.0
IL_006f: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), CLAZZ.VB$StateMachine_2_F)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef CLAZZ.VB$StateMachine_2_F)"
IL_0074: leave.s IL_00dc
IL_0076: ldarg.0
IL_0077: ldc.i4.m1
IL_0078: dup
IL_0079: stloc.1
IL_007a: stfld "CLAZZ.VB$StateMachine_2_F.$State As Integer"
IL_007f: ldarg.0
IL_0080: ldfld "CLAZZ.VB$StateMachine_2_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0085: stloc.2
IL_0086: ldarg.0
IL_0087: ldflda "CLAZZ.VB$StateMachine_2_F.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_008c: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0092: ldloca.s V_2
IL_0094: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0099: ldloca.s V_2
IL_009b: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00a1: stloc.0
IL_00a2: leave.s IL_00c6
}
catch System.Exception
{
IL_00a4: dup
IL_00a5: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00aa: stloc.3
IL_00ab: ldarg.0
IL_00ac: ldc.i4.s -2
IL_00ae: stfld "CLAZZ.VB$StateMachine_2_F.$State As Integer"
IL_00b3: ldarg.0
IL_00b4: ldflda "CLAZZ.VB$StateMachine_2_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00b9: ldloc.3
IL_00ba: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00bf: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00c4: leave.s IL_00dc
}
IL_00c6: ldarg.0
IL_00c7: ldc.i4.s -2
IL_00c9: dup
IL_00ca: stloc.1
IL_00cb: stfld "CLAZZ.VB$StateMachine_2_F.$State As Integer"
IL_00d0: ldarg.0
IL_00d1: ldflda "CLAZZ.VB$StateMachine_2_F.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00d6: ldloc.0
IL_00d7: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00dc: ret
}
]]>)
c.VerifyIL("CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.MoveNext",
<![CDATA[
{
// Code size 249 (0xf9)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_006e
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0011: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_0016: ldarg.0
IL_0017: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_001c: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0021: ldfld "CLAZZ.FX As Integer"
IL_0026: add.ovf
IL_0027: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$U1 As Integer"
IL_002c: ldarg.0
IL_002d: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0032: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0037: call "Function CLAZZ.f2() As System.Threading.Tasks.Task(Of Integer)"
IL_003c: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0041: stloc.2
IL_0042: ldloca.s V_2
IL_0044: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_0049: brtrue.s IL_008a
IL_004b: ldarg.0
IL_004c: ldc.i4.0
IL_004d: dup
IL_004e: stloc.1
IL_004f: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldloc.2
IL_0056: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005b: ldarg.0
IL_005c: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0061: ldloca.s V_2
IL_0063: ldarg.0
IL_0064: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)"
IL_0069: leave IL_00f8
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.1
IL_0072: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0077: ldarg.0
IL_0078: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_007d: stloc.2
IL_007e: ldarg.0
IL_007f: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0084: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_008a: ldarg.0
IL_008b: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$U1 As Integer"
IL_0090: ldloca.s V_2
IL_0092: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0097: ldloca.s V_2
IL_0099: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_009f: add.ovf
IL_00a0: ldarg.0
IL_00a1: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00a6: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_00ab: add.ovf
IL_00ac: ldarg.0
IL_00ad: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00b2: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_00b7: ldfld "CLAZZ.FX As Integer"
IL_00bc: add.ovf
IL_00bd: stloc.0
IL_00be: leave.s IL_00e2
}
catch System.Exception
{
IL_00c0: dup
IL_00c1: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00c6: stloc.3
IL_00c7: ldarg.0
IL_00c8: ldc.i4.s -2
IL_00ca: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00cf: ldarg.0
IL_00d0: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00d5: ldloc.3
IL_00d6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00db: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00e0: leave.s IL_00f8
}
IL_00e2: ldarg.0
IL_00e3: ldc.i4.s -2
IL_00e5: dup
IL_00e6: stloc.1
IL_00e7: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00ec: ldarg.0
IL_00ed: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00f2: ldloc.0
IL_00f3: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00f8: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_5_nyi()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Console.Write((New CLAZZ()).F().Result.ToString + " ")
Console.Write("X2 ")
End Sub
End Module
Class CLAZZ
Public FX As Integer = 1
Public Async Function F() As Task(Of Integer)
Dim outer As Integer = 100
Console.Write("0 ")
Dim a = Async Function()
Dim result = outer + Me.FX
result = Await f2() + result ' Requires stack spilling because 'result' is hoisted
Return result + outer + Me.FX
End Function
Console.Write("1 ")
Return Await a()
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 10
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="X1 0 1 2 3 212 X2")
c.VerifyIL("CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.MoveNext",
<![CDATA[
{
// Code size 261 (0x105)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_006e
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0011: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_0016: ldarg.0
IL_0017: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_001c: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0021: ldfld "CLAZZ.FX As Integer"
IL_0026: add.ovf
IL_0027: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_002c: ldarg.0
IL_002d: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0032: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0037: call "Function CLAZZ.f2() As System.Threading.Tasks.Task(Of Integer)"
IL_003c: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0041: stloc.2
IL_0042: ldloca.s V_2
IL_0044: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_0049: brtrue.s IL_008a
IL_004b: ldarg.0
IL_004c: ldc.i4.0
IL_004d: dup
IL_004e: stloc.1
IL_004f: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldloc.2
IL_0056: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005b: ldarg.0
IL_005c: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0061: ldloca.s V_2
IL_0063: ldarg.0
IL_0064: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)"
IL_0069: leave IL_0104
IL_006e: ldarg.0
IL_006f: ldc.i4.m1
IL_0070: dup
IL_0071: stloc.1
IL_0072: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0077: ldarg.0
IL_0078: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_007d: stloc.2
IL_007e: ldarg.0
IL_007f: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0084: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_008a: ldarg.0
IL_008b: ldloca.s V_2
IL_008d: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0092: ldloca.s V_2
IL_0094: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_009a: ldarg.0
IL_009b: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_00a0: add.ovf
IL_00a1: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_00a6: ldarg.0
IL_00a7: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_00ac: ldarg.0
IL_00ad: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00b2: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_00b7: add.ovf
IL_00b8: ldarg.0
IL_00b9: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00be: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_00c3: ldfld "CLAZZ.FX As Integer"
IL_00c8: add.ovf
IL_00c9: stloc.0
IL_00ca: leave.s IL_00ee
}
catch System.Exception
{
IL_00cc: dup
IL_00cd: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00d2: stloc.3
IL_00d3: ldarg.0
IL_00d4: ldc.i4.s -2
IL_00d6: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00db: ldarg.0
IL_00dc: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00e1: ldloc.3
IL_00e2: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00e7: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00ec: leave.s IL_0104
}
IL_00ee: ldarg.0
IL_00ef: ldc.i4.s -2
IL_00f1: dup
IL_00f2: stloc.1
IL_00f3: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00f8: ldarg.0
IL_00f9: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00fe: ldloc.0
IL_00ff: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_0104: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_6()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Console.Write((New CLAZZ()).F(1000).Result.ToString + " ")
Console.Write("X2 ")
End Sub
End Module
Class CLAZZ
Public FX As Integer = 1
Public Async Function F(p As Integer) As Task(Of Integer)
Dim outer As Integer = 100
Console.Write("0 ")
Dim a = Async Function()
Dim result = outer + Me.FX
Dim x = Await f2()
Return x + result + p
End Function
Console.Write("1 ")
Return Await a()
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 10
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="X1 0 1 2 3 1111 X2")
c.VerifyIL("CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.MoveNext",
<![CDATA[
{
// Code size 229 (0xe5)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_006b
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0011: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_0016: ldarg.0
IL_0017: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_001c: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0021: ldfld "CLAZZ.FX As Integer"
IL_0026: add.ovf
IL_0027: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_002c: ldarg.0
IL_002d: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0032: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0037: call "Function CLAZZ.f2() As System.Threading.Tasks.Task(Of Integer)"
IL_003c: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0041: stloc.2
IL_0042: ldloca.s V_2
IL_0044: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_0049: brtrue.s IL_0087
IL_004b: ldarg.0
IL_004c: ldc.i4.0
IL_004d: dup
IL_004e: stloc.1
IL_004f: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0054: ldarg.0
IL_0055: ldloc.2
IL_0056: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005b: ldarg.0
IL_005c: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0061: ldloca.s V_2
IL_0063: ldarg.0
IL_0064: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)"
IL_0069: leave.s IL_00e4
IL_006b: ldarg.0
IL_006c: ldc.i4.m1
IL_006d: dup
IL_006e: stloc.1
IL_006f: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0074: ldarg.0
IL_0075: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_007a: stloc.2
IL_007b: ldarg.0
IL_007c: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0081: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0087: ldloca.s V_2
IL_0089: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_008e: ldloca.s V_2
IL_0090: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0096: ldarg.0
IL_0097: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_009c: add.ovf
IL_009d: ldarg.0
IL_009e: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00a3: ldfld "CLAZZ._Closure$__2-0.$VB$Local_p As Integer"
IL_00a8: add.ovf
IL_00a9: stloc.0
IL_00aa: leave.s IL_00ce
}
catch System.Exception
{
IL_00ac: dup
IL_00ad: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00b2: stloc.3
IL_00b3: ldarg.0
IL_00b4: ldc.i4.s -2
IL_00b6: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00bb: ldarg.0
IL_00bc: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00c1: ldloc.3
IL_00c2: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00c7: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00cc: leave.s IL_00e4
}
IL_00ce: ldarg.0
IL_00cf: ldc.i4.s -2
IL_00d1: dup
IL_00d2: stloc.1
IL_00d3: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00d8: ldarg.0
IL_00d9: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00de: ldloc.0
IL_00df: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00e4: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_TaskOfT_Lambda_6_D()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Console.Write((New CLAZZ()).F(1000).Result.ToString + " ")
Console.Write("X2 ")
End Sub
End Module
Class CLAZZ
Public FX As Integer = 1
Public Async Function F(p As Integer) As Task(Of Integer)
Dim outer As Integer = 100
Console.Write("0 ")
Dim a = Async Function()
Dim result = outer + Me.FX
Dim x = Await f2()
Return x + result + p
End Function
Console.Write("1 ")
Return Await a()
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 10
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, options:=TestOptions.ReleaseDebugExe, expectedOutput:="X1 0 1 2 3 1111 X2")
c.VerifyIL("CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.MoveNext",
<![CDATA[
{
// Code size 243 (0xf3)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Threading.Tasks.Task(Of Integer) V_2,
Integer V_3, //x
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_4,
Integer V_5,
System.Exception V_6)
IL_0000: ldarg.0
IL_0001: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0070
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0011: ldfld "CLAZZ._Closure$__2-0.$VB$Local_outer As Integer"
IL_0016: ldarg.0
IL_0017: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_001c: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0021: ldfld "CLAZZ.FX As Integer"
IL_0026: add.ovf
IL_0027: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_002c: ldarg.0
IL_002d: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_0032: ldfld "CLAZZ._Closure$__2-0.$VB$Me As CLAZZ"
IL_0037: call "Function CLAZZ.f2() As System.Threading.Tasks.Task(Of Integer)"
IL_003c: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0041: stloc.s V_4
IL_0043: ldloca.s V_4
IL_0045: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_004a: brtrue.s IL_008d
IL_004c: ldarg.0
IL_004d: ldc.i4.0
IL_004e: dup
IL_004f: stloc.1
IL_0050: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0055: ldarg.0
IL_0056: ldloc.s V_4
IL_0058: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005d: ldarg.0
IL_005e: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0063: ldloca.s V_4
IL_0065: ldarg.0
IL_0066: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0)"
IL_006b: leave IL_00f2
IL_0070: ldarg.0
IL_0071: ldc.i4.m1
IL_0072: dup
IL_0073: stloc.1
IL_0074: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_0079: ldarg.0
IL_007a: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_007f: stloc.s V_4
IL_0081: ldarg.0
IL_0082: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0087: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_008d: ldloca.s V_4
IL_008f: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0094: stloc.s V_5
IL_0096: ldloca.s V_4
IL_0098: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_009e: ldloc.s V_5
IL_00a0: stloc.3
IL_00a1: ldloc.3
IL_00a2: ldarg.0
IL_00a3: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As Integer"
IL_00a8: add.ovf
IL_00a9: ldarg.0
IL_00aa: ldfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As CLAZZ._Closure$__2-0"
IL_00af: ldfld "CLAZZ._Closure$__2-0.$VB$Local_p As Integer"
IL_00b4: add.ovf
IL_00b5: stloc.0
IL_00b6: leave.s IL_00dc
}
catch System.Exception
{
IL_00b8: dup
IL_00b9: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00be: stloc.s V_6
IL_00c0: ldarg.0
IL_00c1: ldc.i4.s -2
IL_00c3: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00c8: ldarg.0
IL_00c9: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00ce: ldloc.s V_6
IL_00d0: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00d5: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00da: leave.s IL_00f2
}
IL_00dc: ldarg.0
IL_00dd: ldc.i4.s -2
IL_00df: dup
IL_00e0: stloc.1
IL_00e1: stfld "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$State As Integer"
IL_00e6: ldarg.0
IL_00e7: ldflda "CLAZZ._Closure$__2-0.VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00ec: ldloc.0
IL_00ed: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00f2: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_Finalizer()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(f().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function f() As Task(Of Integer)
Try
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
Finally
Console.Write("4 ")
End Try
Return -321
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 123 1")
c.VerifyIL("Form1.VB$StateMachine_1_f.MoveNext", <![CDATA[
{
// Code size 233 (0xe9)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter V_2,
System.Runtime.CompilerServices.YieldAwaitable V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: ldc.i4.1
IL_0009: pop
IL_000a: pop
IL_000b: nop
.try
{
IL_000c: ldloc.1
IL_000d: brfalse.s IL_0065
IL_000f: ldloc.1
IL_0010: ldc.i4.1
IL_0011: bne.un.s IL_0021
IL_0013: ldarg.0
IL_0014: ldc.i4.m1
IL_0015: dup
IL_0016: stloc.1
IL_0017: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_001c: leave IL_00e8
IL_0021: ldstr "2 "
IL_0026: call "Sub System.Console.Write(String)"
IL_002b: call "Function System.Threading.Tasks.Task.Yield() As System.Runtime.CompilerServices.YieldAwaitable"
IL_0030: stloc.3
IL_0031: ldloca.s V_3
IL_0033: call "Function System.Runtime.CompilerServices.YieldAwaitable.GetAwaiter() As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0038: stloc.2
IL_0039: ldloca.s V_2
IL_003b: call "Function System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.get_IsCompleted() As Boolean"
IL_0040: brtrue.s IL_0081
IL_0042: ldarg.0
IL_0043: ldc.i4.0
IL_0044: dup
IL_0045: stloc.1
IL_0046: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_004b: ldarg.0
IL_004c: ldloc.2
IL_004d: stfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0052: ldarg.0
IL_0053: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0058: ldloca.s V_2
IL_005a: ldarg.0
IL_005b: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, Form1.VB$StateMachine_1_f)(ByRef System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter, ByRef Form1.VB$StateMachine_1_f)"
IL_0060: leave IL_00e8
IL_0065: ldarg.0
IL_0066: ldc.i4.m1
IL_0067: dup
IL_0068: stloc.1
IL_0069: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_006e: ldarg.0
IL_006f: ldfld "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0074: stloc.2
IL_0075: ldarg.0
IL_0076: ldflda "Form1.VB$StateMachine_1_f.$A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_007b: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0081: ldloca.s V_2
IL_0083: call "Sub System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter.GetResult()"
IL_0088: ldloca.s V_2
IL_008a: initobj "System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter"
IL_0090: ldstr "3 "
IL_0095: call "Sub System.Console.Write(String)"
IL_009a: ldc.i4.s 123
IL_009c: stloc.0
IL_009d: leave.s IL_00d2
}
finally
{
IL_009f: ldloc.1
IL_00a0: ldc.i4.0
IL_00a1: bge.s IL_00ad
IL_00a3: ldstr "4 "
IL_00a8: call "Sub System.Console.Write(String)"
IL_00ad: endfinally
}
}
catch System.Exception
{
IL_00ae: dup
IL_00af: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00b4: stloc.s V_4
IL_00b6: ldarg.0
IL_00b7: ldc.i4.s -2
IL_00b9: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_00be: ldarg.0
IL_00bf: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00c4: ldloc.s V_4
IL_00c6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00cb: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00d0: leave.s IL_00e8
}
IL_00d2: ldarg.0
IL_00d3: ldc.i4.s -2
IL_00d5: dup
IL_00d6: stloc.1
IL_00d7: stfld "Form1.VB$StateMachine_1_f.$State As Integer"
IL_00dc: ldarg.0
IL_00dd: ldflda "Form1.VB$StateMachine_1_f.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00e2: ldloc.0
IL_00e3: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00e8: ret
}
]]>)
End Sub
<Fact, WorkItem(1002672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1002672")>
Public Sub Simple_LateBinding_1()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As Object
Return Nothing
End Function
End Class
Module Program
Async Sub Test2()
Dim o As Object = New MyTask(Of Integer)
Dim x = Await o
Await o
End Sub
Sub Main()
End Sub
End Module
</file>
</compilation>, options:=TestOptions.DebugExe, useLatestFramework:=True)
c.VerifyIL("Program.VB$StateMachine_0_Test2.MoveNext",
<![CDATA[
{
// Code size 485 (0x1e5)
.maxstack 8
.locals init (Integer V_0,
Object V_1,
System.Runtime.CompilerServices.ICriticalNotifyCompletion V_2,
System.Runtime.CompilerServices.INotifyCompletion V_3,
Program.VB$StateMachine_0_Test2 V_4,
Object V_5,
System.Runtime.CompilerServices.ICriticalNotifyCompletion V_6,
System.Runtime.CompilerServices.INotifyCompletion V_7,
System.Exception V_8)
~IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_0006: stloc.0
.try
{
~IL_0007: ldloc.0
IL_0008: brfalse.s IL_0012
IL_000a: br.s IL_000c
IL_000c: ldloc.0
IL_000d: ldc.i4.1
IL_000e: beq.s IL_0017
IL_0010: br.s IL_001c
IL_0012: br IL_00af
IL_0017: br IL_0174
-IL_001c: nop
-IL_001d: ldarg.0
IL_001e: newobj "Sub MyTask(Of Integer)..ctor()"
IL_0023: stfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_o$0 As Object"
-IL_0028: ldarg.0
IL_0029: ldfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_o$0 As Object"
IL_002e: ldnull
IL_002f: ldstr "GetAwaiter"
IL_0034: ldc.i4.0
IL_0035: newarr "Object"
IL_003a: ldnull
IL_003b: ldnull
IL_003c: ldnull
IL_003d: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0042: stloc.1
~IL_0043: ldloc.1
IL_0044: ldnull
IL_0045: ldstr "IsCompleted"
IL_004a: ldc.i4.0
IL_004b: newarr "Object"
IL_0050: ldnull
IL_0051: ldnull
IL_0052: ldnull
IL_0053: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0058: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_005d: brfalse.s IL_0061
IL_005f: br.s IL_00c6
IL_0061: ldarg.0
IL_0062: ldc.i4.0
IL_0063: dup
IL_0064: stloc.0
IL_0065: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
<IL_006a: ldarg.0
IL_006b: ldloc.1
IL_006c: stfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_0071: ldloc.1
IL_0072: isinst "System.Runtime.CompilerServices.ICriticalNotifyCompletion"
IL_0077: stloc.2
IL_0078: ldloc.2
IL_0079: brfalse.s IL_0090
IL_007b: ldarg.0
IL_007c: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0081: ldloca.s V_2
IL_0083: ldarg.0
IL_0084: stloc.s V_4
IL_0086: ldloca.s V_4
IL_0088: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.ICriticalNotifyCompletion, Program.VB$StateMachine_0_Test2)(ByRef System.Runtime.CompilerServices.ICriticalNotifyCompletion, ByRef Program.VB$StateMachine_0_Test2)"
IL_008d: nop
IL_008e: br.s IL_00aa
IL_0090: ldloc.1
IL_0091: castclass "System.Runtime.CompilerServices.INotifyCompletion"
IL_0096: stloc.3
IL_0097: ldarg.0
IL_0098: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_009d: ldloca.s V_3
IL_009f: ldarg.0
IL_00a0: stloc.s V_4
IL_00a2: ldloca.s V_4
IL_00a4: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of System.Runtime.CompilerServices.INotifyCompletion, Program.VB$StateMachine_0_Test2)(ByRef System.Runtime.CompilerServices.INotifyCompletion, ByRef Program.VB$StateMachine_0_Test2)"
IL_00a9: nop
IL_00aa: leave IL_01e4
>IL_00af: ldarg.0
IL_00b0: ldc.i4.m1
IL_00b1: dup
IL_00b2: stloc.0
IL_00b3: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_00b8: ldarg.0
IL_00b9: ldfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_00be: stloc.1
IL_00bf: ldarg.0
IL_00c0: ldnull
IL_00c1: stfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_00c6: ldarg.0
IL_00c7: ldloc.1
IL_00c8: ldnull
IL_00c9: ldstr "GetResult"
IL_00ce: ldc.i4.0
IL_00cf: newarr "Object"
IL_00d4: ldnull
IL_00d5: ldnull
IL_00d6: ldnull
IL_00d7: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_00dc: ldnull
IL_00dd: stloc.1
IL_00de: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_00e3: stfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_x$1 As Object"
-IL_00e8: ldarg.0
IL_00e9: ldfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_o$0 As Object"
IL_00ee: ldnull
IL_00ef: ldstr "GetAwaiter"
IL_00f4: ldc.i4.0
IL_00f5: newarr "Object"
IL_00fa: ldnull
IL_00fb: ldnull
IL_00fc: ldnull
IL_00fd: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_0102: stloc.s V_5
~IL_0104: ldloc.s V_5
IL_0106: ldnull
IL_0107: ldstr "IsCompleted"
IL_010c: ldc.i4.0
IL_010d: newarr "Object"
IL_0112: ldnull
IL_0113: ldnull
IL_0114: ldnull
IL_0115: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object, System.Type, String, Object(), String(), System.Type(), Boolean()) As Object"
IL_011a: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToBoolean(Object) As Boolean"
IL_011f: brfalse.s IL_0123
IL_0121: br.s IL_018c
IL_0123: ldarg.0
IL_0124: ldc.i4.1
IL_0125: dup
IL_0126: stloc.0
IL_0127: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
<IL_012c: ldarg.0
IL_012d: ldloc.s V_5
IL_012f: stfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_0134: ldloc.s V_5
IL_0136: isinst "System.Runtime.CompilerServices.ICriticalNotifyCompletion"
IL_013b: stloc.s V_6
IL_013d: ldloc.s V_6
IL_013f: brfalse.s IL_0156
IL_0141: ldarg.0
IL_0142: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0147: ldloca.s V_6
IL_0149: ldarg.0
IL_014a: stloc.s V_4
IL_014c: ldloca.s V_4
IL_014e: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.ICriticalNotifyCompletion, Program.VB$StateMachine_0_Test2)(ByRef System.Runtime.CompilerServices.ICriticalNotifyCompletion, ByRef Program.VB$StateMachine_0_Test2)"
IL_0153: nop
IL_0154: br.s IL_0172
IL_0156: ldloc.s V_5
IL_0158: castclass "System.Runtime.CompilerServices.INotifyCompletion"
IL_015d: stloc.s V_7
IL_015f: ldarg.0
IL_0160: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0165: ldloca.s V_7
IL_0167: ldarg.0
IL_0168: stloc.s V_4
IL_016a: ldloca.s V_4
IL_016c: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of System.Runtime.CompilerServices.INotifyCompletion, Program.VB$StateMachine_0_Test2)(ByRef System.Runtime.CompilerServices.INotifyCompletion, ByRef Program.VB$StateMachine_0_Test2)"
IL_0171: nop
IL_0172: leave.s IL_01e4
>IL_0174: ldarg.0
IL_0175: ldc.i4.m1
IL_0176: dup
IL_0177: stloc.0
IL_0178: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_017d: ldarg.0
IL_017e: ldfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_0183: stloc.s V_5
IL_0185: ldarg.0
IL_0186: ldnull
IL_0187: stfld "Program.VB$StateMachine_0_Test2.$A0 As Object"
IL_018c: ldloc.s V_5
IL_018e: ldnull
IL_018f: ldstr "GetResult"
IL_0194: ldc.i4.0
IL_0195: newarr "Object"
IL_019a: ldnull
IL_019b: ldnull
IL_019c: ldnull
IL_019d: ldc.i4.1
IL_019e: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object"
IL_01a3: pop
IL_01a4: ldnull
IL_01a5: stloc.s V_5
-IL_01a7: leave.s IL_01ce
}
catch System.Exception
{
~$IL_01a9: dup
IL_01aa: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_01af: stloc.s V_8
~IL_01b1: ldarg.0
IL_01b2: ldc.i4.s -2
IL_01b4: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_01b9: ldarg.0
IL_01ba: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_01bf: ldloc.s V_8
IL_01c1: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"
IL_01c6: nop
IL_01c7: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_01cc: leave.s IL_01e4
}
-IL_01ce: ldarg.0
IL_01cf: ldc.i4.s -2
IL_01d1: dup
IL_01d2: stloc.0
IL_01d3: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
~IL_01d8: ldarg.0
IL_01d9: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_01de: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"
IL_01e3: nop
IL_01e4: ret
}
]]>,
sequencePoints:="Program+VB$StateMachine_0_Test2.MoveNext")
End Sub
<Fact, WorkItem(1002672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1002672")>
Public Sub Simple_LateBinding_2()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Runtime.CompilerServices
Class MyTask(Of T)
Function GetAwaiter() As MyTaskAwaiter(Of T)
Return Nothing
End Function
End Class
Structure MyTaskAwaiter(Of T)
Implements INotifyCompletion
Friend m_Task As MyTask(Of T)
ReadOnly Property IsCompleted As Boolean
Get
Throw New NotImplementedException()
End Get
End Property
Sub OnCompleted(r As Action) Implements INotifyCompletion.OnCompleted
Throw New NotImplementedException()
End Sub
Function GetResult() As Object
Throw New NotImplementedException()
End Function
End Structure
Module Program
Async Sub Test2()
Dim o As New MyTask(Of Integer)
Dim x As Integer = Await o
System.Console.WriteLine(x)
End Sub
Sub Main()
End Sub
End Module
</file>
</compilation>, options:=TestOptions.DebugExe, useLatestFramework:=True)
c.VerifyIL("Program.VB$StateMachine_0_Test2.MoveNext",
<![CDATA[
{
// Code size 223 (0xdf)
.maxstack 3
.locals init (Integer V_0,
MyTaskAwaiter(Of Integer) V_1,
Program.VB$StateMachine_0_Test2 V_2,
Object V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_0006: stloc.0
.try
{
IL_0007: ldloc.0
IL_0008: brfalse.s IL_000c
IL_000a: br.s IL_000e
IL_000c: br.s IL_0056
IL_000e: nop
IL_000f: ldarg.0
IL_0010: newobj "Sub MyTask(Of Integer)..ctor()"
IL_0015: stfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_o$0 As MyTask(Of Integer)"
IL_001a: ldarg.0
IL_001b: ldfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_o$0 As MyTask(Of Integer)"
IL_0020: callvirt "Function MyTask(Of Integer).GetAwaiter() As MyTaskAwaiter(Of Integer)"
IL_0025: stloc.1
IL_0026: ldloca.s V_1
IL_0028: call "Function MyTaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_002d: brtrue.s IL_0074
IL_002f: ldarg.0
IL_0030: ldc.i4.0
IL_0031: dup
IL_0032: stloc.0
IL_0033: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_0038: ldarg.0
IL_0039: ldloc.1
IL_003a: stfld "Program.VB$StateMachine_0_Test2.$A0 As MyTaskAwaiter(Of Integer)"
IL_003f: ldarg.0
IL_0040: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_0045: ldloca.s V_1
IL_0047: ldarg.0
IL_0048: stloc.2
IL_0049: ldloca.s V_2
IL_004b: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitOnCompleted(Of MyTaskAwaiter(Of Integer), Program.VB$StateMachine_0_Test2)(ByRef MyTaskAwaiter(Of Integer), ByRef Program.VB$StateMachine_0_Test2)"
IL_0050: nop
IL_0051: leave IL_00de
IL_0056: ldarg.0
IL_0057: ldc.i4.m1
IL_0058: dup
IL_0059: stloc.0
IL_005a: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_005f: ldarg.0
IL_0060: ldfld "Program.VB$StateMachine_0_Test2.$A0 As MyTaskAwaiter(Of Integer)"
IL_0065: stloc.1
IL_0066: ldarg.0
IL_0067: ldflda "Program.VB$StateMachine_0_Test2.$A0 As MyTaskAwaiter(Of Integer)"
IL_006c: initobj "MyTaskAwaiter(Of Integer)"
IL_0072: br.s IL_0074
IL_0074: ldarg.0
IL_0075: ldloca.s V_1
IL_0077: call "Function MyTaskAwaiter(Of Integer).GetResult() As Object"
IL_007c: stloc.3
IL_007d: ldloca.s V_1
IL_007f: initobj "MyTaskAwaiter(Of Integer)"
IL_0085: ldloc.3
IL_0086: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_008b: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer"
IL_0090: stfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_x$1 As Integer"
IL_0095: ldarg.0
IL_0096: ldfld "Program.VB$StateMachine_0_Test2.$VB$ResumableLocal_x$1 As Integer"
IL_009b: call "Sub System.Console.WriteLine(Integer)"
IL_00a0: nop
IL_00a1: leave.s IL_00c8
}
catch System.Exception
{
IL_00a3: dup
IL_00a4: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00a9: stloc.s V_4
IL_00ab: ldarg.0
IL_00ac: ldc.i4.s -2
IL_00ae: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_00b3: ldarg.0
IL_00b4: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_00b9: ldloc.s V_4
IL_00bb: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"
IL_00c0: nop
IL_00c1: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00c6: leave.s IL_00de
}
IL_00c8: ldarg.0
IL_00c9: ldc.i4.s -2
IL_00cb: dup
IL_00cc: stloc.0
IL_00cd: stfld "Program.VB$StateMachine_0_Test2.$State As Integer"
IL_00d2: ldarg.0
IL_00d3: ldflda "Program.VB$StateMachine_0_Test2.$Builder As System.Runtime.CompilerServices.AsyncVoidMethodBuilder"
IL_00d8: call "Sub System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"
IL_00dd: nop
IL_00de: ret
}
]]>)
End Sub
<Fact()>
Public Sub Simple_Generics()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Call (New BASE(Of Object).CLAZZ(Of String)()).F(Of Integer)(1).Wait(60000)
Console.Write("X2 ")
End Sub
End Module
Public Class BASE(Of T)
Public Class CLAZZ(Of U As T)
Public FX As T
Public Async Function F(Of V As Structure)(p As V) As Task(Of Integer)
Dim outer As U = Nothing
Console.Write("0 ")
Dim a = Async Function()
Dim result As String = outer.ToString & Me.FX.ToString
Dim x = Await f2()
Return result & p.ToString
End Function
Console.Write("1 ")
Return Await a()
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
End Function
End Class
End Class
</file>
</compilation>, useLatestFramework:=True)
c.VerifyIL("BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).MoveNext",
<![CDATA[
{
// Code size 242 (0xf2)
.maxstack 3
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of String) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0086
IL_000a: newobj "Sub BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of SM$V)..ctor()"
IL_000f: dup
IL_0010: ldarg.0
IL_0011: ldfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$VB$Me As BASE(Of T).CLAZZ(Of U)"
IL_0016: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of SM$V).$VB$Me As BASE(Of T).CLAZZ(Of U)"
IL_001b: dup
IL_001c: ldarg.0
IL_001d: ldfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$VB$Local_p As SM$V"
IL_0022: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of SM$V).$VB$Local_p As SM$V"
IL_0027: dup
IL_0028: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of SM$V).$VB$Local_outer As U"
IL_002d: initobj "U"
IL_0033: ldstr "0 "
IL_0038: call "Sub System.Console.Write(String)"
IL_003d: ldftn "Function BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of SM$V)._Lambda$__0() As System.Threading.Tasks.Task(Of String)"
IL_0043: newobj "Sub VB$AnonymousDelegate_0(Of System.Threading.Tasks.Task(Of String))..ctor(Object, System.IntPtr)"
IL_0048: ldstr "1 "
IL_004d: call "Sub System.Console.Write(String)"
IL_0052: callvirt "Function VB$AnonymousDelegate_0(Of System.Threading.Tasks.Task(Of String)).Invoke() As System.Threading.Tasks.Task(Of String)"
IL_0057: callvirt "Function System.Threading.Tasks.Task(Of String).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_005c: stloc.2
IL_005d: ldloca.s V_2
IL_005f: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).get_IsCompleted() As Boolean"
IL_0064: brtrue.s IL_00a2
IL_0066: ldarg.0
IL_0067: ldc.i4.0
IL_0068: dup
IL_0069: stloc.1
IL_006a: stfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$State As Integer"
IL_006f: ldarg.0
IL_0070: ldloc.2
IL_0071: stfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0076: ldarg.0
IL_0077: ldflda "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_007c: ldloca.s V_2
IL_007e: ldarg.0
IL_007f: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of String), BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V))(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of String), ByRef BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V))"
IL_0084: leave.s IL_00f1
IL_0086: ldarg.0
IL_0087: ldc.i4.m1
IL_0088: dup
IL_0089: stloc.1
IL_008a: stfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$State As Integer"
IL_008f: ldarg.0
IL_0090: ldfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_0095: stloc.2
IL_0096: ldarg.0
IL_0097: ldflda "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_009c: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00a2: ldloca.s V_2
IL_00a4: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of String).GetResult() As String"
IL_00a9: ldloca.s V_2
IL_00ab: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of String)"
IL_00b1: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(String) As Integer"
IL_00b6: stloc.0
IL_00b7: leave.s IL_00db
}
catch System.Exception
{
IL_00b9: dup
IL_00ba: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00bf: stloc.3
IL_00c0: ldarg.0
IL_00c1: ldc.i4.s -2
IL_00c3: stfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$State As Integer"
IL_00c8: ldarg.0
IL_00c9: ldflda "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00ce: ldloc.3
IL_00cf: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_00d4: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00d9: leave.s IL_00f1
}
IL_00db: ldarg.0
IL_00dc: ldc.i4.s -2
IL_00de: dup
IL_00df: stloc.1
IL_00e0: stfld "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$State As Integer"
IL_00e5: ldarg.0
IL_00e6: ldflda "BASE(Of T).CLAZZ(Of U).VB$StateMachine_2_F(Of SM$V).$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00eb: ldloc.0
IL_00ec: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_00f1: ret
}
]]>)
c.VerifyIL("BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.MoveNext", <![CDATA[
{
// Code size 273 (0x111)
.maxstack 3
.locals init (String V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse.s IL_0088
IL_000a: ldarg.0
IL_000b: ldarg.0
IL_000c: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0)"
IL_0011: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).$VB$Local_outer As U"
IL_0016: constrained. "U"
IL_001c: callvirt "Function Object.ToString() As String"
IL_0021: ldarg.0
IL_0022: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0)"
IL_0027: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).$VB$Me As BASE(Of T).CLAZZ(Of U)"
IL_002c: ldflda "BASE(Of T).CLAZZ(Of U).FX As T"
IL_0031: constrained. "T"
IL_0037: callvirt "Function Object.ToString() As String"
IL_003c: call "Function String.Concat(String, String) As String"
IL_0041: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As String"
IL_0046: ldarg.0
IL_0047: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0)"
IL_004c: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).$VB$Me As BASE(Of T).CLAZZ(Of U)"
IL_0051: call "Function BASE(Of T).CLAZZ(Of U).f2() As System.Threading.Tasks.Task(Of Integer)"
IL_0056: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_005b: stloc.2
IL_005c: ldloca.s V_2
IL_005e: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_0063: brtrue.s IL_00a4
IL_0065: ldarg.0
IL_0066: ldc.i4.0
IL_0067: dup
IL_0068: stloc.1
IL_0069: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$State As Integer"
IL_006e: ldarg.0
IL_006f: ldloc.2
IL_0070: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0075: ldarg.0
IL_0076: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_007b: ldloca.s V_2
IL_007d: ldarg.0
IL_007e: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0)"
IL_0083: leave IL_0110
IL_0088: ldarg.0
IL_0089: ldc.i4.m1
IL_008a: dup
IL_008b: stloc.1
IL_008c: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$State As Integer"
IL_0091: ldarg.0
IL_0092: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0097: stloc.2
IL_0098: ldarg.0
IL_0099: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_009e: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00a4: ldloca.s V_2
IL_00a6: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_00ab: ldloca.s V_2
IL_00ad: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00b3: pop
IL_00b4: ldarg.0
IL_00b5: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$ResumableLocal_result$0 As String"
IL_00ba: ldarg.0
IL_00bb: ldfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$VB$NonLocal__Closure$__2-0 As BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0)"
IL_00c0: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).$VB$Local_p As $CLS0"
IL_00c5: constrained. "$CLS0"
IL_00cb: callvirt "Function System.ValueType.ToString() As String"
IL_00d0: call "Function String.Concat(String, String) As String"
IL_00d5: stloc.0
IL_00d6: leave.s IL_00fa
}
catch System.Exception
{
IL_00d8: dup
IL_00d9: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_00de: stloc.3
IL_00df: ldarg.0
IL_00e0: ldc.i4.s -2
IL_00e2: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$State As Integer"
IL_00e7: ldarg.0
IL_00e8: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_00ed: ldloc.3
IL_00ee: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetException(System.Exception)"
IL_00f3: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_00f8: leave.s IL_0110
}
IL_00fa: ldarg.0
IL_00fb: ldc.i4.s -2
IL_00fd: dup
IL_00fe: stloc.1
IL_00ff: stfld "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$State As Integer"
IL_0104: ldarg.0
IL_0105: ldflda "BASE(Of T).CLAZZ(Of U)._Closure$__2-0(Of $CLS0).VB$StateMachine___Lambda$__0.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String)"
IL_010a: ldloc.0
IL_010b: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of String).SetResult(String)"
IL_0110: ret
}
]]>)
End Sub
<WorkItem(553894, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/553894")>
<Fact()>
Public Sub Simple_TaskOfT_EmitMetadataOnly()
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("X1 ")
Call (New CLAZZ()).F()
Console.Write("X2 ")
End Sub
End Module
Class CLAZZ
Public FX As Integer
Public Async Function F() As Task(Of Integer)
Dim outer As Integer = 123
Console.Write("0 ")
Return Await f2()
Console.Write("1 ")
End Function
Async Function f2() As Task(Of Integer)
Console.Write("2 ")
Await Task.Yield
Console.Write("3 ")
Return 123
End Function
End Class
</file>
</compilation>, references:=LatestVbReferences).VerifyDiagnostics()
Using stream As New MemoryStream()
Dim emitResult = compilation.Emit(stream, options:=New EmitOptions(metadataOnly:=True))
' This should not crash
End Using
End Sub
<Fact()>
Public Sub SpilledArrayAccessAndFieldAccess()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of Integer)
Dim s(1, 1) As S
s(0, 0).I = 1
s(0, 1).I = 0
s(1, 1).I = 10
Console.Write("2 ")
Return M(s(s(0, 0).I, s(0, 1).I + 1).I, Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 1
End Function
Public Function M(ByRef x As Integer, y As Integer) As Integer
Console.Write("5 ")
Return x + y
End Function
Public Structure S
Public I As Integer
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 11 1")
c.VerifyIL("Form1.VB$StateMachine_1_Test.MoveNext",
<![CDATA[
{
// Code size 369 (0x171)
.maxstack 4
.locals init (Integer V_0,
Integer V_1,
Form1.S(,) V_2, //s
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_3,
System.Exception V_4)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse IL_00e0
IL_000d: ldc.i4.2
IL_000e: ldc.i4.2
IL_000f: newobj "Form1.S(*,*)..ctor"
IL_0014: stloc.2
IL_0015: ldloc.2
IL_0016: ldc.i4.0
IL_0017: ldc.i4.0
IL_0018: call "Form1.S(*,*).Address"
IL_001d: ldc.i4.1
IL_001e: stfld "Form1.S.I As Integer"
IL_0023: ldloc.2
IL_0024: ldc.i4.0
IL_0025: ldc.i4.1
IL_0026: call "Form1.S(*,*).Address"
IL_002b: ldc.i4.0
IL_002c: stfld "Form1.S.I As Integer"
IL_0031: ldloc.2
IL_0032: ldc.i4.1
IL_0033: ldc.i4.1
IL_0034: call "Form1.S(*,*).Address"
IL_0039: ldc.i4.s 10
IL_003b: stfld "Form1.S.I As Integer"
IL_0040: ldstr "2 "
IL_0045: call "Sub System.Console.Write(String)"
IL_004a: ldarg.0
IL_004b: ldloc.2
IL_004c: stfld "Form1.VB$StateMachine_1_Test.$U1 As Form1.S(,)"
IL_0051: ldarg.0
IL_0052: ldloc.2
IL_0053: ldc.i4.0
IL_0054: ldc.i4.0
IL_0055: call "Form1.S(*,*).Address"
IL_005a: ldfld "Form1.S.I As Integer"
IL_005f: stfld "Form1.VB$StateMachine_1_Test.$U2 As Integer"
IL_0064: ldarg.0
IL_0065: ldloc.2
IL_0066: ldc.i4.0
IL_0067: ldc.i4.1
IL_0068: call "Form1.S(*,*).Address"
IL_006d: ldfld "Form1.S.I As Integer"
IL_0072: ldc.i4.1
IL_0073: add.ovf
IL_0074: stfld "Form1.VB$StateMachine_1_Test.$U3 As Integer"
IL_0079: ldarg.0
IL_007a: ldfld "Form1.VB$StateMachine_1_Test.$U1 As Form1.S(,)"
IL_007f: ldarg.0
IL_0080: ldfld "Form1.VB$StateMachine_1_Test.$U2 As Integer"
IL_0085: ldarg.0
IL_0086: ldfld "Form1.VB$StateMachine_1_Test.$U3 As Integer"
IL_008b: call "Form1.S(*,*).Get"
IL_0090: pop
IL_0091: ldarg.0
IL_0092: ldfld "Form1.VB$StateMachine_1_Test.$U1 As Form1.S(,)"
IL_0097: ldarg.0
IL_0098: ldfld "Form1.VB$StateMachine_1_Test.$U2 As Integer"
IL_009d: ldarg.0
IL_009e: ldfld "Form1.VB$StateMachine_1_Test.$U3 As Integer"
IL_00a3: call "Form1.S(*,*).Get"
IL_00a8: pop
IL_00a9: call "Function Form1.F() As System.Threading.Tasks.Task(Of Integer)"
IL_00ae: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00b3: stloc.3
IL_00b4: ldloca.s V_3
IL_00b6: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_00bb: brtrue.s IL_00fc
IL_00bd: ldarg.0
IL_00be: ldc.i4.0
IL_00bf: dup
IL_00c0: stloc.1
IL_00c1: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_00c6: ldarg.0
IL_00c7: ldloc.3
IL_00c8: stfld "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00cd: ldarg.0
IL_00ce: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00d3: ldloca.s V_3
IL_00d5: ldarg.0
IL_00d6: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), Form1.VB$StateMachine_1_Test)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef Form1.VB$StateMachine_1_Test)"
IL_00db: leave IL_0170
IL_00e0: ldarg.0
IL_00e1: ldc.i4.m1
IL_00e2: dup
IL_00e3: stloc.1
IL_00e4: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_00e9: ldarg.0
IL_00ea: ldfld "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00ef: stloc.3
IL_00f0: ldarg.0
IL_00f1: ldflda "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00f6: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00fc: ldarg.0
IL_00fd: ldfld "Form1.VB$StateMachine_1_Test.$U1 As Form1.S(,)"
IL_0102: ldarg.0
IL_0103: ldfld "Form1.VB$StateMachine_1_Test.$U2 As Integer"
IL_0108: ldarg.0
IL_0109: ldfld "Form1.VB$StateMachine_1_Test.$U3 As Integer"
IL_010e: call "Form1.S(*,*).Address"
IL_0113: ldflda "Form1.S.I As Integer"
IL_0118: ldloca.s V_3
IL_011a: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_011f: ldloca.s V_3
IL_0121: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0127: call "Function Form1.M(ByRef Integer, Integer) As Integer"
IL_012c: stloc.0
IL_012d: ldarg.0
IL_012e: ldnull
IL_012f: stfld "Form1.VB$StateMachine_1_Test.$U1 As Form1.S(,)"
IL_0134: leave.s IL_015a
}
catch System.Exception
{
IL_0136: dup
IL_0137: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_013c: stloc.s V_4
IL_013e: ldarg.0
IL_013f: ldc.i4.s -2
IL_0141: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_0146: ldarg.0
IL_0147: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_014c: ldloc.s V_4
IL_014e: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_0153: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0158: leave.s IL_0170
}
IL_015a: ldarg.0
IL_015b: ldc.i4.s -2
IL_015d: dup
IL_015e: stloc.1
IL_015f: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_0164: ldarg.0
IL_0165: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_016a: ldloc.0
IL_016b: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_0170: ret
}
]]>)
End Sub
<Fact()>
Public Sub HoistedArrayAccessAndFieldAccess()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of Integer)
Dim s(1, 1) As S
s(0, 0).I = 1
s(0, 1).I = 0
s(1, 1).I = 10
Console.Write("2 ")
Return M(s(s(0, 0).I, s(0, 1).I + 1).I, Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 1
End Function
Public Function M(ByRef x As Double, y As Integer) As Integer
Console.Write("5 ")
Return x + y
End Function
Public Structure S
Public I As Integer
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 11 1")
c.VerifyIL("Form1.VB$StateMachine_1_Test.MoveNext", <![CDATA[
{
// Code size 388 (0x184)
.maxstack 5
.locals init (Integer V_0,
Integer V_1,
System.Runtime.CompilerServices.TaskAwaiter(Of Integer) V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_0006: stloc.1
.try
{
IL_0007: ldloc.1
IL_0008: brfalse IL_00ea
IL_000d: ldarg.0
IL_000e: ldc.i4.2
IL_000f: ldc.i4.2
IL_0010: newobj "Form1.S(*,*)..ctor"
IL_0015: stfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_001a: ldarg.0
IL_001b: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0020: ldc.i4.0
IL_0021: ldc.i4.0
IL_0022: call "Form1.S(*,*).Address"
IL_0027: ldc.i4.1
IL_0028: stfld "Form1.S.I As Integer"
IL_002d: ldarg.0
IL_002e: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0033: ldc.i4.0
IL_0034: ldc.i4.1
IL_0035: call "Form1.S(*,*).Address"
IL_003a: ldc.i4.0
IL_003b: stfld "Form1.S.I As Integer"
IL_0040: ldarg.0
IL_0041: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0046: ldc.i4.1
IL_0047: ldc.i4.1
IL_0048: call "Form1.S(*,*).Address"
IL_004d: ldc.i4.s 10
IL_004f: stfld "Form1.S.I As Integer"
IL_0054: ldstr "2 "
IL_0059: call "Sub System.Console.Write(String)"
IL_005e: ldarg.0
IL_005f: ldarg.0
IL_0060: ldarg.0
IL_0061: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0066: ldc.i4.0
IL_0067: ldc.i4.0
IL_0068: call "Form1.S(*,*).Address"
IL_006d: ldfld "Form1.S.I As Integer"
IL_0072: stfld "Form1.VB$StateMachine_1_Test.$V1 As Integer"
IL_0077: ldarg.0
IL_0078: ldarg.0
IL_0079: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_007e: ldc.i4.0
IL_007f: ldc.i4.1
IL_0080: call "Form1.S(*,*).Address"
IL_0085: ldfld "Form1.S.I As Integer"
IL_008a: ldc.i4.1
IL_008b: add.ovf
IL_008c: stfld "Form1.VB$StateMachine_1_Test.$V2 As Integer"
IL_0091: ldarg.0
IL_0092: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0097: ldarg.0
IL_0098: ldfld "Form1.VB$StateMachine_1_Test.$V1 As Integer"
IL_009d: ldarg.0
IL_009e: ldfld "Form1.VB$StateMachine_1_Test.$V2 As Integer"
IL_00a3: call "Form1.S(*,*).Address"
IL_00a8: ldfld "Form1.S.I As Integer"
IL_00ad: conv.r8
IL_00ae: stfld "Form1.VB$StateMachine_1_Test.$S1 As Double"
IL_00b3: call "Function Form1.F() As System.Threading.Tasks.Task(Of Integer)"
IL_00b8: callvirt "Function System.Threading.Tasks.Task(Of Integer).GetAwaiter() As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00bd: stloc.2
IL_00be: ldloca.s V_2
IL_00c0: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).get_IsCompleted() As Boolean"
IL_00c5: brtrue.s IL_0106
IL_00c7: ldarg.0
IL_00c8: ldc.i4.0
IL_00c9: dup
IL_00ca: stloc.1
IL_00cb: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_00d0: ldarg.0
IL_00d1: ldloc.2
IL_00d2: stfld "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00d7: ldarg.0
IL_00d8: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_00dd: ldloca.s V_2
IL_00df: ldarg.0
IL_00e0: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).AwaitUnsafeOnCompleted(Of System.Runtime.CompilerServices.TaskAwaiter(Of Integer), Form1.VB$StateMachine_1_Test)(ByRef System.Runtime.CompilerServices.TaskAwaiter(Of Integer), ByRef Form1.VB$StateMachine_1_Test)"
IL_00e5: leave IL_0183
IL_00ea: ldarg.0
IL_00eb: ldc.i4.m1
IL_00ec: dup
IL_00ed: stloc.1
IL_00ee: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_00f3: ldarg.0
IL_00f4: ldfld "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_00f9: stloc.2
IL_00fa: ldarg.0
IL_00fb: ldflda "Form1.VB$StateMachine_1_Test.$A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0100: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_0106: ldarg.0
IL_0107: ldflda "Form1.VB$StateMachine_1_Test.$S1 As Double"
IL_010c: ldloca.s V_2
IL_010e: call "Function System.Runtime.CompilerServices.TaskAwaiter(Of Integer).GetResult() As Integer"
IL_0113: ldloca.s V_2
IL_0115: initobj "System.Runtime.CompilerServices.TaskAwaiter(Of Integer)"
IL_011b: call "Function Form1.M(ByRef Double, Integer) As Integer"
IL_0120: ldarg.0
IL_0121: ldfld "Form1.VB$StateMachine_1_Test.$VB$ResumableLocal_s$0 As Form1.S(,)"
IL_0126: ldarg.0
IL_0127: ldfld "Form1.VB$StateMachine_1_Test.$V1 As Integer"
IL_012c: ldarg.0
IL_012d: ldfld "Form1.VB$StateMachine_1_Test.$V2 As Integer"
IL_0132: call "Form1.S(*,*).Address"
IL_0137: ldarg.0
IL_0138: ldfld "Form1.VB$StateMachine_1_Test.$S1 As Double"
IL_013d: call "Function System.Math.Round(Double) As Double"
IL_0142: conv.ovf.i4
IL_0143: stfld "Form1.S.I As Integer"
IL_0148: stloc.0
IL_0149: leave.s IL_016d
}
catch System.Exception
{
IL_014b: dup
IL_014c: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"
IL_0151: stloc.3
IL_0152: ldarg.0
IL_0153: ldc.i4.s -2
IL_0155: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_015a: ldarg.0
IL_015b: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_0160: ldloc.3
IL_0161: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetException(System.Exception)"
IL_0166: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_016b: leave.s IL_0183
}
IL_016d: ldarg.0
IL_016e: ldc.i4.s -2
IL_0170: dup
IL_0171: stloc.1
IL_0172: stfld "Form1.VB$StateMachine_1_Test.$State As Integer"
IL_0177: ldarg.0
IL_0178: ldflda "Form1.VB$StateMachine_1_Test.$Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer)"
IL_017d: ldloc.0
IL_017e: call "Sub System.Runtime.CompilerServices.AsyncTaskMethodBuilder(Of Integer).SetResult(Integer)"
IL_0183: ret
}
]]>)
End Sub
<Fact()>
Public Sub CapturingMeOfStructureAsLValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Structure Form1
Shared Sub Main()
Console.Write("0 ")
Dim f As New Form1()
f.FLD = 1
Console.Write((f.Test().Result + f.FLD).ToString + " ")
Console.Write("1 ")
End Sub
Public FLD As Integer
Async Function Test() As Task(Of Integer)
Console.Write("2 ")
Dim result = M(Me, Await F()) + Me.FLD
Me.FLD = 100
Return result
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 1000
End Function
Public Function M(ByRef x As Form1, y As Integer) As Integer
Console.Write("5 ")
Dim result = x.FLD + y
x.FLD = 10
Return result
End Function
End Structure
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 1003 1")
End Sub
<Fact()>
Public Sub CapturingMeOfClassAsRValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class Form1
Shared Sub Main()
Console.Write("0 ")
Dim f As New Form1()
f.FLD = 1
Console.Write((f.Test().Result + f.FLD).ToString + " ")
Console.Write("1 ")
End Sub
Public FLD As Integer
Async Function Test() As Task(Of Integer)
Console.Write("2 ")
Dim result = M(Me, Await F()) + Me.FLD
Me.FLD = 100
Return result
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 1000
End Function
Public Function M(ByRef x As Form1, y As Integer) As Integer
Console.Write("5 ")
Dim result = x.FLD + y
x.FLD = 10
Return result
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 1111 1")
End Sub
<Fact()>
Public Sub MeMyClassMyBase()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class Form0
Public FLD As Integer = 1
Public Overridable Async Function F() As Task(Of Integer)
Console.Write("0 ")
Await Task.Yield
Console.Write("1 ")
Return 1000
End Function
End Class
Class Form1
Inherits Form0
Shared Sub Main()
Console.Write("2 ")
Dim f As New Form1()
f.FLD = 10000
Console.Write((f.Test().Result + f.FLD).ToString + " ")
Console.Write("3 ")
End Sub
Public Shadows FLD As Integer
Async Function Test() As Task(Of Integer)
Console.Write("4 ")
Dim result = M(Me, Await MyClass.F()) + MyBase.FLD + M(Me, Await MyBase.F()) + MyClass.FLD
Me.FLD = 100
Return result
End Function
Public Overrides Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 100000
End Function
Public Function M(ByRef x As Form1, y As Integer) As Integer
Console.Write("7 ")
Dim result = x.FLD + y
x.FLD = 10
Return result
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="2 4 5 6 7 0 1 7 111121 3")
End Sub
<Fact()>
Public Sub ArrayLengthAndInitialization()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of Integer)
Return Await Reflect((Await Reflect(Await F())).Length)
End Function
Public Async Function F() As Task(Of Integer())
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
End Function
Public Async Function Reflect(Of T)(p As T) As Task(Of T)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return p
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 4 5 6 5 6 10 1")
End Sub
<Fact()>
Public Sub UnaryOperator()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of Integer)
Return Await Reflect(-(Await Reflect(+Await F())))
End Function
Public Async Function F() As Task(Of S)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return New S() With {.F = 12345}
End Function
Public Async Function Reflect(Of T)(p As T) As Task(Of T)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return p
End Function
Structure S
Public F As Integer
Public Shared Operator +(s As S) As Integer
Return s.F
End Operator
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 4 5 6 5 6 -12345 1")
End Sub
<Fact()>
Public Sub BinaryOperator()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of Integer)
Return Await Reflect(1 + (Await Reflect(Await F() + 10000)))
End Function
Public Async Function F() As Task(Of S)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return New S() With {.F = 100}
End Function
Public Async Function Reflect(Of T)(p As T) As Task(Of T)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return p
End Function
Structure S
Public F As Integer
Public Shared Operator +(s As S, i As Integer) As Integer
Return s.F + i
End Operator
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 4 5 6 5 6 10101 1")
End Sub
<Fact()>
Public Sub BinarySortCircuitOperator()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Async Function A(Of T)(b As T, s As String) As Task(Of T)
Await Task.Yield
Console.Write(s)
Console.Write(" ")
Return b
End Function
Async Function Test() As Task
Do
Loop Until Await A(False, "1") OrElse Await A(True, "2") OrElse Await A(False, "3")
While Await A(True, "4") AndAlso Await A(False, "5") AndAlso Await A(True, "6")
End While
If If(Await A(False, "7"), Await A(False, "8"), Await A(True, "9")) Then
End If
Dim y = If(Await A(CType("", String), "10"), Await A("", "11"))
Dim x = If(Await A(CType(Nothing, String), "12"), Await A("", "13"))
End Function
Sub Main()
Test().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 4 5 7 9 10 12 13")
End Sub
<Fact()>
Public Sub BinaryAndTernaryConditional()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of String)
Return Await Reflect(
If(Await F(), Await Reflect(10000)).ToString() +
If(Await F() IsNot Nothing, Await Reflect(1), Await Reflect(2)).ToString())
End Function
Public Async Function F() As Task(Of Object)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 100
End Function
Public Async Function Reflect(Of T)(p As T) As Task(Of T)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return p
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 4 3 4 5 6 5 6 1001 1")
End Sub
<Fact()>
Public Sub TypeOfExpression()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test().Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test() As Task(Of String)
Return (Await Reflect(TypeOf (Await Reflect(Await F())) Is String)).ToString
End Function
Public Async Function F() As Task(Of Object)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return "STR"
End Function
Public Async Function Reflect(Of T)(p As T) As Task(Of T)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return p
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 4 5 6 5 6 True 1")
End Sub
<Fact()>
Public Sub CaptureParameterSimple()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test(100).Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test(p As Integer) As Task(Of Integer)
Console.Write("2 ")
Return M(p, Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 10
End Function
Public Function M(ByRef x As Integer, y As Integer) As Integer
Console.Write("5 ")
Return x + y
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 110 1")
End Sub
<Fact()>
Public Sub CaptureParameterInLValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test(New S() With {.I = 100}).Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test(p As S) As Task(Of Integer)
Console.Write("2 ")
Return M(p.I, Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 10
End Function
Public Function M(ByRef x As Integer, y As Integer) As Integer
Console.Write("5 ")
Return x + y
End Function
Structure S
Public I As Integer
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 110 1")
End Sub
<Fact()>
Public Sub CaptureByRefLocalWithParameterAndFieldAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(Test(New S() With {.I = 100}).Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function Test(p As S) As Task(Of Integer)
Console.Write("2 ")
Return M(p.I, Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("3 ")
Await Task.Yield
Console.Write("4 ")
Return 10
End Function
Public Function M(ByRef x As Double, y As Integer) As Integer
Console.Write("5 ")
Return x + y
End Function
Structure S
Public I As Integer
End Structure
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 3 4 5 110 1")
End Sub
<Fact()>
Public Sub CaptureByRefLocalWithMeMyBaseMyClassAndArrayAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class BASE
Public FLD As Integer = 4
Public Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 0
End Function
Public Function M(ByRef x As Double, y As Integer) As Integer
Console.Write("7 ")
Return x + y
End Function
End Class
Class Form1
Inherits BASE
Public Shadows FLD As Integer
Shared Sub Main()
Console.Write("0 ")
Console.Write((New Form1() With {.FLD = 1}).TestMe({770, 771, 772, 773, 774}).Result.ToString + " ")
Console.Write((New Form1() With {.FLD = 2}).TestMyBase({770, 771, 772, 773, 774}).Result.ToString + " ")
Console.Write((New Form1() With {.FLD = 3}).TestMyClass({770, 771, 772, 773, 774}).Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function TestMe(p As Integer()) As Task(Of Integer)
Console.Write("2 ")
Return M(p(Me.FLD), Await F())
End Function
Async Function TestMyBase(p As Integer()) As Task(Of Integer)
Console.Write("3 ")
Return M(p(MyBase.FLD), Await F())
End Function
Async Function TestMyClass(p As Integer()) As Task(Of Integer)
Console.Write("4 ")
Return M(p(MyClass.FLD), Await F())
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 5 6 7 771 3 5 6 7 774 4 5 6 7 773 1")
End Sub
<Fact()>
Public Sub CaptureByRefLocalWithLocalConstAndRValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Console.Write("0 ")
Console.Write(TestLocal({1111, 1, 10, 100, 1000}).Result.ToString + " ")
Console.Write(TestRValue({1111, 1, 10, 100, 1000}).Result.ToString + " ")
Console.Write(TestConst({1111, 1, 10, 100, 1000}).Result.ToString + " ")
Console.Write("1 ")
End Sub
Async Function TestLocal(p As Integer()) As Task(Of Integer)
Console.Write("2 ")
Dim loc As Integer = 1
Return M(p(loc), Await F())
End Function
Async Function TestRValue(p As Integer()) As Task(Of Integer)
Console.Write("3 ")
Dim loc As Integer = 1
Return M(p(1 + loc), Await F())
End Function
Async Function TestConst(p As Integer()) As Task(Of Integer)
Console.Write("4 ")
Return M(p(3), Await F())
End Function
Public Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 10000
End Function
Public Function M(ByRef x As Double, y As Integer) As Integer
Console.Write("7 ")
Return x + y
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 2 5 6 7 10001 3 5 6 7 10010 4 5 6 7 10100 1")
End Sub
<Fact()>
Public Sub Spilling_ExceptionInArrayAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("0 ")
Test(1).Wait(60000)
Console.Write("1 ")
Test(2).Wait(60000)
Console.Write("2 ")
Catch ex As AggregateException
Console.Write("EXC(" + ex.InnerExceptions(0).Message + ")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Async Function Test(p As Integer) As Task
Console.Write("3 ")
Dim a(1) As Integer
M(a(p), Await F())
Console.Write("4 ")
Console.Write(a(p).ToString() + " ")
End Function
Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 100
End Function
Public Sub M(ByRef x As Integer, y As Integer)
Console.Write("7 ")
x += 10000
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 5 6 7 4 10000 1 3 EXC(Index was outside the bounds of the array.)")
End Sub
<Fact()>
Public Sub Spilling_ExceptionInFieldAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main(args As String())
Test().Wait(60000)
End Sub
Async Function Test() As Task
Dim b As Box(Of String) = Nothing
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("1 ")
M(b.field, g(), Await t())
Catch ex As NullReferenceException
Console.Write("EXC(")
Console.Write(ex.Message)
Console.Write(")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Function
Function g() As Integer
Console.Write("!!ERROR!! ")
Return 1
End Function
Sub M(ByRef s As String, i As Integer, j As Integer)
Console.Write("3 ")
End Sub
Async Function t() As Task(Of Integer)
Console.Write("!!ERROR!! ")
Await Task.Yield()
Return 1
End Function
Class Box(Of T)
Public field As T
End Class
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 EXC(Object reference not set to an instance of an object.)")
End Sub
<Fact()>
Public Sub Capture_ExceptionInArrayAccess()
Dim source = <compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("0 ")
Test(1).Wait(60000)
Console.Write("1 ")
Test(2).Wait(60000)
Console.Write("2 ")
Catch ex As AggregateException
Console.Write("EXC(" + ex.InnerExceptions(0).Message + ")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Async Function Test(p As Integer) As Task
Console.Write("3 ")
Dim a(1) As Integer
M(a(p), Await F())
Console.Write("4 ")
Console.Write(a(p).ToString() + " ")
End Function
Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 100
End Function
Public Sub M(ByRef x As Double, y As Integer)
Console.Write("7 ")
x += 10000
End Sub
End Module
</file>
</compilation>
CompileAndVerify(source, useLatestFramework:=True, options:=TestOptions.ReleaseExe, expectedOutput:="0 3 5 6 7 4 10000 1 3 EXC(Index was outside the bounds of the array.)")
CompileAndVerify(source, useLatestFramework:=True, options:=TestOptions.DebugExe, expectedOutput:="0 3 5 6 7 4 10000 1 3 EXC(Index was outside the bounds of the array.)")
End Sub
<Fact()>
Public Sub Capture_ExceptionInFieldAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main(args As String())
Test().Wait(60000)
End Sub
Async Function Test() As Task
Dim b As Box(Of String) = Nothing
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("1 ")
M(b.field, g(), Await t())
Catch ex As NullReferenceException
Console.Write("EXC(")
Console.Write(ex.Message)
Console.Write(")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Function
Function g() As Integer
Console.Write("!!ERROR!! ")
Return 1
End Function
Sub M(ByRef s As Double, i As Integer, j As Integer)
Console.Write("3 ")
End Sub
Async Function t() As Task(Of Integer)
Console.Write("!!ERROR!! ")
Await Task.Yield()
Return 1
End Function
Class Box(Of T)
Public field As T
End Class
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 EXC(Object reference not set to an instance of an object.)")
End Sub
<Fact()>
Public Sub Spilling_ExceptionInArrayAccess2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("0 ")
Test({10, 20}, 1, 0).Wait(60000)
Console.Write("1 ")
Test({10, 20}, 2, 1).Wait(60000)
Console.Write("2 ")
Catch ex As AggregateException
Console.Write("EXC(" + ex.InnerExceptions(0).Message + ")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Async Function Test(a() As Integer, p1 As Integer, p2 As Integer) As Task
Console.Write("3 ")
M(a(INDX(p1)), a(INDX(p2)), Await F())
Console.Write("4 ")
End Function
Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 100
End Function
Public Sub M(ByRef x As Integer, ByRef y As Integer, z As Integer)
Console.Write("7 ")
x += 10000
y += 100
Console.Write(x.ToString() + " ")
Console.Write(y.ToString() + " ")
End Sub
Function INDX(i As Integer) As Integer
Console.Write("8 ")
Return i
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 8 8 5 6 7 10020 110 4 1 3 8 EXC(Index was outside the bounds of the array.)")
End Sub
<Fact()>
Public Sub Capture_ExceptionInArrayAccess2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Form1
Sub Main()
Dim saveUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture
System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture
Try
Console.Write("0 ")
Test({10, 20}, 1, 0).Wait(60000)
Console.Write("1 ")
Test({10, 20}, 2, 1).Wait(60000)
Console.Write("2 ")
Catch ex As AggregateException
Console.Write("EXC(" + ex.InnerExceptions(0).Message + ")")
Finally
System.Threading.Thread.CurrentThread.CurrentUICulture = saveUICulture
End Try
End Sub
Async Function Test(a() As Integer, p1 As Integer, p2 As Integer) As Task
Console.Write("3 ")
M(a(INDX(p1)), a(INDX(p2)), Await F())
Console.Write("4 ")
End Function
Async Function F() As Task(Of Integer)
Console.Write("5 ")
Await Task.Yield
Console.Write("6 ")
Return 100
End Function
Public Sub M(ByRef x As Double, ByRef y As Double, z As Integer)
Console.Write("7 ")
x += 10000
y += 100
Console.Write(x.ToString() + " ")
Console.Write(y.ToString() + " ")
End Sub
Function INDX(i As Integer) As Integer
Console.Write("8 ")
Return i
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0 3 8 8 5 6 7 10020 110 4 1 3 8 EXC(Index was outside the bounds of the array.)")
End Sub
<Fact()>
Public Sub Imported_VoidReturningAsync()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Dim i As Integer = 0
Public Async Sub F(handle As AutoResetEvent)
Await Task.Factory.StartNew(Sub()
Form1.i += 1
End Sub)
handle.Set()
End Sub
Public Sub Main()
Dim handle As New AutoResetEvent(False)
F(handle)
handle.WaitOne(1000)
Console.WriteLine(i)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1")
End Sub
<Fact,
WorkItem(94940, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems#_a=edit&id=94940"),
WorkItem(785170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/785170")>
Public Sub Imported_AsyncWithEH()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Dim awaitCount As Integer = 0
Dim finallyCount As Integer = 0
Sub LogAwait()
awaitCount += 1
End Sub
Sub LogException()
finallyCount += 1
End Sub
Public Async Sub F(handle As AutoResetEvent)
Await Task.Factory.StartNew(AddressOf LogAwait)
Try
Await Task.Factory.StartNew(AddressOf LogAwait)
Try
Await Task.Factory.StartNew(AddressOf LogAwait)
Try
Await Task.Factory.StartNew(AddressOf LogAwait)
Throw New Exception()
Catch ex As Exception
Finally
LogException()
End Try
Await Task.Factory.StartNew(AddressOf LogAwait)
Throw New Exception()
Catch ex As Exception
Finally
LogException()
End Try
Await Task.Factory.StartNew(AddressOf LogAwait)
Throw New Exception()
Catch ex As Exception
Finally
LogException()
End Try
Await Task.Factory.StartNew(AddressOf LogAwait)
handle.Set()
End Sub
Public Sub Main2(i As Integer)
awaitCount = 0
finallyCount = 0
Dim handle As New AutoResetEvent(False)
F(handle)
Dim completed = handle.WaitOne(4000)
If completed Then
If Not (awaitCount = 7 And finallyCount = 3) Then
Throw New Exception("failed at " & i)
End If
Else
Throw New Exception("did not complete in time: " & i)
End If
End Sub
Public Sub Main()
For i As Integer = 0 To 2000
Main2(i)
Next
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="")
End Sub
<Fact()>
Public Sub Imported_TaskReturningAsync()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Dim i As Integer = 0
Public Async Sub F(handle As AutoResetEvent)
Await Task.Factory.StartNew(Sub()
i = 42
End Sub)
handle.Set()
End Sub
Public Sub Main()
Dim handle As New AutoResetEvent(False)
F(handle)
handle.WaitOne(1000)
Console.Write(i)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_GenericTaskReturningAsync()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F() As Task(Of String)
Return Await Task.Factory.StartNew(Function()
Return "O brave new world..."
End Function)
End Function
Public Sub Main()
Console.Write(F().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="O brave new world...")
End Sub
<Fact()>
Public Sub Imported_AsyncWithLocals()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function()
Return x
End Function)
End Function
Public Async Function G(x As Integer) As Task(Of Integer)
Dim c As Integer = 0
Await F(x)
c += x
Await F(x)
c += x
Return c
End Function
Public Sub Main()
Console.Write(G(21).Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithParam()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function G(x As Integer) As Task(Of Integer)
x = 21 + Await Task.Factory.StartNew(Function()
Return x
End Function)
Return 21 + Await Task.Factory.StartNew(Function() x)
End Function
Public Sub Main()
Console.Write(G(0).Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AwaitInExpr()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F() As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() 21)
End Function
Public Async Function G() As Task(Of Integer)
Dim c As Integer = 0
c = (Await f()) + 21
Return c
End Function
Public Sub Main()
Console.Write(G().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithParamsAndLocals_Hoisted()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G(x As Integer) As Task(Of Integer)
Dim c As Integer = 0
c = (Await F(x)) + 21
Return c
End Function
Public Sub Main()
Console.Write(G(21).Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithParamsAndLocals_DoubleAwait_Spilling()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G(x As Integer) As Task(Of Integer)
Dim c As Integer = 0
c = (Await F(x)) + c
c = (Await F(x)) + c
Return c
End Function
Public Sub Main()
Console.Write(G(21).Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithDynamic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F(x As Object) As Task(Of Integer)
Return Await x
End Function
Public Sub Main()
Console.Write(Task.Factory.StartNew(Function() 42).Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithThisRef()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class C
Public x As Integer = 42
Public Async Function F() As Task(Of Integer)
Dim c = Me.x
Return Await Task.Factory.StartNew(Function() c)
End Function
End Class
Module Form1
Sub Main()
Console.WriteLine(New C().F().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithBaseRef()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class B
Protected x As Integer = 42
End Class
Class C
Inherits B
Public Async Function F() As Task(Of Integer)
Dim c = MyBase.x
Return Await Task.Factory.StartNew(Function() c)
End Function
End Class
Module Form1
Sub Main()
Console.WriteLine(New C().F().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_AsyncWithException1()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Async Function F() As Task(Of Integer)
Throw New Exception()
End Function
Async Function G() As Task(Of Integer)
Try
Return Await F()
Catch ex As Exception
Return -1
End Try
End Function
Sub Main()
Console.WriteLine(G().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="-1")
End Sub
<Fact()>
Public Sub Imported_AsyncWithException2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Async Function F() As Task(Of Integer)
Throw New Exception()
End Function
Async Function H() As Task(Of Integer)
Return Await F()
End Function
Sub Main()
Dim t = H()
Try
t.Wait(60000)
Catch ex As AggregateException
Console.WriteLine("exception")
End Try
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="exception")
End Sub
<Fact()>
Public Sub Imported_Conformance_Awaiting_Methods_Generic01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Runtime.CompilerServices
Public Class MyTask(Of T)
Public Function GetAwaiter() As MyTaskAwaiter(Of T)
Return New MyTaskAwaiter(Of T)()
End Function
Public Async Function Run(Of U As {MyTask(Of Integer), New})(uu As U) As Task
Dim tests = 0
tests += 1
Dim rez = Await uu
If rez = 0 Then
Form1.Count += 1
End If
Result = Form1.Count - tests
End Function
End Class
Public Class MyTaskAwaiter(Of T)
Implements INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As T
Return Nothing
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call New MyTask(Of Integer)().Run(Of MyTask(Of Integer))(New MyTask(Of Integer)()).Wait(60000)
Console.WriteLine(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Conformance_Awaiting_Methods_Method01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Interface IExplicit
Function Method(Optional x As Integer = 4)
End Interface
Class C1
Implements IExplicit
Private Function Method(Optional x As Integer = 4) As Object Implements IExplicit.Method
Return Task.Run(Async Function()
Await Task.Yield
form1.Count += 1
End Function)
End Function
End Class
Class TestCase
Public Async Function Run() As Task
Dim tests = 0
tests += 1
Dim c As New C1()
Dim e = DirectCast(c, IExplicit)
Await e.Method()
Result = Form1.Count - tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call (New TestCase()).Run().Wait(60000)
Console.WriteLine(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_DoFinallyBodies()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public finally_count As Integer = 0
Async Function F() As Task
Try
Await Task.Factory.StartNew(Sub()
End Sub)
Finally
finally_count += 1
End Try
End Function
Sub Main()
F().Wait(60000)
Console.WriteLine(finally_count)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1")
End Sub
<Fact()>
Public Sub Imported_Conformance_Awaiting_Methods_Parameter003()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Shared Count = 0
Public Shared Function Goo(Of T)(tt As T) As T
Return tt
End Function
Public Shared Async Function Bar(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Shared Async Function Run() As Task
Dim x1 = Goo(Await Bar(4))
Dim t = Bar(5)
Dim x2 = Goo(Await t)
If x1 <> 4 Then
Count += 1
End If
If x2 <> 5 Then
Count += 1
End If
End Function
End Class
Module Form1
Sub Main()
TestCase.Run().Wait(60000)
Console.WriteLine(TestCase.Count)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Conformance_Awaiting_Methods_Method05()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class C
Public Status As Integer
End Class
Interface IImplicit
Function Method(Of T As Task(Of C))(ParamArray d() As Decimal) As T
End Interface
Class Impl
Implements IImplicit
Public Function Method(Of T As Task(Of C))(ParamArray d() As Decimal) As T Implements IImplicit.Method
Return Task.Run(Async Function()
Await Task.Yield
Count += 1
Return New C() With {.Status = 1}
End Function)
End Function
End Class
Class TestCase
Public Async Function Run() As Task
Dim tests = 0
Dim i As New Impl()
tests += 1
Await i.Method(Of Task(Of C))(3, 4)
Result = Count - tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call (New TestCase()).Run().Wait(60000)
Console.WriteLine(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Conformance_Awaiting_Methods_Accessible010()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase : Inherits Test
Public Shared Count = 0
Public Shared Async Function Run() As Task
Dim x = Await Test.GetValue(Of Integer)(1)
If Not (x = 1) Then
Count += 1
End If
End Function
End Class
Class Test
Protected Shared Async Function GetValue(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.WriteLine(TestCase.Count)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_NestedUnary()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F() As Task(Of Integer)
Return 1
End Function
Public Async Function G1() As Task(Of Integer)
Return -(Await F())
End Function
Public Async Function G2() As Task(Of Integer)
Return -(-(Await F()))
End Function
Public Async Function G3() As Task(Of Integer)
Return -(-(-(Await F())))
End Function
Public Sub WaitAndPrint(t As Task(Of Integer))
t.Wait(60000)
Console.Write(t.Result)
Console.Write(" ")
End Sub
Sub Main()
WaitAndPrint(G1())
WaitAndPrint(G2())
WaitAndPrint(G3())
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="-1 1 -1")
End Sub
<Fact()>
Public Sub Imported_SpillCall()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Sub Printer(ParamArray a() As Integer)
For Each x In a
Console.Write(" ")
Console.Write(x)
Next
End Sub
Public Function Get_(x As Integer) As Integer
Console.Write(" > " + x.ToString)
Return x
End Function
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G() As Task
Printer(Get_(111), Get_(222), Get_(333), Await F(Get_(444)), Get_(555))
End Function
Sub Main()
G().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="> 111 > 222 > 333 > 444 > 555 111 222 333 444 555")
End Sub
<Fact()>
Public Sub Imported_SpillCall2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Sub Printer(ParamArray a() As Integer)
For Each x In a
Console.Write(" ")
Console.Write(x)
Next
End Sub
Public Function Get_(x As Integer) As Integer
Console.Write(" > " + x.ToString)
Return x
End Function
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G() As Task
Printer(Get_(111), Await F(Get_(222)), Get_(333), Await F(Get_(444)), Get_(555))
End Function
Sub Main()
G().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="> 111 > 222 > 333 > 444 > 555 111 222 333 444 555")
End Sub
<Fact()>
Public Sub Imported_SpillCall3()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Sub Printer(ParamArray a() As Integer)
For Each x In a
Console.Write(" ")
Console.Write(x)
Next
End Sub
Public Function Get_(x As Integer) As Integer
Console.Write(" > " + x.ToString)
Return x
End Function
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G() As Task
Printer(1, Await F(2), 3, await F(await F(await F(await F(4)))), Await F(5), 6)
End Function
Sub Main()
G().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3 4 5 6")
End Sub
<Fact()>
Public Sub Imported_SpillCall4()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Sub Printer(ParamArray a() As Integer)
For Each x In a
Console.Write(" ")
Console.Write(x)
Next
End Sub
Public Async Function F(x As Integer) As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() x)
End Function
Public Async Function G() As Task
Printer(1, Await F(Await F(2)))
End Function
Sub Main()
G().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2")
End Sub
<Fact()>
Public Sub Imported_Array01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run(Of T As Structure)(tt As t) as Task
Dim tests = 0
tests += 1
Console.Write(tests)
Console.Write(" ")
Dim arr(Await GetVal(3)) As Integer
If arr.Length = 4 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
Dim arr2(Await GetVal(3), Await GetVal(3)) As Decimal
If arr2.Rank = 2 AndAlso arr2.Length = 16 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
arr2 = New Decimal(3, Await GetVal(3)) {}
If arr2.Rank = 2 AndAlso arr2.Length = 16 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
ReDim arr2(4, Await GetVal(4))
If arr2.Rank = 2 AndAlso arr2.Length = 25 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
ReDim Preserve arr2(4, Await GetVal(2))
If arr2.Rank = 2 AndAlso arr2.Length = 15 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
arr2 = New Decimal(Await GetVal(3), 3) {}
If arr2.Rank = 2 AndAlso arr2.Length = 16 Then
Count += 1
End If
tests += 1
Console.Write(tests)
Console.Write(" ")
Dim arr3 As Decimal?()() = New Decimal?(Await GetVal(3))() {}
If arr3.Rank = 1 AndAlso arr3.Length = 4 Then
Count += 1
End If
Result = Count - tests
End Function
End Class
Module Form1
Public Result = -1
Public Count = 0
Sub Main()
Call New TestCase().Run(6).Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3 4 5 6 7 0")
End Sub
<Fact()>
Public Sub Imported_Array02()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run(Of T As Structure)(tt As t) As Task
Dim tests = 0
tests += 1
Dim arr(Await GetVal(3)) As Integer
If arr.Length = 4 Then
Count += 1
End If
tests += 1
arr(0) = Await GetVal(4)
If arr(0) = 4 Then
Count += 1
End If
tests += 1
arr(0) += Await GetVal(4)
If arr(0) = 8 Then
Count += 1
End If
tests += 1
arr(1) += Await (GetVal(arr(0)))
If arr(1) = 8 Then
Count += 1
End If
tests += 1
arr(1) += Await (GetVal(arr(Await GetVal(0))))
If arr(1) = 16 Then
Count += 1
End If
Result = Count - tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call New TestCase().Run(6).Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Array03()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run(Of T As Structure)(tt As t) as Task
Dim tests = 0
tests += 1
Dim arr(Await GetVal(3), Await GetVal(3)) As Integer
arr(0, 0) = Await GetVal(4)
If arr(0, Await (GetVal(0))) = 4 Then
Count += 1
End If
tests += 1
arr(0, 0) += Await GetVal(4)
If arr(0, Await (GetVal(0))) = 8 Then
Count += 1
End If
tests += 1
arr(1, 1) += Await (GetVal(arr(0, 0)))
If arr(1, 1) = 8 Then
Count += 1
End If
tests += 1
arr(1, 1) += Await (GetVal(arr(0, Await GetVal(0))))
If arr(1, 1) = 16 Then
Count += 1
End If
Result = Count - tests
End Function
End Class
Module Form1
Public Result = -1
Public Count = 0
Sub Main()
Call New TestCase().Run(6).Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Array04()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure MyStruct(Of T)
Public Property TT As T
Default Public Property This(index As T) As T
Get
Return index
End Get
Set(value As T)
TT = value
End Set
End Property
End Structure
Structure TestCase
Public Async Function Run() As Task
Dim ms As New MyStruct(Of Integer)()
Dim x = ms(index:=Await Goo())
Console.Write(x + 100)
End Function
Public Async Function Goo() As Task(Of Integer)
Await Task.Yield
Return 10
End Function
End Structure
Module Form1
Sub Main()
Call New TestCase().Run().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="110")
End Sub
<Fact()>
Public Sub Imported_ArrayAssign()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public arr(3) As Integer
Async Function Run() As Task
arr(0) = Await Task.Factory.StartNew(Function() 42)
End Function
Sub Main()
Run().Wait(60000)
Console.Write(arr(0))
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_CaptureThis()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function Run() As Task(Of Integer)
Return Await Goo()
End Function
Public Async Function Goo() As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() 42)
End Function
End Class
Module Form1
Sub Main()
Console.Write(New TestCase().Run().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_SpillArrayLocal()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run(Of t As Structure)(tt As t) As Task
Dim arr() As Integer = {-1, 42}
Dim tests = 0
tests += 1
Dim t1 = arr(Await GetVal(1))
If t1 = 42 Then
Count += 1
End If
Result = Count - tests
End Function
End Class
Module Form1
Public Result = -1
Public Count = 0
Sub Main()
Call New TestCase().Run(6).Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_SpillArrayCompoundAssignmentLValue()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public arr() As Integer
Async Function Run() As Task
arr = {1}
arr(0) += Await Task.Factory.StartNew(Function() 41)
End Function
Sub Main()
Call Run().Wait(60000)
Console.Write(arr(0))
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_SpillArrayCompoundAssignmentLValueAwait()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public arr() As Integer
Async Function Run() As Task
arr = {1}
arr(Await Task.Factory.StartNew(Function() 0)) += Await Task.Factory.StartNew(Function() 41)
End Function
Sub Main()
Call Run().Wait(60000)
Console.Write(arr(0))
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_SpillArrayCompoundAssignmentLValueAwait2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure S1
Public X As Integer
End Structure
Structure S2
Public S As S1
End Structure
Module Form1
Public arr() As S2
Async Function Run() As Task(Of Integer)
arr = {New S2() With {.S = New S1() With {.X = 1}}}
arr(Await Task.Factory.StartNew(Function() 0)).S.X += Await Task.Factory.StartNew(Function() 41)
Return arr(Await Task.Factory.StartNew(Function() 0)).S.X
End Function
Sub Main()
Console.Write(Run().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_DoubleSpillArrayCompoundAssignment()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure S1
Public X As Integer
End Structure
Structure S2
Public S As S1
End Structure
Module Form1
Public arr() As S2
Async Function Run() As Task(Of Integer)
arr = {New S2() With {.S = New S1() With {.X = 1}}}
arr(Await Task.Factory.StartNew(Function() 0)).S.X +=
arr((Await Task.Factory.StartNew(Async Function()
Return Await Task.Factory.StartNew(Function() 1)
End Function)).Result - 1).S.X +
Await Task.Factory.StartNew(Function() 40)
Return arr(Await Task.Factory.StartNew(Function() 0)).S.X
End Function
Sub Main()
Console.Write(Run().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_Array05()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run() As Task
Dim tests = 0
tests += 1
Dim arr1()() As Integer =
New Integer()() {
New Integer() {Await GetVal(2), Await GetVal(3)},
New Integer() {4, Await GetVal(5), Await GetVal(6)}
}
If arr1(0)(1) = 3 AndAlso arr1(1)(1) = 5 AndAlso arr1(1)(2) = 6 Then
Count += 1
End If
tests += 1
Dim arr2()() As Integer =
New Integer()() {
New Integer() {Await GetVal(2), Await GetVal(3)},
Await Goo()
}
If arr2(0)(1) = 3 AndAlso arr2(1)(1) = 2 Then
Count += 1
End If
Result = Count - tests
End Function
Public Async Function Goo() As Task(Of Integer())
Await Task.Yield
Return {1, 2, 3}
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Array06()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run() As Task
Dim tests = 0
tests += 1
Dim arr1(,) As Integer =
{
{Await GetVal(2), Await GetVal(3)},
{Await GetVal(5), Await GetVal(6)}
}
If arr1(0, 1) = 3 AndAlso arr1(1, 0) = 5 AndAlso arr1(1, 1) = 6 Then
Count += 1
End If
tests += 1
Dim arr2(,) As Integer =
{
{Await GetVal(2), 3},
{4, Await GetVal(5)}
}
If arr2(0, 1) = 3 AndAlso arr2(1, 1) = 5 Then
Count += 1
End If
Result = Count - tests
End Function
Public Async Function Goo() As Task(Of Integer())
Await Task.Yield
Return {1, 2, 3}
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Array07()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run() As Task
Dim tests = 0
tests += 1
Dim arr1()() As Integer =
New Integer()() {
New Integer() {Await GetVal(2), Await Task.Run(Of Integer)(Async Function()
Await Task.Yield
Return 3
End Function)},
New Integer() {Await GetVal(5), 4, Await Task.Run(Of Integer)(Async Function()
Await Task.Yield
Return 6
End Function)}
}
If arr1(0)(1) = 3 AndAlso arr1(1)(1) = 4 AndAlso arr1(1)(2) = 6 Then
Count += 1
End If
tests += 1
Dim arr2()() As Integer =
New Integer()() {
New Integer() {Await GetVal(2), 3},
Await Goo()
}
If arr2(0)(1) = 3 AndAlso arr2(1)(1) = 2 Then
Count += 1
End If
Result = Count - tests
End Function
Public Async Function Goo() As Task(Of Integer())
Await Task.Yield
Return {1, 2, 3}
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
Private Function GetFieldSignatures(type As NamedTypeSymbol) As String()
Return (From member In type.GetMembers()
Where member.Kind = SymbolKind.Field
Select member.ToDisplayString()).ToArray()
End Function
Private Function ArrayToSortedString(Of T)(arr() As T) As String
Array.Sort(arr)
Dim builder As New System.Text.StringBuilder()
For Each value In arr
builder.AppendLine(value.ToString)
Next
Return builder.ToString()
End Function
Private Sub CheckFields(m As ModuleSymbol, typeName As String, methodName As String, expected As String)
Dim TestCaseClass = m.ContainingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)(typeName)
For Each member In TestCaseClass.GetTypeMembers()
If member.Name.IndexOf(methodName, StringComparison.Ordinal) >= 0 Then
Assert.Equal(expected, ArrayToSortedString(GetFieldSignatures(member)))
Return
End If
Next
Assert.True(False)
End Sub
Private Sub CheckFields(m As ModuleSymbol, typeName As String, methodName As String, expected() As String)
CheckFields(m, typeName, methodName, ArrayToSortedString(expected))
End Sub
<Fact()>
Public Sub Imported_ReuseFields()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Shared Sub F1(x As Integer, y As Integer)
Console.Write(x)
Console.Write(" ")
End Sub
Shared Async Function F2() As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() 42)
End Function
Public Shared Async Function Run() As task
Dim x = 1
F1(x, Await F2())
Dim y = 2
F1(y, Await F2())
Dim z = 3
F1(z, Await F2())
End Function
End Class
Module Form1
Sub Main()
TestCase.Run().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3",
symbolValidator:=Sub(m)
CheckFields(m, "TestCase", "Run",
{
"Friend $A0 As System.Runtime.CompilerServices.TaskAwaiter(Of Integer)",
"Friend $U1 As Integer",
"Public $Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"Public $State As Integer"
})
End Sub)
End Sub
<Fact()>
Public Sub AllParametersAreToBeCaptured()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class CLS
Async Function F1(x As String, y As Integer) as Task
End Function
End Class
Module Form1
Sub Main()
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="",
symbolValidator:=Sub(m)
CheckFields(m, "CLS", "F1",
{
"Friend $VB$Local_x As String",
"Friend $VB$Local_y As Integer",
"Friend $VB$Me As CLS",
"Public $Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"Public $State As Integer"
})
End Sub)
End Sub
<Fact()>
Public Sub Imported_NestedExpressionInArrayInitializer()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function Run() As Task(Of Integer(,))
Return New Integer(,) {{1, 2, 21 + (Await Task.Factory.StartNew(Function() 21))}}
End Function
Sub Main()
For Each i In Run().Result
Console.Write(i)
Console.Write(" ")
Next
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 42")
End Sub
<Fact()>
Public Sub Imported_Basic02()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Shared test As Integer = 0
Shared count As Integer = 0
Shared Sub F1(x As Integer, y As Integer)
Console.Write(x)
Console.Write(" ")
End Sub
Shared Async Function F2() As Task(Of Integer)
Return Await Task.Factory.StartNew(Function() 42)
End Function
Public Shared Async Function Run() As task
test += 1
Dim f = Await Bar()
Dim x = f(1)
If Not x.Equals("1") Then
count -= 1
End If
Result = test - count
End Function
Shared Async Function Bar() As Task(Of Converter(Of Integer, Object))
count += 1
Await Task.Yield
Return Function(p1 As Integer)
Return p1.ToString()
End Function
End Function
End Class
Module Form1
Public Result As Integer = -1
Sub Main()
Call TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Argument03()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Shared sb As New System.Text.StringBuilder()
Public Async Function Run() As Task
Bar(One(), Await Two())
If sb.ToString() = "OneTwo" Then
Result = 0
End If
End Function
Function One() As Integer
sb.Append("One")
Return 1
End Function
Async Function Two() As Task(Of Integer)
Await Task.Yield
sb.Append("Two")
Return 2
End Function
Sub Bar(ParamArray a() As Object)
For Each x In a
Console.Write(x.ToString())
Console.Write(" ")
Next
End Sub
End Class
Module Form1
Public Result As Integer = -1
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 0")
End Sub
<Fact()>
Public Sub Imported_ObjectInit02()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections
Imports System.Collections.Generic
Structure TestCase
Implements IEnumerable
Public X As Integer
Public Async Function Run() As Task
Dim test = 0
Dim count = 0
test += 1
Dim x = New TestCase With {.X = Await Bar()}
If x.X = 1 Then
count += 1
End If
Result = test - count
End Function
Async Function Bar() As Task(Of Integer)
Await Task.Yield
Return 1
End Function
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New Exception()
End Function
End Structure
Module Form1
Public Result As Integer = -1
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Generic01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Shared test As Integer = 0
Shared count As Integer = 0
Public Async Function Run() As Task
test += 1
Qux(Async Function()
Return 1
End Function)
Await Task.Yield
Result = test - count
End Function
Shared Async Sub Qux(Of T)(x As Func(Of Task(Of T)))
Dim y = Await x()
If DirectCast(DirectCast(y, Object), Integer) = 1 Then
count += 1
End If
End Sub
End Class
Module Form1
Public Result As Integer = -1
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Ref01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class BaseTestCase
Public Sub GooRef(ByRef d As Decimal, x As Integer, ByRef od As Decimal)
od = d
d += 1
End Sub
Public Async Function GetVal(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
End Class
Class TestCase : Inherits BaseTestCase
Public Async Function Run() As Task
Dim tests = 0
Dim d As Decimal = 1
Dim od As Decimal
tests += 1
MyBase.GooRef(d, Await MyBase.GetVal(4), od)
If d = 2 AndAlso od = 1 Then
count += 1
End If
Result = count - tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public count As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Struct02a()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure TestCase
Private t As Task(Of Integer)
Public Async Function Run() As Task
Tests += 1
t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x = Await t
If x = 1 Then
Count += 1
End If
Tests += 1
t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x2 = Await Me.t
If x2 = 1 Then
Count += 1
End If
Result = Count - Tests
End Function
End Structure
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Struct02b()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure TT
Public t As Task(Of Integer)
End Structure
Structure TTT
Public t As TT
End Structure
Structure TestCase
Private t As TTT
Public Async Function Run() As Task
Tests += 1
t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x = Await t.t.t
If x = 1 Then
Count += 1
End If
Tests += 1
t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x2 = Await Me.t.t.t
If x2 = 1 Then
Count += 1
End If
Result = Count - Tests
End Function
End Structure
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Struct02c()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure TT
Public t As Task(Of Integer)
End Structure
Structure TTT
Public t As TT
End Structure
Structure TestCase
Private t As TTT
Public Async Function Run() As Task
Tests += 1
MyClass.t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x = Await t.t.t
If x = 1 Then
Count += 1
End If
Tests += 1
t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x2 = Await MyClass.t.t.t
If x2 = 1 Then
Count += 1
End If
Result = Count - Tests
End Function
End Structure
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Struct02d()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure TT
Public t As Task(Of Integer)
End Structure
Structure TTT
Public t As TT
End Structure
Class Base
Protected t As TTT
End Class
Class TestCase: Inherits Base
Public Async Function Run() As Task
Tests += 1
MyBase.t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x = Await MyBase.t.t.t
If x = 1 Then
Count += 1
End If
Tests += 1
MyBase.t.t.t = Task.Run(Async Function()
Await Task.Yield
Return 1
End Function)
Dim x2 = Await MyBase.t.t.t
If x2 = 1 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_StackSpill_Operator_Compound02()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run() As Task
Dim x() As Integer = {1, 2, 3, 4}
Tests += 1
x(Await GetVal(0)) += Await GetVal(4)
If x(0) = 5 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_AwaitSwitch()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function Run() As Task
Tests += 1
Select Case Await (Async Function()
Await Task.Yield
Return 5
End Function)()
Case 1
Case 2
Case 5
Count += 1
Case Else
End Select
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Inference()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure Test
Public ReadOnly Property Goo As Task(Of String)
Get
Return Task.Run(Of String)(Async Function()
Await Task.Yield
Return "abc"
End Function)
End Get
End Property
End Structure
Class TestCase(Of U)
Public Shared Async Function GetVal(tt As Object) As Task(Of Object)
Await Task.Yield
Return tt
End Function
Public Shared Function GetVal1(Of T As Task(Of U))(tt As T) As T
Return tt
End Function
Public Async Function Run() As Task
Dim t As New Test()
Tests += 1
Dim x1 = Await TestCase(Of String).GetVal(Await t.Goo)
If x1 = "abc" Then
Count += 1
End If
Tests += 1
Dim x2 = Await TestCase(Of String).GetVal1(t.Goo)
If x2 = "abc" Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase(Of Integer)().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Operator05()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase(Of U)
Public Async Function Goo1() As Task(Of Integer)
Await Task.Yield
Count += 1
Dim i = 42
Return i
End Function
Public Async Function Goo2() As Task(Of Object)
Await Task.Yield
Count += 1
Return "string"
End Function
Public Async Function Run() As Task
Dim x1 = TryCast(Await Goo1(), Object)
Dim x2 = TypeOf (Await Goo2()) Is String
If x1.Equals(42) Then
Tests += 1
End If
If x2 = True Then
Tests += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase(Of Integer)().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Property21()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class Base
Public Overridable Property MyProp As Integer
Get
Return 42
End Get
Protected Set(value As Integer)
End Set
End Property
End Class
Class TestCase : Inherits Base
Async Function GetBaseMyProp() As Task(Of Integer)
Await Task.Yield
Return MyBase.MyProp
End Function
Public Async Function Run() As Task
Result = Await GetBaseMyProp() - 42
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_AnonType32()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function Run() As Task
Tests += 1
Try
Throw New Exception(
Await (New With {
.Task = Task.Run(Of String)(
Async Function()
Await Task.Yield
Return "0-0"
End Function)}).Task)
Catch ex As Exception
If ex.Message = "0-0" Then
Count += 1
End If
End Try
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Init19()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class ObjInit
Public async As Integer
Public t As Task
Public l As Long
End Class
Class TestCase
Private Function [Throw](Of T)(i As T) As T
Throw New OverflowException()
End Function
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
[Throw](tt)
Return tt
End Function
Public Property MyProperty As Task(Of Long)
Public Async Function Run() As Task
Dim t = Task.Run(Of Integer)(Async Function()
Await Task.Yield
Throw New FieldAccessException()
Return 1
End Function)
Tests += 1
Try
MyProperty = Task.Run(Of Long)(Async Function()
Await Task.Yield
Throw New DataMisalignedException()
Return 1
End Function)
Dim obj As New ObjInit() With {
.async = Await t,
.t = GetVal((Task.Run(Async Sub()
Await Task.Yield
End Sub))),
.l = Await MyProperty
}
Await obj.t
Catch fieldex As FieldAccessException
Count += 1
Catch ex As Exception
Count -= 1
End Try
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call New TestCase().Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Dynamic()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Public Async Function F1(d As Object) As Task(Of Object)
Return Await d
End Function
Public Async Function F2(d As Task(Of Integer)) As Task(Of Integer)
Return Await d
End Function
Public Async Function Run() As Task(Of Integer)
Dim a As Integer = Await F1(Task.Factory.StartNew(Function() 21))
Dim b = Await F2(Task.Factory.StartNew(Function() 21))
Return a + b
End Function
Sub Main()
Console.Write(Run().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_Await15()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure DynamicClass
Public Async Function Goo(Of T)(tt As T) As Task(Of Object)
Await Task.Yield
Return tt
End Function
Public Async Function Bar(i As Integer) As Task(Of Task(Of Object))
Await Task.Yield
Return Task.Run(Of Object)(Async Function()
Await Task.Yield
Return i
End Function)
End Function
End Structure
Class TestCase
Public Shared Async Function Run() As Task
Dim dc As New DynamicClass()
Dim d As Object = 123
Tests += 1
Dim x1 = Await dc.Goo("")
If x1 = "" Then
Count += 1
End If
Tests += 1
Dim x2 = Await Await dc.Bar(d)
If x2 = 123 Then
Count += 1
End If
Tests += 1
Dim x3 = Await Await dc.Bar(Await dc.Goo(234))
If x3 = 234 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Await40()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class C1
Public Async Function Method(x As Integer) As Task(Of Integer)
Await Task.Yield
Return x
End Function
End Class
Class C2
Public Status As Integer
Public Sub New(Optional x As Integer = 5)
Status = x
End Sub
Public Sub New(x As Integer, y As Integer)
Status = x + y
End Sub
Public Function Bar(x As Integer) As Integer
Return x
End Function
End Class
Class TestCase
Public Shared Async Function Run() As Task
tests += 1
Dim c As Object = New C1()
Dim cc As New C2(x:=Await c.Method(1))
If cc.Status = 1 Then
Count += 1
End If
tests += 1
Dim f As Object = (Async Function()
Await Task.Yield
Return 4
End Function)
cc = New C2(Await c.Method(2), Await f.Invoke())
If cc.Status = 6 Then
Count += 1
End If
tests += 1
Dim x = New C2(2).Bar(Await c.Method(1))
If x = 1 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Await43()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure MyClazz
Public Shared Operator *(c As MyClazz, i As Integer) As Task
Return Task.Run(Async Function() As task
Await Task.Yield
Count += 1
End Function)
End Operator
Public Shared Operator +(c As MyClazz, i As Integer) As Task
Return Task.Run(Async Function() As task
Await Task.Yield
Count += 1
End Function)
End Operator
End Structure
Class TestCase
Public Shared Async Function Run() As Task
Dim dy As Object = Task.Run(Of MyClazz)(Async Function()
Await Task.Yield
Return New MyClazz()
End Function)
Tests += 1
Await ((Await dy) * 5)
Tests += 1
Dim d As Object = New MyClazz()
Dim dd As Object = Task.Run(Of Long)(Async Function()
Await Task.Yield
Return 1L
End Function)
Await (d + Await dd)
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Await44()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure MyClazz
Public Shared Narrowing Operator CType(c As MyClazz) As task
Return Task.Run(Async Function() As task
Await Task.Yield
Count += 1
End Function)
End Operator
End Structure
Class TestCase
Public Shared Async Function Run() As Task
Dim mc As New MyClazz()
Tests += 1
Dim t1 As Task = mc
Await t1
Tests += 1
Dim t2 As Object = CType(mc, Task)
Await t2
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Async_Conformance_Awaiting_indexer23_ValueType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure MyClazz(Of T As Task(Of Func(Of Integer)))
Public Property P As T
Public F As T
Default Public Property This(index As T) As T
Get
Return P
End Get
Set(value As T)
P = value
End Set
End Property
End Structure
Class TestCase
Public Shared Async Function Goo(d As Task(Of Func(Of Integer))) As Task(Of Task(Of Func(Of Integer)))
Await Task.Yield
Interlocked.Increment(Count)
Return d
End Function
Public Shared Async Function Run() As Task
Dim ms As New MyClazz(Of Task(Of Func(Of Integer)))()
ms(index:=Nothing) = Task.Run(Of Func(Of Integer))(Async Function()
Await Task.Yield
Interlocked.Increment(Count)
Return Function()
Return 123
End Function
End Function)
Tests += 1
Dim x = Await ms(index:=Await Goo(Nothing))
If x IsNot Nothing AndAlso x() = 123 Then
Tests += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Async_Conformance_Awaiting_indexer23_ReferenceType()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class MyClazz(Of T As Task(Of Func(Of Integer)))
Public Property P As T
Public F As T
Default Public Property This(index As T) As T
Get
Return P
End Get
Set(value As T)
P = value
End Set
End Property
End Class
Class TestCase
Public Shared Async Function Goo(d As Task(Of Func(Of Integer))) As Task(Of Task(Of Func(Of Integer)))
Await Task.Yield
Interlocked.Increment(Count)
Return d
End Function
Public Shared Async Function Run() As Task
Dim ms As New MyClazz(Of Task(Of Func(Of Integer)))()
ms(index:=Nothing) = Task.Run(Of Func(Of Integer))(Async Function()
Await Task.Yield
Interlocked.Increment(Count)
Return Function()
Return 123
End Function
End Function)
Tests += 1
Dim x = Await ms(index:=Await Goo(Nothing))
If x IsNot Nothing AndAlso x() = 123 Then
Tests += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
TestCase.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_Async_StackSpill_Argument_Generic04()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class MyClazz(Of T)
Public Async Function Goo(Of V)(tt As T, vv As V) As Task(Of Object)
Await Task.Yield
Return vv
End Function
End Class
Class TestCase
Public Shared Async Function Goo() As Task(Of Integer)
Dim mc As Object = New MyClazz(Of String)()
Dim rez = Await mc.Goo(Of String)(Nothing, Await (Async Function() As Task(Of String)
Await Task.Yield
Return "Test"
End Function)())
If rez = "Test" Then
Return 0
End If
Return 1
End Function
End Class
Module Form1
Sub Main()
Console.Write(TestCase.Goo().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_AsyncStackSpill_assign01()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Private val As Integer
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Async Function Run() As Task
Tests += 1
Dim x() As Integer = {1, 2, 3, 4}
val = Await (Async Function()
x(Await GetVal(0)) += Await GetVal(4)
Return x(Await GetVal(0))
End Function())
If x(0) = 5 AndAlso val = Await GetVal(5) Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call (New TestCase()).Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_MyTask_08()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class MyTask
Public Shared Async Function Run() As Task
Tests += 1
Dim myTask As New MyTask()
Dim x = Await myTask
If x = 123 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Public Class MyTaskAwaiter : Implements System.Runtime.CompilerServices.INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements System.Runtime.CompilerServices.INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As Integer
Return 123
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
Public Module Extension
<System.Runtime.CompilerServices.Extension>
Public Function GetAwaiter(this As MyTask) As MyTaskAwaiter
Return New MyTaskAwaiter()
End Function
End Module
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
MyTask.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_MyTask_16()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class MyTask
Public Function GetAwaiter() As MyTaskAwaiter
Return New MyTaskAwaiter()
End Function
Public Shared Async Function Run() As Task
Tests += 1
Dim myTask As New MyTask()
Dim x = Await myTask
If x = 123 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Public Class MyTaskBaseAwaiter : Implements System.Runtime.CompilerServices.INotifyCompletion
Public Sub OnCompleted(continuation As Action) Implements System.Runtime.CompilerServices.INotifyCompletion.OnCompleted
End Sub
Public Function GetResult() As Integer
Return 123
End Function
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
End Class
Public Class MyTaskAwaiter : Inherits MyTaskBaseAwaiter
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
MyTask.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_InitCollection_045()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Structure PrivateCollection : Implements IEnumerable
Public lst As List(Of Integer)
Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Return lst
End Function
Public Sub Add(x As Integer)
If lst Is Nothing Then
lst = New List(Of Integer)
End If
lst.Add(x)
End Sub
End Structure
Public Class MyTask
Public Shared Async Function GetVal(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Shared Async Function Run() As Task
Tests += 1
Dim myCol = New PrivateCollection() From {Await GetVal(1), Await GetVal(2)}
If myCol.lst(0) = 1 AndAlso myCol.lst(1) = 2 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
MyTask.Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_RefExpr()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class MyClazz
Public Field As Integer
End Class
Public Class MyTask
Public Shared Function Goo(ByRef x As Integer, y As Integer) As Integer
Return x + y
End Function
Public Shared Async Function GetVal(Of T)(tt As T) As Task(Of T)
Await Task.Yield
Return tt
End Function
Public Shared Async Function Run() As Task(Of Integer)
Return Goo((New MyClazz() With {.Field = 21}.Field), Await Task.Factory.StartNew(Function() 21))
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
'MyTask.Run()
'CompletedSignal.WaitOne(60000)
'Console.Write(Result)
Console.Write(MyTask.Run().Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub Imported_ManagedPointerSpillAssign03()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Public Async Function GetVal(Of T)(tt As t) As Task(Of T)
Await Task.Yield
Return tt
End Function
Class PrivClass
Friend Structure ValueT
Public Field As Integer
End Structure
Friend arr(2) As ValueT
End Class
Private myPrivClass As PrivClass
Public Async Function Run() As Task
Me.myPrivClass = New PrivClass()
Tests += 1
Me.myPrivClass.arr(0).Field = Await GetVal(4)
If Me.myPrivClass.arr(0).Field = 4 Then
Count += 1
End If
Tests += 1
Me.myPrivClass.arr(0).Field += Await GetVal(4)
If Me.myPrivClass.arr(0).Field = 8 Then
Count += 1
End If
Tests += 1
Me.myPrivClass.arr(Await GetVal(1)).Field += Await GetVal(4)
If Me.myPrivClass.arr(1).Field = 4 Then
Count += 1
End If
Tests += 1
Me.myPrivClass.arr(Await GetVal(1)).Field += 1
If Me.myPrivClass.arr(1).Field = 5 Then
Count += 1
End If
Result = Count - Tests
End Function
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
Call (New TestCase()).Run().Wait(60000)
Console.Write(Result)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_SacrificialRead()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Class TestCase
Shared Sub F1(ByRef x As Integer, y As Integer, z As Integer)
x += y + z
End Sub
Shared Function F0() As Integer
Console.Write(-1)
Return 0
End Function
Shared Async Function F2() As Task(Of Integer)
Dim x() As Integer = {21}
x = Nothing
F1(x(0), F0(), Await Task.Factory.StartNew(Function() 21))
Return x(0)
End Function
End Class
Module Form1
Sub Main()
Dim t = TestCase.F2()
Try
t.Wait(60000)
Catch ex As Exception
Console.Write(0)
Return
End Try
Console.Write(-1)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="0")
End Sub
<Fact()>
Public Sub Imported_RefThisStruct()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Structure S1
Public X As Integer
Public Async Sub Goo1()
Bar(Me, Await Task(Of Integer).FromResult(42))
End Sub
Public Sub Goo2()
Bar(Me, 42)
End Sub
Public Sub Bar(ByRef x As S1, y As Integer)
x.X = 42
End Sub
End Structure
Class C1
Public X As Integer
Public Async Sub Goo1()
Bar(Me, Await Task(Of Integer).FromResult(42))
End Sub
Public Sub Goo2()
Bar(Me, 42)
End Sub
Public Sub Bar(ByRef x As C1, y As Integer)
x.X = 42
End Sub
End Class
Module Form1
Public Result As Integer = -1
Public Count As Integer = 0
Public Tests As Integer = 0
Sub Main()
If True Then
Dim s As S1
s.X = -1
s.Goo1()
Console.Write(s.X)
Console.Write(" ")
End If
If True Then
Dim s As S1
s.X = -1
s.Goo2()
Console.Write(s.X)
Console.Write(" ")
End If
If True Then
Dim s As S1
s.X = -1
s.Bar(s, 42)
Console.Write(s.X)
Console.Write(" ")
End If
If True Then
Dim s As New C1
s.X = -1
s.Goo1()
Console.Write(s.X)
Console.Write(" ")
End If
If True Then
Dim s As New C1
s.X = -1
s.Goo2()
Console.Write(s.X)
Console.Write(" ")
End If
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="-1 -1 42 42 42")
End Sub
<Fact()>
Public Sub FieldReuseOnStatementLevel()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Linq.Expressions
Imports System.Collections
Imports System.Collections.Generic
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Async Function F(Of T)(p As T, s As String) As Task(Of T)
Console.Write(s)
Console.Write(" ")
Await Task.Yield
Return p
End Function
Function S(Of T)(ParamArray a() As T) As T
Console.Write("S(")
For i = 0 To a.Count - 1
If i > 0 Then
Console.Write(",")
End If
Console.Write(a(i).ToString())
Next
Console.Write(") ")
Return a(0)
End Function
Async Function Test() As Task
Await Task.Yield
S(Await F(True, "1"),
Await F(True, "2"),
Await F(True, "3"),
If(Await F(False, "4"),
Await F(False, "5"),
S(Await F(False, "6"),
Await F(False, "7"),
Await F(False, "8"))),
Await F(True, "9"))
End Function
Sub Main()
Test().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3 4 6 7 8 S(False,False,False) 9 S(True,True,True,False,True)",
symbolValidator:=Sub(m)
CheckFields(m, "Form1", "Test",
{
"Friend $A0 As System.Runtime.CompilerServices.YieldAwaitable.YieldAwaiter",
"Friend $A1 As System.Runtime.CompilerServices.TaskAwaiter(Of Boolean)",
"Friend $U1 As Boolean",
"Friend $U2 As Boolean",
"Friend $U3 As Boolean",
"Friend $U4 As Boolean",
"Friend $U5 As Boolean",
"Friend $U6 As Boolean",
"Friend $U7 As Boolean",
"Public $Builder As System.Runtime.CompilerServices.AsyncTaskMethodBuilder",
"Public $State As Integer"
})
End Sub)
End Sub
<Fact()>
Public Sub SpillValueRequiringCleanUp()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Sub M(Of T)(x As T, y As T)
Console.Write("M ")
End Sub
Async Function F(Of T As New)(v As T) As Task(Of T)
Console.Write("F ")
Await Task.Yield
Return v
End Function
Class C
End Class
Async Function Test(Of T As New)() As Task
Console.Write("Test ")
M(New T, Await F(New T))
End Function
Sub Main()
Test(Of C)().Wait(60000)
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="Test F M")
End Sub
<Fact()>
Public Sub CapturedExceptionInCatchBlock()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Async Function Test() As task
Dim col = {1, 2, 3}
Try
Throw New Exception("test")
Catch ex As Exception
Dim q = From i In col Where ex.Message = "test" Select p = ex.Message
For Each t In q
Console.Write(t)
Console.Write(" ")
Next
End Try
Await task.Delay(5)
End Function
Sub Main()
Test().Wait()
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="test test test")
End Sub
<Fact()>
Public Sub ForLoopAndLateBinding()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Async Function x() As Task(Of Integer)
Await Task.Yield
Return 1
End Function
Async Function y() As Task(Of Integer)
Await Task.Yield
Return 10
End Function
Async Function z() As Task(Of Integer)
Await Task.Yield
Return 2
End Function
Async Function Test() As Task
'Try
Dim a As Object = x()
Dim b As Object = y()
Dim c As Object = z()
Dim iCount As Integer = 0
For i = Await a To Await b Step Await c
Console.Write(i)
Console.Write(" ")
Next
'Catch ex As Exception
' Console.Write(" EXC(")
' Console.Write(ex.Message)
' Console.Write(")")
'End Try
End Function
Sub Main()
Test().Wait()
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 3 5 7 9")
End Sub
<Fact, WorkItem(1003196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1003196")>
Public Sub AsyncAndPartialMethods()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Form1
Sub Main()
Call (New C).CallingMethod()
End Sub
End Module
Partial Class C
Public Async Sub CallingMethod()
Await Task.Yield
F()
End Sub
Partial Private Sub F()
End Sub
End Class
Partial Class C
Private Async Sub F()
Await Task.Yield
End Sub
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="")
End Sub
<Fact()>
Public Sub NoNeedToProcessUnstructuredExceptions()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Program
Sub Main(args As String())
Console.Write(New TestCase_named_04().Concatenate("1", " ", "2").Result)
End Sub
End Module
Class TestCase_named_04
Public Async Function Concatenate(ParamArray vals As String()) As Task(Of String)
Await Task.Yield
Dim rez As String = String.Empty
For i = 0 To vals.Length - 1
rez += vals(i)
Next
Return rez
End Function
End Class
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2")
End Sub
<Fact()>
Public Sub ExceptionsInPropertyAccess()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Public Sub Main(args As String())
Test1().Wait()
Test2().Wait()
Test3().Wait()
Test4().Wait()
End Sub
Async Function Test1() As Task
Try
M().PropA() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
End Function
Async Function Test2() As Task
Try
M().PropA() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += L()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += O()
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
End Function
Async Function Test3() As Task
Try
M().PropA() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() = (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
End Function
Async Function Test4() As Task
Try
M().PropA() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropA() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
M().PropB() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropA() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += (Await LL())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
Try
N().PropB() += (Await OO())
Catch ex As Exception
Console.Write(ex.Message)
Console.Write(" ")
End Try
End Function
Async Function F(ParamArray a() As Integer) As Task(Of String)
Await Task.Yield
Return ""
End Function
Private Function L() As String
Throw New Exception("L()")
End Function
Private Async Function LL() As Task(Of String)
Throw New Exception("L()")
End Function
Private Function M() As Clazz
Throw New Exception("M()")
End Function
Private Function N() As Clazz
Return New Clazz()
End Function
Private Function O() As String
Return ""
End Function
Private Async Function OO() As Task(Of String)
Return ""
End Function
End Module
Public Class Clazz
Public Property PropA As String
Get
Throw New Exception("get_Prop")
End Get
Set(value As String)
Throw New Exception("set_Prop")
End Set
End Property
Public Property PropB As String
Get
Throw New Exception("get_Prop")
End Get
Set(value As String)
Throw New Exception("set_Prop")
End Set
End Property
End Class
</file>
</compilation>, useLatestFramework:=True,
expectedOutput:="M() M() M() M() L() set_Prop L() set_Prop M() M() M() M() L() set_Prop L() set_Prop M()" +
" M() M() M() get_Prop get_Prop get_Prop get_Prop M() M() M() M() get_Prop get_Prop get_Prop" +
" get_Prop M() M() M() M() L() set_Prop L() set_Prop M() M() M() M() L() set_Prop L() set_Prop" +
" M() M() M() M() get_Prop get_Prop get_Prop get_Prop M() M() M() M() get_Prop get_Prop get_Prop get_Prop")
End Sub
<Fact()>
Public Sub RewritingBlocksIntoBoundStateMachineScope()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Module Program
Sub Main(args As String())
Console.Write(Select3().Result)
End Sub
Async Function Select3() As Task(Of Object)
Dim outer = 1
Dim s As Object
Select Case 1
Case 1
Dim inner1 = 41
Await Task.Yield
s = inner1
Case Else
Dim inner2 = 1
s = inner2
End Select
s = outer + s
Return s
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub AwaitWithPlaceholderInLambda()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.Reflection
Module Module1
Dim t As Task(Of Integer) = Task.Factory.StartNew(Function() 4)
Sub Main()
f1(t).Wait()
Console.Write(f2(2).Result)
g(t, 4)
End Sub
Async Function f1(Of U)(ByVal x As Task(Of U)) As Task
Console.Write(Await x)
End Function
Async Function f2(Of U)(ByVal y As U) As Task(Of U)
Return y
End Function
Sub g(Of U)(ByVal x As Task(Of U), ByVal y As U)
Dim lambda1 = Async Function(x1 As Task(Of U))
Dim z = Await x1
End Function
Dim lambda2 = Async Function(y2 As U)
Return y2
End Function
lambda1(x).Wait()
lambda2(y).Wait()
End Sub
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="42")
End Sub
<Fact()>
Public Sub GenericLambdasAndAsyncFunctions()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.Reflection
Imports System.Collections
Module Module1
Sub Main()
h(Of Integer)(Function() b(Of Integer)(),
b(Of Integer)(),
Function() d(Of Integer)(),
d(Of Integer)())
End Sub
Sub h(Of T)(ByVal p1 As Func(Of AwaitableStructure(Of T)), ByVal p2 As AwaitableStructure(Of T),
ByVal p3 As Func(Of Task(Of T)), ByVal p4 As Task(Of T))
Dim lambda = Async Function()
Console.Write("1 ")
Await e(Of T)()
Console.Write(Await e(Of T)())
Console.Write(" ")
Dim e1 = e(Of T)()
Await e1
Console.Write(Await e1)
Console.Write(" ")
End Function
lambda().Wait()
End Sub
Public Structure AwaitableStructure
Public Function GetAwaiter() As AwaiterStructure
Console.Write("2 ")
Return New AwaiterStructure
End Function
End Structure
Public Structure AwaiterStructure : Implements System.Runtime.CompilerServices.INotifyCompletion
Public ReadOnly Property IsCompleted As Boolean
Get
Console.Write("3 ")
Return True
End Get
End Property
Public Sub OnCompleted(ByVal continuationAction As Action) Implements System.Runtime.CompilerServices.INotifyCompletion.OnCompleted
Console.Write("4 ")
End Sub
Public Sub GetResult()
Console.Write("5 ")
End Sub
End Structure
Public Function b(Of T)() As AwaitableStructure(Of T)
Console.Write("6 ")
Return New AwaitableStructure(Of T)
End Function
Public Structure AwaitableStructure(Of T)
Public Function GetAwaiter() As AwaiterStructure(Of T)
Console.Write("7 ")
Return New AwaiterStructure(Of T)
End Function
End Structure
Public Structure AwaiterStructure(Of T) : Implements System.Runtime.CompilerServices.INotifyCompletion
Public ReadOnly Property IsCompleted As Boolean
Get
Console.Write("8 ")
Return True
End Get
End Property
Public Sub OnCompleted(ByVal continuationAction As Action) Implements System.Runtime.CompilerServices.INotifyCompletion.OnCompleted
Console.Write("9 ")
End Sub
Public Function GetResult() As T
Console.Write("10 ")
Return Nothing
End Function
End Structure
Public Function d(Of T)() As Task(Of T)
Console.Write("11 ")
Return Task.Factory.StartNew(Of T)(Function() Nothing)
End Function
Public Function e(Of T)() As RegularStructure(Of T)
Console.Write("12 ")
Return New RegularStructure(Of T)
End Function
Public Structure RegularStructure(Of T)
End Structure
<System.Runtime.CompilerServices.Extension()> Function GetAwaiter(Of T)(ByVal self As RegularStructure(Of T)) As AwaiterStructure(Of T)
Console.Write("13 ")
Return New AwaiterStructure(Of T)
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="6 11 1 12 13 8 10 12 13 8 10 0 12 13 8 10 13 8 10 0")
End Sub
<Fact>
Public Sub LiftApparentlyEmptyStructs()
Dim csCompilation = CreateCSharpCompilation("Empty_cs", <![CDATA[
/// <summary>
/// An apparently empty struct that actually encapsulates a byte. Used to see how
/// the compiler treats empty structs.
/// </summary>
public struct Empty
{
public byte Value
{
get
{
unsafe
{
byte* p = Ptr(ref this);
return *p;
}
}
set
{
unsafe
{
byte* p = Ptr(ref this);
*p = value;
}
}
}
private unsafe byte* Ptr(ref Empty e)
{
fixed (Empty* p = &e)
{
return (byte*)p;
}
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release, allowUnsafe:=True))
csCompilation.VerifyDiagnostics()
Dim vbexeCompilation = CreateVisualBasicCompilation("VBExe", <![CDATA[
Imports System
Imports System.Threading.Tasks
Module Module1
Sub Main()
Sample().Wait()
End Sub
Private Async Function Sample() As Task
Dim e1 As Empty
e1.Value = 12
Await Task.Delay(5)
Console.WriteLine(e1.Value)
End Function
End Module]]>,
compilationOptions:=TestOptions.ReleaseExe,
referencedCompilations:={csCompilation},
referencedAssemblies:=LatestVbReferences)
Dim vbexeVerifier = CompileAndVerify(vbexeCompilation, expectedOutput:="12")
vbexeVerifier.VerifyDiagnostics()
End Sub
<Fact()>
Public Sub HoistingUninitializerVars()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.Reflection
Module Form1
Sub Main()
UninitializedVar().Wait(60000)
End Sub
Async Function UninitializedVar() As Task
For q = 1 To 2
For i = 1 To 3
Dim y As Integer
Dim x = y + 1
y = x
Console.Write(x)
Console.Write(" ")
Next
Await Task.Yield()
Next
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3 4 5 6")
End Sub
<Fact()>
Public Sub HoistingUninitializerVars2()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Linq
Imports System.Threading
Imports System.Threading.Tasks
Imports System.Collections.Generic
Imports System.Reflection
Module Form1
Sub Main()
RecursiveVar().Wait(60000)
End Sub
Async Function RecursiveVar() As Task
For q = 1 To 2
For i = 1 To 3
Dim x As Integer = x + 1
Console.Write(x)
Console.Write(" ")
Next
Await Task.Yield()
Next
End Function
End Module
</file>
</compilation>, useLatestFramework:=True, expectedOutput:="1 2 3 4 5 6")
End Sub
Private Sub EmittedSymbolsCheck(dbg As Boolean)
Dim TypeNamePattern As New Regex("^VB\$StateMachine_(\d)+_(\w)+$", RegexOptions.Singleline)
Dim FieldPattern As New Regex("^((\$Builder)|(\$Stack)|(\$State)|(\$VB\$Me)|(\$A(\d)+)|(\$S(\d)+)|(\$I(\d)+)|(\$VB\$ResumableLocal_\$(\d)+)|(\$U(\d)+))$", RegexOptions.Singleline)
Dim FormatAttribute As Func(Of VisualBasicAttributeData, String) =
Function(attr)
Dim result = attr.AttributeClass.ToDisplayString & "("
Dim first = True
For Each arg In attr.ConstructorArguments()
If first Then
first = False
Else
result &= ","
End If
result &= arg.Value.ToString()
Next
For Each arg In attr.NamedArguments
If first Then
first = False
Else
result &= ","
End If
result &= arg.Key
result &= "="
result &= arg.Value.ToString
Next
result &= ")"
Return result
End Function
Dim attributeValidator As Action(Of Symbol, String()) =
Sub(symbol, attrs)
Assert.Equal(ArrayToSortedString(attrs),
ArrayToSortedString((From a In symbol.GetAttributes() Select FormatAttribute(a)).ToArray()))
End Sub
Dim methodValidator As Action(Of MethodSymbol) =
Sub(method)
Select Case method.Name
Case ".ctor"
' This is an auto-generated constructor, ignore it
Case "System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine"
Assert.Equal(Accessibility.Private, method.DeclaredAccessibility)
Assert.Equal(1, method.ExplicitInterfaceImplementations.Length)
Assert.Equal("Sub SetStateMachine(stateMachine As System.Runtime.CompilerServices.IAsyncStateMachine)", method.ExplicitInterfaceImplementations(0).ToDisplayString)
attributeValidator(method, If(dbg,
{"System.Diagnostics.DebuggerNonUserCodeAttribute()"},
{}))
Case "MoveNext"
Assert.Equal(Accessibility.Friend, method.DeclaredAccessibility)
Assert.Equal(1, method.ExplicitInterfaceImplementations.Length)
Assert.Equal("Sub MoveNext()", method.ExplicitInterfaceImplementations(0).ToDisplayString)
attributeValidator(method, {"System.Runtime.CompilerServices.CompilerGeneratedAttribute()"})
Case Else
Assert.True(False)
End Select
End Sub
Dim fieldValidator As Action(Of FieldSymbol) =
Sub(field)
Assert.True(FieldPattern.IsMatch(field.Name))
' TODO: $Builder and $State are public
'Assert.Equal(Accessibility.Internal, field.DeclaredAccessibility)
attributeValidator(field, {})
End Sub
Dim stateMachineValidator As Action(Of NamedTypeSymbol) =
Sub(type)
Assert.Equal(Accessibility.Private, type.DeclaredAccessibility)
Assert.True(type.IsNotInheritable)
Assert.Equal(1, type.Interfaces.Length)
Assert.Equal("System.Runtime.CompilerServices.IAsyncStateMachine", type.Interfaces(0).ToDisplayString())
attributeValidator(type, {"System.Runtime.CompilerServices.CompilerGeneratedAttribute()"})
Dim processed As New HashSet(Of String)
For Each member In type.GetMembers()
Dim added = processed.Add(member.Name)
Debug.Assert(added)
Select Case member.Kind
Case SymbolKind.Method
methodValidator(DirectCast(member, MethodSymbol))
Case SymbolKind.Field
fieldValidator(DirectCast(member, FieldSymbol))
Case Else
Assert.True(False)
End Select
Next
End Sub
Dim moduleValidator As Action(Of ModuleSymbol) =
Sub([module])
Dim testCaseType As NamedTypeSymbol = [module].ContainingAssembly.GetTypeByMetadataName("TestCase")
Assert.NotNull(testCaseType)
Dim runMethod = testCaseType.GetMember(Of MethodSymbol)("Run")
Assert.NotNull(runMethod)
If dbg Then
attributeValidator(runMethod, {"System.Diagnostics.DebuggerStepThroughAttribute()",
"System.Runtime.CompilerServices.AsyncStateMachineAttribute(TestCase.VB$StateMachine_4_Run)"})
Else
attributeValidator(runMethod, {"System.Runtime.CompilerServices.AsyncStateMachineAttribute(TestCase.VB$StateMachine_4_Run)"})
End If
Dim f2Method = testCaseType.GetMember(Of MethodSymbol)("F2")
Assert.NotNull(f2Method)
If dbg Then
attributeValidator(f2Method, {"System.Diagnostics.DebuggerStepThroughAttribute()",
"System.Runtime.CompilerServices.AsyncStateMachineAttribute(TestCase.VB$StateMachine_2_F2)"})
Else
attributeValidator(f2Method, {"System.Runtime.CompilerServices.AsyncStateMachineAttribute(TestCase.VB$StateMachine_2_F2)"})
End If
For Each nestedType In testCaseType.GetTypeMembers()
Assert.True(TypeNamePattern.IsMatch(nestedType.Name))
stateMachineValidator(nestedType)
Next
End Sub
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading
Imports System.Threading.Tasks
Public Class TestCase
Public field As Integer
Async Function F2() As Task(Of Integer)
Await Task.Yield
Return 1
End Function
Function FFF(x As Integer, ByRef y As Double, z As Integer) As Integer
Return x + y + z
End Function
Public Async Function Run() As Task(Of Integer)
Dim x = 1
x += Await F2()
Dim y = 2
Return FFF(y + x, Me.field, Await F2())
End Function
End Class
</file>
</compilation>, options:=If(dbg, TestOptions.DebugDll, TestOptions.ReleaseDll),
useLatestFramework:=True,
symbolValidator:=moduleValidator)
End Sub
<Fact, WorkItem(1002672, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1002672")>
Public Sub EmittedSymbolsCheck_Debug()
EmittedSymbolsCheck(True)
End Sub
<Fact>
Public Sub EmittedSymbolsCheck_Release()
EmittedSymbolsCheck(False)
End Sub
<WorkItem(840843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840843")>
<Fact>
Public Sub MissingAsyncVoidMethodBuilder()
Dim source =
<compilation name="AsyncVoid">
<file name="a.vb">
Public Class TestCase
Async Sub M()
End Sub
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {MscorlibRef}, TestOptions.ReleaseDll) ' NOTE: 4.0, Not 4.5, so it's missing the async helpers.
comp.AssertTheseEmitDiagnostics(
<errors>
BC31091: Import of type 'AsyncVoidMethodBuilder' from assembly or module 'AsyncVoid.dll' failed.
Async Sub M()
~~~~~~~~~~~~~~
BC31091: Import of type 'AsyncVoidMethodBuilder' from assembly or module 'AsyncVoid.dll' failed.
Async Sub M()
~~~~~~~~~~~~~~
BC31091: Import of type 'IAsyncStateMachine' from assembly or module 'AsyncVoid.dll' failed.
Async Sub M()
~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' is not defined.
Async Sub M()
~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' is not defined.
Async Sub M()
~~~~~~~~~~~~~~
BC42356: This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.
Async Sub M()
~
</errors>)
End Sub
<Fact>
Public Sub MissingAsyncTaskMethodBuilder()
Dim source =
<compilation name="AsyncTask">
<file name="a.vb">
Imports System.Threading.Tasks
Public Class TestCase
Async Function M() As Task
End Function
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {MscorlibRef}, TestOptions.ReleaseDll) ' NOTE: 4.0, Not 4.5, so it's missing the async helpers.
comp.AssertTheseEmitDiagnostics(
<errors>
BC31091: Import of type 'AsyncTaskMethodBuilder' from assembly or module 'AsyncTask.dll' failed.
Async Function M() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'AsyncTaskMethodBuilder' from assembly or module 'AsyncTask.dll' failed.
Async Function M() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'IAsyncStateMachine' from assembly or module 'AsyncTask.dll' failed.
Async Function M() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' is not defined.
Async Function M() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' is not defined.
Async Function M() As Task
~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42356: This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.
Async Function M() As Task
~
</errors>)
End Sub
<Fact>
Public Sub MissingAsyncTaskMethodBuilder_T()
Dim source =
<compilation name="AsyncTask_T">
<file name="a.vb">
Imports System.Threading.Tasks
Public Class TestCase
Async Function M() As Task(Of Integer)
Return 3
End Function
End Class
</file>
</compilation>
Dim comp = CreateEmptyCompilationWithReferences(source, {MscorlibRef}, TestOptions.ReleaseDll) ' NOTE: 4.0, Not 4.5, so it's missing the async helpers.
comp.AssertTheseEmitDiagnostics(
<errors>
BC31091: Import of type 'AsyncTaskMethodBuilder(Of )' from assembly or module 'AsyncTask_T.dll' failed.
Async Function M() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'AsyncTaskMethodBuilder(Of )' from assembly or module 'AsyncTask_T.dll' failed.
Async Function M() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC31091: Import of type 'IAsyncStateMachine' from assembly or module 'AsyncTask_T.dll' failed.
Async Function M() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' is not defined.
Async Function M() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' is not defined.
Async Function M() As Task(Of Integer)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC42356: This async method lacks 'Await' operators and so will run synchronously. Consider using the 'Await' operator to await non-blocking API calls, or 'Await Task.Run(...)' to do CPU-bound work on a background thread.
Async Function M() As Task(Of Integer)
~
</errors>)
End Sub
<WorkItem(863, "https://github.com/dotnet/roslyn/issues/863")>
<Fact()>
Public Sub CatchInIteratorStateMachine()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Collections
Class C
Shared Function F() As Object
Throw New ArgumentException("Value does not fall within the expected range.")
End Function
Shared Iterator Function M() As IEnumerable
Dim o As Object
Try
o = F()
Catch e As Exception
o = e
End Try
Yield o
End Function
Shared Sub Main()
For Each e As Exception in M()
' Cannot just call .ToString() on the exception, because the exact format of a stack trace depends on a localization
Console.WriteLine($"{e.GetType()}: {e.Message}")
For Each frame In New Diagnostics.StackTrace(e).GetFrames()
Dim m = frame.GetMethod()
Console.WriteLine($" at {m.DeclaringType.FullName.Replace("+"c, "."c)}.{m.Name}({String.Join(",", DirectCast(m.GetParameters(), Object()))})")
Next
Next
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe,
useLatestFramework:=True,
expectedOutput:=
"System.ArgumentException: Value does not fall within the expected range.
at C.F()
at C.VB$StateMachine_2_M.MoveNext()")
End Sub
<WorkItem(863, "https://github.com/dotnet/roslyn/issues/863")>
<Fact()>
Public Sub CatchInAsyncStateMachine()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Class C
Shared Function F() As Object
Throw New ArgumentException("Value does not fall within the expected range.")
End Function
Shared Async Function M() As Task(Of Object)
Dim o As Object
Try
o = F()
Catch e As Exception
o = e
End Try
Return o
End Function
Shared Sub Main()
Dim e = DirectCast(M().Result, Exception)
' Cannot just call .ToString() on the exception, because the exact format of a stack trace depends on a localization
Console.WriteLine($"{e.GetType()}: {e.Message}")
For Each frame In New Diagnostics.StackTrace(e).GetFrames()
Dim m = frame.GetMethod()
Console.WriteLine($" at {m.DeclaringType.FullName.Replace("+"c, "."c)}.{m.Name}({String.Join(",", DirectCast(m.GetParameters(), Object()))})")
Next
End Sub
End Class
</file>
</compilation>,
options:=TestOptions.DebugExe,
useLatestFramework:=True,
expectedOutput:=
"System.ArgumentException: Value does not fall within the expected range.
at C.F()
at C.VB$StateMachine_2_M.MoveNext()")
End Sub
<Fact, WorkItem(1942, "https://github.com/dotnet/roslyn/issues/1942")>
Public Sub HoistStructure()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Structure TestStruct
Public i As Long
Public j As Long
End Structure
Class Program
Shared Async Function TestAsync() As Task
Dim t As TestStruct
t.i = 12
Console.WriteLine("Before {0}", t.i)
Await Task.Delay(100)
Console.WriteLine("After {0}", t.i)
End Function
Shared Sub Main()
TestAsync().Wait()
End Sub
End Class
</file>
</compilation>
Dim expectedOutput = <![CDATA[Before 12
After 12]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")>
Public Sub HoistUsing001()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Class D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Console.WriteLine("disposed")
End Sub
End Class
Sub Main()
Console.WriteLine(Test.Result)
End Sub
Private Async Function Test() As Task(Of String)
Console.WriteLine("Pre")
Using window = New D
Console.WriteLine("show")
For index = 1 To 2
Await Task.Delay(100)
Next
End Using
Console.WriteLine("Post")
Return "result"
End Function
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[Pre
show
disposed
Post
result]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")>
Public Sub HoistUsing002()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Class D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Console.WriteLine("disposed")
End Sub
End Class
Sub Main()
Console.WriteLine(Test.Result)
End Sub
Private Async Function Test() As Task(Of String)
Console.WriteLine("Pre")
Dim window = New D
Try
Console.WriteLine("show")
For index = 1 To 2
Await Task.Delay(100)
Next
Finally
window.Dispose()
End Try
Console.WriteLine("Post")
Return "result"
End Function
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[Pre
show
disposed
Post
result]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")>
Public Sub HoistUsing003()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Class D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Console.WriteLine("disposed")
End Sub
End Class
Sub Main()
Console.WriteLine(Test.Result)
End Sub
Private Async Function Test() As Task(Of String)
Console.WriteLine("Pre")
Dim window as D
Try
window = New D
Console.WriteLine("show")
For index = 1 To 2
Await Task.Delay(100)
Next
Finally
window.Dispose()
End Try
Console.WriteLine("Post")
Return "result"
End Function
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[Pre
show
disposed
Post
result]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")>
Public Sub HoistUsing004()
Dim source =
<compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Module Module1
Class D
Implements IDisposable
Public Sub Dispose() Implements IDisposable.Dispose
Console.WriteLine("disposed")
End Sub
End Class
Sub Main()
Console.WriteLine(Test.Result)
End Sub
Private Async Function Test() As Task(Of String)
Console.WriteLine("Pre")
Using window1 = New D
Console.WriteLine("show")
Using window = New D
Console.WriteLine("show")
For index = 1 To 2
Await Task.Delay(100)
Next
End Using
End Using
Console.WriteLine("Post")
Return "result"
End Function
End Module
</file>
</compilation>
Dim expectedOutput = <![CDATA[Pre
show
show
disposed
disposed
Post
result]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(9463, "https://github.com/dotnet/roslyn/issues/9463")>
Public Sub AsyncIteratorReportsDiagnosticsWhenCoreTypesAreMissing()
Dim source = "
Imports System.Threading.Tasks
Namespace System
Public Class [Object]
End Class
Public Class [Int32]
End Class
Public Class [Boolean]
End Class
Public Class [String]
End Class
Public Class Exception
End Class
Public Class ValueType
End Class
Public Class [Enum]
End Class
Public Class Void
End Class
End Namespace
Namespace System.Threading.Tasks
Public Class Task
Public Function GetAwaiter() As TaskAwaiter
Return Nothing
End Function
End Class
Public Class TaskAwaiter
Implements System.Runtime.CompilerServices.INotifyCompletion
Public ReadOnly Property IsCompleted As Boolean
Get
Return True
End Get
End Property
Public Sub GetResult()
End Sub
End Class
End Namespace
Namespace System.Runtime.CompilerServices
Public Interface INotifyCompletion
End Interface
Public Interface ICriticalNotifyCompletion
End Interface
Public Interface IAsyncStateMachine
Sub MoveNext()
Sub SetStateMachine(stateMachine As IAsyncStateMachine)
End Interface
Public Class AsyncVoidMethodBuilder
End Class
End Namespace
Class C
Public Async Sub GetNumber(task As Task)
Await task
End Sub
End Class
"
Dim compilation = CreateEmptyCompilation({Parse(source)})
compilation.AssertTheseEmitDiagnostics(<expected>
BC30456: 'Create' is not a member of 'AsyncVoidMethodBuilder'.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'SetException' is not a member of 'AsyncVoidMethodBuilder'.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'SetResult' is not a member of 'AsyncVoidMethodBuilder'.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'SetStateMachine' is not a member of 'AsyncVoidMethodBuilder'.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'Start' is not a member of 'AsyncVoidMethodBuilder'.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError' is not defined.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC35000: Requested operation is not available because the runtime library function 'Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError' is not defined.
Public Async Sub GetNumber(task As Task)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
BC30456: 'AwaitOnCompleted' is not a member of 'AsyncVoidMethodBuilder'.
Await task
~~~~~~~~~~
</expected>)
End Sub
<Fact, WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")>
Public Sub MethodGroupWithConversionNoSpill()
Dim source = <compilation name="Async">
<file name="a.vb">
Imports System
Imports System.Threading.Tasks
Public Class AsyncBug
Public Shared Sub Main()
AsyncBug.Boom().GetAwaiter().GetResult()
End Sub
Public Async Shared Function Boom() As Task
Dim func As Func(Of Type) = Addressof (Await Task.FromResult(1)).GetType
Console.WriteLine(func())
End Function
End Class
</file>
</compilation>
Dim expectedOutput = <![CDATA[System.Int32]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(13734, "https://github.com/dotnet/roslyn/issues/13734")>
Public Sub MethodGroupConversionWithSpill()
Dim source = <compilation name="Async">
<file name="a.vb">
imports System.Threading.Tasks
imports System
imports System.Linq
imports System.Collections.Generic
class Program
class SomeClass
Public Function Method(value as Integer) as Boolean
Return value Mod 2 = 0
End Function
End Class
private Async Function Danger() as Task(Of SomeClass)
await Task.Yield()
return new SomeClass()
End Function
Async function Killer() as Task(Of IEnumerable(Of Boolean))
Return {1, 2, 3, 4, 5}.Select(AddressOf (Await Danger()).Method)
End Function
Shared Sub Main(args As String())
For Each b in new Program().Killer().GetAwaiter().GetResult()
Console.WriteLine(b)
Next
End Sub
End Class
</file>
</compilation>
Dim expectedOutput = <![CDATA[False
True
False
True
False
]]>
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
<Fact, WorkItem(19831, "https://github.com/dotnet/roslyn/issues/19831")>
Public Sub CaptureAssignedInOuterFinally()
Dim source = <compilation name="Async">
<file name="a.vb">
imports System.Threading.Tasks
imports System
Module Module1
Sub Main()
Test().Wait()
System.Console.WriteLine("success")
End Sub
Async Function Test() As Task
Dim obj = New Object()
Try
For i = 0 To 3
' NRE on second iteration
obj.ToString()
Await Task.Yield()
Next
Finally
obj = Nothing
End Try
End Function
End Module
</file>
</compilation>
Dim expectedOutput = "success"
Dim compilation = CompilationUtils.CreateEmptyCompilationWithReferences(source, references:=LatestVbReferences, options:=TestOptions.DebugExe)
CompileAndVerify(compilation, expectedOutput:=expectedOutput)
CompileAndVerify(compilation.WithOptions(TestOptions.ReleaseExe), expectedOutput:=expectedOutput)
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenAsyncTests.vb
|
Visual Basic
|
apache-2.0
| 288,341
|
' 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.[Text]
Imports System.Collections.Generic
Imports System.Linq
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Imports Xunit
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class SimpleFlowTests
Inherits FlowTestBase
<Fact>
Public Sub TestUninitializedIntegerLocal()
Dim program = <compilation name="TestUninitializedIntegerLocal">
<file name="a.b">
Module Module1
Sub Goo(z As Integer)
Dim x As Integer
If z = 2 Then
Dim y As Integer = x : x = y ' ok to use unassigned integer local
Else
dim y as integer = x : x = y ' no diagnostic in unreachable code
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestUnusedIntegerLocal()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Module Module1
Public Sub SubWithByRef(ByRef i As Integer)
End Sub
Sub TestInitialized1()
Dim x as integer = 1 ' No warning for a variable assigned a value but not used
Dim i1 As Integer
Dim i2 As Integer
i2 = i1 ' OK to use an uninitialized integer. Spec says all variables are initialized
Dim i3 As Integer
SubWithByRef(i3) ' Ok to pass an uninitialized integer byref
Dim i4 As Integer ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
<expected>
BC42024: Unused local variable: 'i4'.
Dim i4 As Integer ' Warning - unused local
~~
</expected>)
End Sub
<Fact>
Public Sub TestStructure1()
Dim program = <compilation name="TestStructure1">
<file name="a.b">
Module Module1
Structure s1
Dim i As Integer
Dim o As Object
End Structure
Public Sub SubWithByRef(ByRef i As s1, j as integer)
End Sub
Sub TestInitialized1()
Dim i1 As s1
Dim i2 As s1
i2 = i1 ' Warning- use of uninitialized variable
Dim i3 As s1
SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable
Dim i4 As s1 ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42109: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
i2 = i1 ' Warning- use of uninitialized variable
~~
BC42108: Variable 'i3' is passed by reference before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
SubWithByRef(j := 1, i := i3) ' Warning- use of uninitialized variable
~~
BC42024: Unused local variable: 'i4'.
Dim i4 As s1 ' Warning - unused local
~~
</expected>))
End Sub
<Fact>
Public Sub TestObject1()
Dim program = <compilation name="TestObject1">
<file name="a.b">
Module Module1
Class C1
Public i As Integer
Public o As Object
End Class
Public Sub SubWithByRef(ByRef i As C1)
End Sub
Sub TestInitialized1()
Dim i1 As C1
Dim i2 As C1
i2 = i1 ' Warning- use of uninitialized variable
Dim i3 As MyClass
SubWithByRef(i3) ' Warning- use of uninitialized variable
Dim i4 As C1 ' Warning - unused local
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'i1' is used before it has been assigned a value. A null reference exception could result at runtime.
i2 = i1 ' Warning- use of uninitialized variable
~~
BC42104: Variable 'i3' is used before it has been assigned a value. A null reference exception could result at runtime.
SubWithByRef(i3) ' Warning- use of uninitialized variable
~~
BC42024: Unused local variable: 'i4'.
Dim i4 As C1 ' Warning - unused local
~~
</expected>))
End Sub
<Fact()>
Public Sub LambdaInUnimplementedPartial_1()
Dim program = <compilation name="LambdaInUnimplementedPartial_1">
<file name="a.b">
Imports System
Partial Class C
Partial Private Shared Sub Goo(a As action)
End Sub
Public Shared Sub Main()
Goo(DirectCast(Sub()
Dim x As Integer
Dim y As Integer = x
End Sub, Action))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs, (<errors></errors>))
End Sub
<Fact()>
Public Sub LambdaInUnimplementedPartial_2()
Dim program = <compilation name="LambdaInUnimplementedPartial_2">
<file name="a.b">
Imports System
Partial Class C
Partial Private Shared Sub Goo(a As action)
End Sub
Public Shared Sub Main()
Goo(DirectCast(Sub()
Dim x As Integer
End Sub, Action))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42024: Unused local variable: 'x'.
Dim x As Integer
~
</errors>))
End Sub
<WorkItem(722619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722619")>
<Fact()>
Public Sub Bug_722619()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module SubMod
Sub Main()
Dim x As Exception
Try
Throw New DivideByZeroException
L1:
'COMPILEWARNING: BC42104, "x"
Console.WriteLine(x.Message)
Catch ex As DivideByZeroException
GoTo L1
Finally
x = New Exception("finally")
End Try
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(x.Message)
~
</errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575a()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestNone
Structure Str1(Of T)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575b()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestStruct
Structure Str1(Of T As Structure)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575c()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestClass
Structure Str1(Of T As Class)
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
o = s1
~~
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
o = s2.x
~~~~
</errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575d()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Module TestNewAndDisposable
Structure Str1(Of T As {IDisposable, New})
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1(Of T)
o = s1
Dim s2 As Str1(Of T)
o = s2.x
Dim s3 As Str1(Of T)
s3.x = Nothing
o = s3.x
Dim s4 As Str1(Of T)
s4.x = Nothing
o = s4
End Sub
End Structure
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(722575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722575")>
<Fact()>
Public Sub Bug_722575e()
Dim program =
<compilation>
<file name="a.b">
Imports System
Friend Class TestNone(Of T)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestStruct(Of T As Structure)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestClass(Of T As Class)
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
Friend Class TestNewAndDisposable(Of T As {IDisposable, New})
Structure Str1
Dim x As T
Sub goo()
Dim o As Object
Dim s1 As Str1
o = s1
Dim s2 As Str1
o = s2.x
Dim s3 As Str1
s3.x = Nothing
o = s3.x
Dim s4 As Str1
s4.x = Nothing
o = s4
End Sub
End Structure
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42109: Variable 's1' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
o = s1
~~
BC42104: Variable 'x' is used before it has been assigned a value. A null reference exception could result at runtime.
o = s2.x
~~~~
</errors>)
End Sub
<WorkItem(617061, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/617061")>
<Fact()>
Public Sub Bug_617061()
Dim program =
<compilation>
<file name="a.b">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Sub Main(args As String())
Dim a(100) As MEMORY_BASIC_INFORMATION
Dim b = From x In a Select x.BaseAddress
End Sub
End Module
Structure MEMORY_BASIC_INFORMATION
Dim BaseAddress As UIntPtr
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, references:={SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp, <errors></errors>)
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221a()
Dim program =
<compilation name="TestBug12221a">
<file name="a.b">
Imports System
Structure SS
Public S As String
End Structure
Module Program222
Sub Main(args As String())
Dim s As SS
Dim dict As New Dictionary(Of String, SS)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42109: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime. Make sure the structure or all the reference members are initialized before use
If dict.TryGetValue("", s) Then
~
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221b()
Dim program =
<compilation name="TestBug12221b">
<file name="a.b">
Imports System
Structure SS
Public S As Integer
End Structure
Module Program222
Sub Main(args As String())
Dim s As SS
Dim dict As New Dictionary(Of String, SS)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221c()
Dim program =
<compilation name="TestBug12221c">
<file name="a.b">
Module Program222
Interface I
End Interface
Sub Main(Of T As I)(args As String())
Dim s As T
Dim dict As New Dictionary(Of String, T)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<WorkItem(544072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544072")>
<Fact()>
Public Sub TestBug12221d()
Dim program =
<compilation name="TestBug12221d">
<file name="a.b">
Module Program222
Sub Main(Of T As Class)(args As String())
Dim s As T
Dim dict As New Dictionary(Of String, T)
If dict.TryGetValue("", s) Then
End If
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 's' is used before it has been assigned a value. A null reference exception could result at runtime.
If dict.TryGetValue("", s) Then
~
</expected>))
End Sub
<Fact()>
Public Sub TestReachable1()
Dim program = <compilation name="TestReachable1">
<file name="a.b">
Imports System
Module Module1
Sub TestUnreachable1()
Dim i As Integer ' Dev10 Warning - unused local
Return
Dim j As Integer ' Dev10 No warning because this is unreachable
Console.WriteLine(i, j)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestReachable2()
Dim program = <compilation name="TestReachable2">
<file name="a.b">
Imports System
Module Module1
Sub TestUnreachable1()
Dim i As Integer ' Dev10 Warning - unused local
Return
Dim j As Integer = 1 ' Dev10 No warning because this is unreachable
Console.WriteLine(i, j)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestGoto1()
Dim program = <compilation name="TestGoto1">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
l1:
If false Then
o2 = "a"
end if
GoTo l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime.
o1 = o2
~~
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable1()
Dim program = <compilation name="LambdaEntryPointIsReachable1">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim x As Integer = i
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable2()
Dim program = <compilation name="LambdaEntryPointIsReachable2">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub LambdaEntryPointIsReachable3()
Dim program = <compilation name="LambdaEntryPointIsReachable3">
<file name="a.b">
Imports System
Public Module Program
Public Sub Main(args As String())
Dim i As Integer
Return
Dim a As action = DirectCast(Sub()
Dim j As Integer = i + j
Return
Dim k = j
End Sub, action)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
</expected>))
End Sub
<Fact>
Public Sub TestDoLoop1()
Dim program = <compilation name="TestDoLoop1">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
l1:
do
exit do
o2 = "a"
loop
GoTo l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<expected>
BC42104: Variable 'o2' is used before it has been assigned a value. A null reference exception could result at runtime.
o1 = o2
~~
</expected>))
End Sub
<Fact>
Public Sub TestDoLoop2()
Dim program = <compilation name="TestDoLoop2">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
Dim o1, o2 As Object
GoTo l1
l2:
o1 = o2
return
do
l1:
o2 = "a"
exit do
loop
goto l2
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestBlocks()
Dim program = <compilation name="TestDoLoop2">
<file name="a.b">
Imports System
Module Module1
Sub TestGoto1()
do until false
while false
end while
loop
do while true
while true
end while
loop
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub RefParameter01()
Dim program = <compilation name="RefParameter01">
<file name="a.b">
class Program
public shared Sub Main(args as string())
dim i as string
F(i) ' use of unassigned local variable 'i'
end sub
shared sub F(byref i as string)
end sub
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Assert.NotEmpty(Me.FlowDiagnostics(comp).AsEnumerable().Where(Function(e) e.Severity = DiagnosticSeverity.[Warning]))
End Sub
<Fact>
Public Sub FunctionDoesNotReturnAValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
class Program
public function goo() as integer
end function
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42353: Function 'goo' doesn't return a value on all code paths. Are you missing a 'Return' statement?
end function
~~~~~~~~~~~~
</errors>))
End Sub
<Fact>
Public Sub FunctionReturnsAValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
class Program
public function goo() as integer
return 0
end function
public function bar() as integer
bar = 0
end function
end class</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
</errors>))
End Sub
<WorkItem(540687, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540687")>
<Fact>
Public Sub FunctionDoesNotReturnAnEnumValue()
Dim program = <compilation name="FunctionDoesNotReturnAValue">
<file name="a.b">
Imports System
Imports System.Collections.Generic
Imports System.Linq
Enum e1
a
b
End Enum
Module Program
Function f As e1
End Function
Sub Main(args As String())
Dim x As Func(Of e1) = Function()
End Function
End Sub
End Module</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
<![CDATA[
BC42353: Function 'f' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
BC42353: Function '<anonymous method>' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Function
~~~~~~~~~~~~
]]>
</errors>))
End Sub
<WorkItem(541005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541005")>
<Fact>
Public Sub TestLocalsInitializedByAsNew()
Dim program = <compilation name="TestLocalsInitializedByAsNew">
<file name="a.b">
Module Module1
Class C
Public Sub New()
End Class
End Class
Sub Goo()
Dim x, y, z as New C
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(542817, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542817")>
<Fact>
Public Sub ConditionalStateInsideQueryLambda()
Dim program = <compilation name="ConditionalStateInsideQueryLambda">
<file name="a.b">
Imports System.Linq
Class PEModuleSymbol
Function IsNoPiaLocalType(i As Integer) As Boolean
End Function
End Class
Class PENamedTypeSymbol
Friend Sub New(
moduleSymbol As PEModuleSymbol,
containingNamespace As PENamespaceSymbol,
typeRid As Integer
)
End Sub
End Class
Class PENamespaceSymbol
Private Sub LazyInitializeTypes(types As IEnumerable(Of IGrouping(Of String, Integer)))
Dim moduleSymbol As PEModuleSymbol = Nothing
Dim children As IEnumerable(Of PENamedTypeSymbol)
children = (From g In types, t In g
Where Not moduleSymbol.IsNoPiaLocalType(t)
Select New PENamedTypeSymbol(moduleSymbol, Me, t))
End Sub
End Class
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim diags = comp.GetDiagnostics()
End Sub
<Fact>
Public Sub TestSelectCase_CaseClauseExpression_NeverConstantExpr()
Dim program = <compilation name="TestUninitializedIntegerLocal">
<file name="a.b">
<![CDATA[
Imports System
Module M1
Sub Main()
For x = 0 to 11
Console.Write(x.ToString() + ":")
Test(x)
Next
End Sub
Sub Test(number as Integer)
' No unreachable code warning for any case block
Select Case 1
Case 1
Console.WriteLine("Equal to 1")
Case Is < 1
Console.WriteLine("Less than 1")
Case 1 To 5
Console.WriteLine("Between 2 and 5, inclusive")
Case 6, 7, 8
Console.WriteLine("Between 6 and 8, inclusive")
Case 9 To 10
Console.WriteLine("Equal to 9 or 10")
Case Else
Console.WriteLine("Greater than 10")
End Select
End Sub
End Module
]]>
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_NoCaseBlocks_NoUnusedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim number as Integer = 10
Select Case number ' no unused integer warning even though select statement is optimized away
End Select
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_UninitializedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable.
obj = new Object()
Case Else
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(obj) ' Use of uninitialized local warning
~~~
</errors>))
End Sub
<Fact>
Public Sub TestSelectCase_NoUninitializedLocalWarning()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1
obj = new Object()
Case Is > 1, 2
obj = new Object()
Case 1 To 10
obj = new Object()
Case Else
obj = new Object()
End Select
Console.WriteLine(obj)
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
Public Sub TestSelectCase_UninitializedLocalWarning_InvalidRangeClause()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 10 To 1 ' Invalid range clause
obj = new Object()
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
CompilationUtils.AssertTheseDiagnostics(errs,
(<errors>
BC42104: Variable 'obj' is used before it has been assigned a value. A null reference exception could result at runtime.
Console.WriteLine(obj) ' Use of uninitialized local warning
~~~
</errors>))
End Sub
<Fact>
Public Sub TestSelectCase_NoUninitializedLocalWarning_JumpToAnotherCaseBlock()
Dim program = <compilation name="TestUnusedIntegerLocal">
<file name="a.b">
Imports System
Module M1
Sub Main()
Dim obj as Object
Select Case 1
Case 1 ' Case clause expression are never compile time constants, hence Case Else is reachable.
Label1:
obj = new Object()
Case Else
Goto Label1
End Select
Console.WriteLine(obj) ' Use of uninitialized local warning
End Sub
End Module
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")>
<Fact()>
Public Sub TestSelectCase_Error_MissingCaseStatement()
Dim program = <compilation name="TestSelectCase_Error_MissingCaseStatement">
<file name="a.b">
Imports System
Module Program
Sub Main(args As String())
Dim x As New myclass1
Select x
Ca
End Sub
End Module
Structure myclass1
Implements IDisposable
Public Sub dispose() Implements IDisposable.Dispose
End Sub
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<WorkItem(543095, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543095")>
<Fact()>
Public Sub TestSelectCase_Error_MissingCaseExpression()
Dim program = <compilation name="TestSelectCase_Error_MissingCaseExpression">
<file name="a.b">
Imports System
Module Program
Sub Main(args As String())
Dim x As New myclass1
Select x
Case
End Select
End Sub
End Module
Structure myclass1
Implements IDisposable
Public Sub dispose() Implements IDisposable.Dispose
End Sub
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program)
Dim errs = Me.FlowDiagnostics(comp)
errs.AssertNoErrors()
End Sub
<Fact>
<WorkItem(100475, "https://devdiv.visualstudio.com/defaultcollection/DevDiv/_workitems?_a=edit&id=100475")>
<WorkItem(529405, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529405")>
Public Sub TestThrowDoNotReportUnreachable()
Dim program =
<compilation>
<file name="a.b">
Imports System
Class Test
Sub Method1()
Throw New Exception()
Return
End Sub
Function Method2(x As Integer) As Integer
If x < 0 Then
Return -1
Else
Return 1
End If
Throw New System.InvalidOperationException()
End Function
End Class
</file>
</compilation>
CompilationUtils.CreateCompilationWithMscorlib40(program).VerifyDiagnostics()
End Sub
<WorkItem(531310, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531310")>
<Fact()>
Public Sub Bug_17926()
Dim program =
<compilation>
<file name="a.b">
Imports System
Imports System.Collections.Generic
Module Module1
Public Function RemoveTextWriterTraceListener() As Boolean
Try
RemoveTextWriterTraceListener = False
'Return true to indicate that the TextWriterTraceListener was removed
RemoveTextWriterTraceListener = True
Catch e As Exception
Console.WriteLine("")
End Try
Return RemoveTextWriterTraceListener
End Function
End Module
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation, <errors></errors>)
End Sub
<WorkItem(531529, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531529")>
<Fact()>
Public Sub Bug_18255()
Dim program =
<compilation>
<file name="a.b">
Imports System
Public Class TestState
ReadOnly Property IsImmediateWindow As Boolean
Get
Return IsImmediateWindow
End Get
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
</errors>)
End Sub
<WorkItem(531530, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531530")>
<Fact()>
Public Sub Bug_18256()
Dim program =
<compilation>
<file name="a.b">
Imports System
Structure SSSS1
End Structure
Structure SSSS2
Private s As String
End Structure
Enum e1
a
End Enum
Class CCCCCC
Public ReadOnly Property Prop1 As System.Threading.CancellationToken
Get
End Get
End Property
Public ReadOnly Property Prop2 As SSSS1
Get
End Get
End Property
Public ReadOnly Property Prop3 As SSSS2
Get
End Get
End Property
Public ReadOnly Property Prop4 As e1
Get
End Get
End Property
Public ReadOnly Property Prop5 As String
Get
End Get
End Property
Public ReadOnly Property Prop6 As Integer
Get
End Get
End Property
End Class
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(compilation,
<errors>
BC42107: Property 'Prop3' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Get
~~~~~~~
BC42355: Property 'Prop4' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Get
~~~~~~~
BC42107: Property 'Prop5' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
End Get
~~~~~~~
BC42355: Property 'Prop6' doesn't return a value on all code paths. Are you missing a 'Return' statement?
End Get
~~~~~~~
</errors>)
End Sub
<Fact(), WorkItem(531237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531237")>
Public Sub Bug17796()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Imports System, System.Runtime.CompilerServices
Public Module Program
Sub Main()
End Sub
Interface ITextView
Event Closed As EventHandler
End Interface
<Extension()>
Public Sub AddOneTimeCloseHandler(ByVal view As ITextView, ByVal del As Action)
Dim del2 As EventHandler = Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del2
End Sub
Dim del3 As Object = Function() As Object
del()
return del3
End Function.Invoke()
Dim del4 As EventHandler
del4 = Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del4
End Sub
Dim del5 As Object
del5 = Function() As Object
del()
return del5
End Function.Invoke()
Dim del6 As EventHandler = DirectCast(TryCast(CType(
Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del6
End Sub, EventHandler), EventHandler), EventHandler)
Dim del7 As EventHandler = (Sub(notUsed1, notUsed2)
del()
RemoveHandler view.Closed, del7
End Sub)
End Sub
End Module
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntimeAndReferences(program, {SystemCoreRef})
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC42104: Variable 'del3' is used before it has been assigned a value. A null reference exception could result at runtime.
return del3
~~~~
BC42104: Variable 'del5' is used before it has been assigned a value. A null reference exception could result at runtime.
return del5
~~~~
</errors>)
End Sub
<Fact(), WorkItem(530465, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530465")>
Public Sub SuppressErrorReportingForSynthesizedLocalSymbolWithEmptyName()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Module Module1
Sub Main()
Dim
End Sub
Sub M()
Static
End Sub
End Module
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(comp,
<errors>
BC30203: Identifier expected.
Dim
~
BC30203: Identifier expected.
Static
~
</errors>)
End Sub
<Fact(), WorkItem(2896, "https://github.com/dotnet/roslyn/issues/2896")>
Public Sub Issue2896()
Dim program = <compilation>
<file name="a.b"><![CDATA[
Public Class Test
Private _f1 As Boolean = Not Me.DaysTimesInputEnable
Private _f2 As Boolean = Me.DaysTimesInputEnable
Public ReadOnly Property DaysTimesInputEnable As Boolean
Get
Return True
End Get
End Property
End Class
]]></file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(program)
CompilationUtils.AssertTheseDiagnostics(comp)
End Sub
<Fact>
Public Sub LogicalExpressionInErroneousObjectInitializer()
Dim program = <compilation>
<file name="a.b">
Public Class Class1
Sub Test()
Dim x As S1
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
End Sub
End Class
Public Structure S1
Public F1 As Boolean
Public F2 As Boolean
Public F3 As Object
End Structure
</file>
</compilation>
Dim comp = CompilationUtils.CreateCompilationWithMscorlib40(program, options:=TestOptions.DebugDll)
comp.AssertTheseDiagnostics(
<expected>
BC30002: Type 'C1' is not defined.
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
~~
BC42104: Variable 'F3' is used before it has been assigned a value. A null reference exception could result at runtime.
Dim y As New C1() With {.F1 = x.F1 AndAlso x.F2, .F3 = x.F3}
~~~~
</expected>
)
End Sub
End Class
End Namespace
|
OmarTawfik/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/FlowAnalysis/FlowDiagnosticTests.vb
|
Visual Basic
|
apache-2.0
| 58,209
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.Organizing.Organizers
Friend Partial Class MemberDeclarationsOrganizer
Public Class Comparer
Implements IComparer(Of StatementSyntax)
' TODO(cyrusn): Allow users to specify the ordering they want
Public Enum OuterOrdering
Fields
EventFields
Constructors
Destructors
Properties
Events
Indexers
Operators
ConversionOperators
Methods
Types
Remaining
End Enum
Public Enum InnerOrdering
StaticInstance
Accessibility
Name
End Enum
Public Enum Accessibility
[Public]
[Protected]
[Friend]
[Private]
End Enum
Public Function Compare(x As StatementSyntax, y As StatementSyntax) As Integer Implements IComparer(Of StatementSyntax).Compare
If x Is y Then
Return 0
End If
Dim xOuterOrdering = GetOuterOrdering(x)
Dim yOuterOrdering = GetOuterOrdering(y)
Dim value = xOuterOrdering - yOuterOrdering
If value <> 0 Then
Return value
End If
If xOuterOrdering = OuterOrdering.Remaining Then
Return 1
ElseIf yOuterOrdering = OuterOrdering.Remaining Then
Return -1
End If
If xOuterOrdering = OuterOrdering.Fields OrElse yOuterOrdering = OuterOrdering.Fields Then
' Fields with initializers can't be reordered relative to
' themselves due to ordering issues.
Dim xHasInitializer = DirectCast(x, FieldDeclarationSyntax).Declarators.Any(Function(v) v.Initializer IsNot Nothing)
Dim yHasInitializer = DirectCast(y, FieldDeclarationSyntax).Declarators.Any(Function(v) v.Initializer IsNot Nothing)
If xHasInitializer AndAlso yHasInitializer Then
Return 0
End If
End If
Dim xIsShared = x.GetModifiers().Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
Dim yIsShared = y.GetModifiers().Any(Function(t) t.Kind = SyntaxKind.SharedKeyword)
value = Comparer(Of Boolean).Default.Inverse().Compare(xIsShared, yIsShared)
If value <> 0 Then
Return value
End If
Dim xAccessibility = GetAccessibility(x)
Dim yAccessibility = GetAccessibility(y)
value = xAccessibility - yAccessibility
If value <> 0 Then
Return value
End If
Dim xName = If(ShouldCompareByName(x), TryCast(x, DeclarationStatementSyntax).GetNameToken(), Nothing)
Dim yName = If(ShouldCompareByName(x), TryCast(y, DeclarationStatementSyntax).GetNameToken(), Nothing)
value = TokenComparer.NormalInstance.Compare(xName, yName)
If value <> 0 Then
Return value
End If
' Their names were the same. Order them by arity at this point.
Return x.GetArity() - y.GetArity()
End Function
Private Shared Function GetAccessibility(x As StatementSyntax) As Accessibility
Dim xModifiers = x.GetModifiers()
If xModifiers.Any(Function(t) t.Kind = SyntaxKind.PublicKeyword) Then
Return Accessibility.Public
ElseIf xModifiers.Any(Function(t) t.Kind = SyntaxKind.FriendKeyword) Then
Return Accessibility.Friend
ElseIf xModifiers.Any(Function(t) t.Kind = SyntaxKind.ProtectedKeyword) Then
Return Accessibility.Protected
Else
' Only fields are private in VB. All other members are public
If x.Kind = SyntaxKind.FieldDeclaration Then
Return Accessibility.Private
Else
Return Accessibility.Public
End If
End If
End Function
Private Function GetOuterOrdering(x As StatementSyntax) As OuterOrdering
Select Case x.Kind
Case SyntaxKind.FieldDeclaration
Return OuterOrdering.Fields
Case SyntaxKind.ConstructorBlock
Return OuterOrdering.Constructors
Case SyntaxKind.PropertyBlock
Return OuterOrdering.Properties
Case SyntaxKind.EventBlock
Return OuterOrdering.Events
Case SyntaxKind.OperatorBlock
Return OuterOrdering.Operators
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
Return OuterOrdering.Methods
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.StructureBlock,
SyntaxKind.EnumBlock,
SyntaxKind.DelegateSubStatement,
SyntaxKind.DelegateFunctionStatement
Return OuterOrdering.Types
Case Else
Return OuterOrdering.Remaining
End Select
End Function
Private Shared Function ShouldCompareByName(x As StatementSyntax) As Boolean
' Constructors and operators should not be sorted by name.
Select Case x.Kind
Case SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock
Return False
Case Else
Return True
End Select
End Function
End Class
End Class
End Namespace
|
mmitche/roslyn
|
src/Features/VisualBasic/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.Comparer.vb
|
Visual Basic
|
apache-2.0
| 6,633
|
Public Class frmShop
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Me.Hide()
My.Forms.MainMenu.Show() 'go to main menu
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Me.Hide()
My.Forms.frmLevel.Show() 'go to level select
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
End 'quit :(
End Sub
Private Sub frmShop_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lblPlayerScore.Text = Score
lblPlayerName.Text = PlayerName 'load the player name
End Sub
Private Sub btnUpSpeed_Click(sender As Object, e As EventArgs) Handles btnUpSpeed.Click
If Score = 20 Then 'makes sure you have funds
Score -= 20 'takes away the funds
UpSpeed = True 'sets boolean
btnUpSpeed.Enabled = False 'disables button
btnUpSpeed.Text = "Upgrade Speed - Purchased" 'changes text to show its been purchased
Else MsgBox("ERROR: Insufficient funds.") 'error if you don't have enough money
End If
End Sub
Private Sub btnWinPts_Click(sender As Object, e As EventArgs) Handles btnWinPts.Click
If Score = 30 Then 'makes sure you have funds
Score -= 30 'takes away the funds
UpWinPts = True 'sets boolean
btnWinPts.Enabled = False 'disables button
btnWinPts.Text = "Upgrade Win Points - Purchased" 'changes text to show its been purchased
Else MsgBox("ERROR: Insufficient funds.") 'error if you don't have enough money
End If
End Sub
Private Sub btnDblPts_Click(sender As Object, e As EventArgs) Handles btnDblPts.Click
If Score = 50 Then 'makes sure you have funds
Score -= 50 'takes away the funds
UpDblPts = True 'sets boolean
btnDblPts.Enabled = False 'disables button
btnDblPts.Text = "Upgrade Double Points - Purchased" 'changes text to show its been purchased
Else MsgBox("ERROR: Insufficient funds.") 'error if you don't have enough money
End If
End Sub
End Class
|
Ayush-G/MinionsMathGame
|
MinionsMath-master/frmMinionsMath/frmShop.vb
|
Visual Basic
|
mit
| 2,204
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("com.deuxhuithuit.ImageColorer.WebApp")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Deux Huit Huit Inc.")>
<Assembly: AssemblyProduct("com.deuxhuithuit.ImageColorer.WebApp")>
<Assembly: AssemblyCopyright("Copyright © Deux Huit Huit Inc. 2012")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("7fff1fff-1d6c-49b2-b736-df783fa6c4b6")>
<Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
DeuxHuitHuit/ImageColorer
|
com.deuxhuithuit.ImageColorer.WebApp/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 907
|
'Namespace System
''' <summary> Static utility methods for dealing with the Windows registry. </summary>
Public NotInheritable Class RegUtils
#Region "Private Fields"
'Private Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger(MyClass.GetType.FullName)
Private Shared Logger As Rstyx.LoggingConsole.Logger = Rstyx.LoggingConsole.LogBox.getLogger("Rstyx.Utilities.RegUtils")
#End Region
#Region "Constructor"
Private Sub New
'Hides the Constructor
End Sub
#End Region
#Region "Static Methods"
''' <summary> Tests wether a given registry key exists. </summary>
''' <param name="KeyPathName"> A registry key name, that begins with a valid registry root name and may or may not end with a backslash. </param>
''' <returns> True, if the key exists AND can be accessed with actual permissions, otherwise False. </returns>
''' <remarks> Example for a registry key name: "HKEY_CURRENT_USER\MyTestKey\Key2\Key3". </remarks>
Public Shared Function KeyExists(ByVal KeyPathName As String) As Boolean
Dim success As Boolean = False
Try
Dim TestValue As Object = Microsoft.Win32.Registry.GetValue(KeyPathName, "", "default")
success = (TestValue IsNot Nothing)
Catch ex as System.ArgumentException
Logger.logError(ex, "KeyExists(): ungültiger Stammschlüsselname in ValuePathName " & KeyPathName)
Catch ex as System.IO.IOException
Logger.logError(ex, "KeyExists(): Der RegistryKey " & KeyPathName & " wurde zum Löschen markiert.")
Catch ex as System.Security.SecurityException
Logger.logError("KeyExists(): Es fehlt die Berechtigung, um aus dem Registrierungsschlüssel " & KeyPathName & " zu lesen.")
Catch ex as System.Exception
Logger.logError(ex, "KeyExists(): unbekannter Fehler")
End Try
Return success
End Function
''' <summary> Tests wether a given registry value name exists. </summary>
''' <param name="ValuePathName"> A registry value name with full path, that begins with a valid registry root name. </param>
''' <returns> True, if the value exists AND can be accessed with actual permissions, otherwise False. </returns>
''' <remarks>
''' Example for a registry key name: "HKEY_CURRENT_USER\MyTestKey\Key2\Key3".
''' If it ends with a backslash, the default value is tested.
''' </remarks>
Public Shared Function ValueExists(ByVal ValuePathName As String) As Boolean
Const UniqValue As String = "@mns4u6e8le9k6fe3rkjui548@"
Dim success As Boolean = false
Dim ValueName As String = getValueName(ValuePathName)
Dim KeyPathName As String = getKeyPathName(ValuePathName)
Try
Dim TestValue As Object = Microsoft.Win32.Registry.GetValue(KeyPathName, ValueName, UniqValue)
success = ((TestValue isNot Nothing) AndAlso (not TestValue.ToString().Equals(UniqValue)))
Catch ex as System.ArgumentException
Logger.logError(ex, "ValueExists(): ungültiger Stammschlüsselname in ValuePathName " & ValuePathName)
Catch ex as System.IO.IOException
Logger.logError(ex, "ValueExists(): Der RegistryKey " & KeyPathName & " wurde zum Löschen markiert.")
Catch ex as System.Security.SecurityException
Logger.logError("ValueExists(): Es fehlt die Berechtigung, um aus dem Registrierungsschlüssel " & KeyPathName & " zu lesen.")
Catch ex as System.Exception
Logger.logError(ex, "ValueExists(): unbekannter Fehler")
End Try
Return success
End Function
''' <summary> Failure tolerant reading: Returns the value of the given ValuePathName if possible, otherwise Nothing. </summary>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <returns> The value of the given ValuePathName if possible, otherwise Nothing. </returns>
Public Shared Function getValue(ByVal ValuePathName As String) As Object
Dim Value As Object = Nothing
If (ValueExists(ValuePathName)) Then
Value = Microsoft.Win32.Registry.GetValue(getKeyPathName(ValuePathName), getValueName(ValuePathName), Nothing)
End If
Return Value
End Function
''' <summary> Failure tolerant reading: Returns the value of the given ValuePathName as string if possible, otherwise Nothing. </summary>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <returns> The value of the given ValuePathName if possible, otherwise Nothing. </returns>
''' <remarks> This is only a short hand for using "getValue(Of String)(ValuePathName)". </remarks>
Public Shared Function getStringValue(ByVal ValuePathName As String) As String
Dim Value As String = Nothing
Try
Value = CStr(getValue(ValuePathName))
Catch ex As System.Exception
Logger.logDebug("getStringValue(): Der Wert " & ValuePathName & " konnte nicht in einen String konvertiert werden.")
End Try
Return Value
End Function
''' <summary> Failure tolerant reading: Returns the value of the given ValuePathName as the given Type if possible, otherwise the initial value of this type. </summary>
''' <typeparam name="T"> Type of the return value. </typeparam>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <returns> The value of the given ValuePathName as the given Type if possible, otherwise the default value of this type. </returns>
''' <remarks>
''' If any error occurs while retrieving or converting the vaue, then the initial value of the given Type is returned.
''' CAUTION: I.e. in case of basic numeric types a return value of "0" could mean both that this value has been read successfully or an error has been occured.
''' </remarks>
Public Shared Function getValue(Of T)(ByVal ValuePathName As String) As T
Dim ValueO As Object = Nothing
Dim ValueT As T = Nothing
Try
ValueO = getValue(ValuePathName)
ValueT = CType(ValueO, T)
Catch ex As System.Exception
Logger.logDebug("getValue(): Der Wert " & ValuePathName & " konnte nicht in den Typ " & GetType(T).ToString() & " konvertiert werden.")
End Try
Return ValueT
End Function
''' <summary> Failure tolerant writing: Sets the value of the given ValuePathName if possible. </summary>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <param name="Value"> The value to write into the registry. </param>
''' <param name="ValueKind"> The kind of value to set. </param>
''' <returns> True, if the value has been set successfully, otherwise false. </returns>
Public Shared Function setValue(ByVal ValuePathName As String, byVal Value As Object, ValueKind As Microsoft.Win32.RegistryValueKind) As Boolean
Dim success As Boolean = false
Try
Microsoft.Win32.Registry.SetValue(getKeyPathName(ValuePathName), getValueName(ValuePathName), Value, ValueKind)
success = True
Catch ex As System.Exception
Logger.logError(ex, "setValue(): Fehler beim Schreiben des Wertes " & ValuePathName & ".")
End Try
Return success
End Function
''' <summary> Failure tolerant writing: Sets the string value of the given ValuePathName if possible. </summary>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <param name="Value"> The string value to write into the registry. </param>
''' <returns> True, if the value has been set successfully, otherwise false. </returns>
Public Shared Function setValue(ByVal ValuePathName As String, byVal Value As String) As Boolean
Return setValue(ValuePathName, Value,Microsoft.Win32.RegistryValueKind.String)
End Function
''' <summary> Gets the value name part from a full ValuePathName. </summary>
''' <param name="ValuePathName"> A registry value name with full path, that begins with a valid registry root name. </param>
''' <returns> The name of the value, which is the part beyond the last backslash. If empty, then it's the default value. </returns>
''' <remarks> If ValuePathName ends with a backslash, then an empty string is returned, which indicates the default value. </remarks>
Public Shared Function getValueName(ByVal ValuePathName As String) As String
Return ValuePathName.Right("\")
End function
''' <summary> Gets the key name part from a full ValuePathName. </summary>
''' <param name="ValuePathName"> A registry value name with full path, that begins with a valid registry root name. </param>
''' <returns> The path name of the key, which is the part until the last backslash (including backslash). </returns>
''' <remarks> If ValuePathName ends with a backslash, then the whole ValuePathName is returned. </remarks>
Public Shared Function getKeyPathName(ByVal ValuePathName As String) As String
Return ValuePathName.Left(ValuePathName.Length - getValueName(ValuePathName).Length)
End function
''' <summary> Extracts a path of an existing application from a registry string value. </summary>
''' <param name="ValuePathName"> A registry value name with full path. If it ends with a backslash, the default value is meant. </param>
''' <returns> The application path of an existing file, otherwise String.Empty. </returns>
''' <remarks>
''' <para>
''' If read value starts with a double quote, the string between quotes is recognized as path.
''' </para>
''' <para>
''' If read value doesn't starts with a double quote, the string until the first space is recognized as path.
''' </para>
''' </remarks>
Public Shared Function getApplicationPath(ByVal ValuePathName As String) As String
Dim AppPath As String = Nothing
Logger.logDebug("getApplicationPath(): Pfad\Name einer Programmdatei ermitteln aus RegistryValue '" & ValuePathName & "'.")
if (ValueExists(ValuePathName)) then
AppPath = getStringValue(ValuePathName)
If (AppPath.IsNotNull) Then
Logger.logDebug(StringUtils.sprintf("getApplicationPath(): Inhalt des RegistryValue: '%s'", AppPath))
AppPath = AppPath.Trim()
' extract Path:
if (AppPath.Left(1) = """") then
' Path is quoted => Path is string between quotes.
AppPath = AppPath.Substring("""", """", false)
else
' Path isn't quoted => Path is string from first character until first space or end.
AppPath = AppPath.Left(" ", false)
end if
end if
end if
Logger.logDebug("getApplicationPath(): Ermittelter Pfad\Name lautet: '" & AppPath & "'")
if (System.IO.File.Exists(AppPath)) then
Logger.logDebug("getApplicationPath(): OK - '" & AppPath & "' existiert.")
else
Logger.logDebug("getApplicationPath(): Datei '" & AppPath & "' existiert nicht!")
AppPath = String.Empty
end if
Return AppPath
End Function
#End Region
End Class
'End Namespace
' for jEdit: :collapseFolds=2::tabSize=4::indentSize=4:
|
rschwenn/Rstyx.Utilities
|
Utilities/source/_global/RegUtils.vb
|
Visual Basic
|
mit
| 13,974
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "fCortes_ExistenciaDepartamentosTodos"
'-------------------------------------------------------------------------------------------'
Partial Class fCortes_ExistenciaDepartamentosTodos
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(" SELECT Articulos.Cod_Dep, ")
loComandoSeleccionar.AppendLine(" Departamentos.Nom_Dep, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Act1) AS Exi_Act1, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Ped1) AS Exi_Ped1, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Act1-Renglones_Almacenes.Exi_Ped1) AS Exi_Dis1, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Por1) AS Exi_Por1, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Cot1) AS Exi_Cot1, ")
loComandoSeleccionar.AppendLine(" SUM(Renglones_Almacenes.Exi_Des1) AS Exi_Des1 ")
loComandoSeleccionar.AppendLine(" FROM Articulos, ")
loComandoSeleccionar.AppendLine(" Departamentos, ")
loComandoSeleccionar.AppendLine(" Renglones_Almacenes ")
loComandoSeleccionar.AppendLine(" WHERE Articulos.Cod_Art = Renglones_Almacenes.Cod_Art ")
loComandoSeleccionar.AppendLine(" AND Articulos.Cod_Dep = Departamentos.Cod_Dep ")
loComandoSeleccionar.AppendLine(" GROUP BY Articulos.Cod_Dep, ")
loComandoSeleccionar.AppendLine(" Departamentos.Nom_Dep ")
'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")
'Me.mCargarLogoEmpresa(loTablaLogo, "LogoEmpresa")
'-------------------------------------------------------------------------------------------------------
' Verificando si el select (tabla nº0) trae registros
'-------------------------------------------------------------------------------------------------------
If (laDatosReporte.Tables(0).Rows.Count <= 0) Then
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Información", _
"No se Encontraron Registros para los Parámetros Especificados. ", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Informacion, _
"350px", _
"200px")
End If
loObjetoReporte = cusAplicacion.goFormatos.mCargarInforme("fCortes_ExistenciaDepartamentosTodos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvfCortes_ExistenciaDepartamentosTodos.ReportSource = loObjetoReporte
Catch loExcepcion As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
"No se pudo Completar el Proceso: " & loExcepcion.Message, _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
"auto", _
"auto")
End Try
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' JJD: 19/04/10: Codigo inicial
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
fCortes_ExistenciaDepartamentosTodos.aspx.vb
|
Visual Basic
|
mit
| 5,035
|
' 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.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
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 Class Binder
Private Function BindLateBoundMemberAccess(node As SyntaxNode,
name As String,
typeArguments As TypeArgumentListSyntax,
receiver As BoundExpression,
containerType As TypeSymbol,
diagnostics As DiagnosticBag) As BoundExpression
Dim boundTypeArguments As BoundTypeArguments = BindTypeArguments(typeArguments, diagnostics)
Return BindLateBoundMemberAccess(node, name, boundTypeArguments, receiver, containerType, diagnostics)
End Function
Private Function BindLateBoundMemberAccess(node As SyntaxNode,
name As String,
boundTypeArguments As BoundTypeArguments,
receiver As BoundExpression,
containerType As TypeSymbol,
diagnostics As DiagnosticBag,
Optional suppressLateBindingResolutionDiagnostics As Boolean = False) As BoundExpression
receiver = AdjustReceiverAmbiguousTypeOrValue(receiver, diagnostics)
If OptionStrict = VisualBasic.OptionStrict.On Then
' "Option Strict On disallows late binding."
If Not suppressLateBindingResolutionDiagnostics Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_StrictDisallowsLateBinding)
End If
Dim children = ArrayBuilder(Of BoundExpression).GetInstance
If receiver IsNot Nothing Then
children.Add(receiver)
End If
If boundTypeArguments IsNot Nothing Then
children.Add(boundTypeArguments)
End If
Return BadExpression(node, children.ToImmutableAndFree, ErrorTypeSymbol.UnknownResultType)
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom AndAlso Not suppressLateBindingResolutionDiagnostics Then
ReportDiagnostic(diagnostics, node, ERRID.WRN_LateBindingResolution)
End If
Dim objType = Me.GetSpecialType(SpecialType.System_Object, node, diagnostics)
If receiver IsNot Nothing AndAlso
receiver.Kind = BoundKind.MeReference AndAlso
(IsMeOrMyBaseOrMyClassInSharedContext() OrElse IsInsideChainedConstructorCallArguments) Then
receiver = Nothing
End If
If receiver IsNot Nothing AndAlso Not receiver.IsLValue Then
receiver = MakeRValue(receiver, diagnostics)
End If
Return New BoundLateMemberAccess(node, name, containerType, receiver, boundTypeArguments, LateBoundAccessKind.Unknown, objType)
End Function
Private Function BindLateBoundInvocation(node As SyntaxNode,
group As BoundMethodOrPropertyGroup,
isDefaultMemberAccess As Boolean,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
diagnostics As DiagnosticBag) As BoundExpression
Dim memberName As String = If(isDefaultMemberAccess,
Nothing,
group.MemberName)
Dim typeArguments As BoundTypeArguments = group.TypeArguments
Dim containingType As TypeSymbol = group.ContainerOfFirstInGroup
Dim receiver As BoundExpression = AdjustReceiverAmbiguousTypeOrValue(group, diagnostics)
If receiver IsNot Nothing AndAlso
(receiver.Kind = BoundKind.TypeExpression OrElse receiver.Kind = BoundKind.NamespaceExpression) Then
receiver = Nothing
End If
Dim memberSyntax As SyntaxNode
Dim invocationSyntax = TryCast(node, InvocationExpressionSyntax)
If invocationSyntax IsNot Nothing Then
memberSyntax = If(invocationSyntax.Expression, group.Syntax)
Else
memberSyntax = node
End If
Dim lateMember = BindLateBoundMemberAccess(memberSyntax, memberName, typeArguments, receiver, containingType, diagnostics,
suppressLateBindingResolutionDiagnostics:=True) ' BindLateBoundInvocation will take care of the diagnostics.
If receiver IsNot Nothing AndAlso receiver.Type IsNot Nothing AndAlso receiver.Type.IsInterfaceType Then
ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, group), ERRID.ERR_LateBoundOverloadInterfaceCall1, memberName)
End If
Return BindLateBoundInvocation(node, group, lateMember, arguments, argumentNames, diagnostics)
End Function
Friend Function BindLateBoundInvocation(node As SyntaxNode,
groupOpt As BoundMethodOrPropertyGroup,
receiver As BoundExpression,
arguments As ImmutableArray(Of BoundExpression),
argumentNames As ImmutableArray(Of String),
diagnostics As DiagnosticBag,
Optional suppressLateBindingResolutionDiagnostics As Boolean = False) As BoundExpression
Debug.Assert(receiver IsNot Nothing AndAlso receiver.Kind <> BoundKind.TypeOrValueExpression)
Debug.Assert(groupOpt Is Nothing OrElse groupOpt.ReceiverOpt Is Nothing OrElse groupOpt.ReceiverOpt.Kind <> BoundKind.TypeOrValueExpression)
' The given receiver should also have been derived from groupOpt.ReceiverOpt (if it exists).
'TODO: may need to distinguish indexing/calling/dictionary
'TODO: for example "Dim a = ("a".Clone)()" is an IndexGet
If receiver.IsNothingLiteral Then
ReportDiagnostic(diagnostics, node, ERRID.ERR_IllegalCallOrIndex)
Return BadExpression(node, arguments, ErrorTypeSymbol.UnknownResultType)
End If
If OptionStrict = VisualBasic.OptionStrict.On Then
Debug.Assert(Not suppressLateBindingResolutionDiagnostics)
' "Option Strict On disallows late binding."
ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, groupOpt), ERRID.ERR_StrictDisallowsLateBinding)
Dim children = ArrayBuilder(Of BoundExpression).GetInstance
If receiver IsNot Nothing Then
children.Add(receiver)
End If
If Not arguments.IsEmpty Then
children.AddRange(arguments)
End If
Return BadExpression(node, children.ToImmutableAndFree, ErrorTypeSymbol.UnknownResultType)
ElseIf OptionStrict = VisualBasic.OptionStrict.Custom AndAlso Not suppressLateBindingResolutionDiagnostics Then
ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, groupOpt), ERRID.WRN_LateBindingResolution)
End If
Dim isIndexing As Boolean = receiver IsNot Nothing AndAlso Not receiver.Kind = BoundKind.LateMemberAccess
Dim objectType = GetSpecialType(SpecialType.System_Object, node, diagnostics)
If Not arguments.IsEmpty Then
Dim builder As ArrayBuilder(Of BoundExpression) = Nothing
For i As Integer = 0 To arguments.Length - 1
Dim origArgument = arguments(i)
Dim argument As BoundExpression = origArgument
If argument.Kind = BoundKind.OmittedArgument Then
Dim omitted = DirectCast(argument, BoundOmittedArgument)
' Omitted arguments are valid in a context of latebound invocation
' so we will reclassify it as an object value.
' NOTE: We do not want to make this a part of general reclassification as
' in general omitted argument is not a value.
argument = omitted.Update(GetSpecialType(SpecialType.System_Object, argument.Syntax, diagnostics))
End If
' indexing is always ByVal
' otherwise everything potentially assignable is passed ByRef
Dim passByRef As Boolean = Not isIndexing AndAlso IsSupportingAssignment(argument)
If Not isIndexing AndAlso IsSupportingAssignment(argument) Then
' Leave property access and late bound nodes with unknown access kind as we don't know whether there will be
' an attempt to copy back value at runtime.
Else
argument = ApplyImplicitConversion(argument.Syntax, objectType, argument, diagnostics)
End If
If builder IsNot Nothing Then
builder.Add(argument)
Else
If argument IsNot origArgument Then
builder = ArrayBuilder(Of BoundExpression).GetInstance(arguments.Length)
For j = 0 To i - 1
builder.Add(arguments(j))
Next
builder.Add(argument)
End If
End If
Next
If builder IsNot Nothing Then
arguments = builder.ToImmutableAndFree
End If
End If
If receiver IsNot Nothing AndAlso
receiver.Kind = BoundKind.MeReference AndAlso
(IsMeOrMyBaseOrMyClassInSharedContext() OrElse IsInsideChainedConstructorCallArguments) Then
receiver = Nothing
End If
If receiver IsNot Nothing AndAlso Not receiver.IsLValue AndAlso receiver.Kind <> BoundKind.LateMemberAccess Then
receiver = MakeRValue(receiver, diagnostics)
End If
Dim objType = Me.GetSpecialType(SpecialType.System_Object, node, diagnostics)
Return New BoundLateInvocation(node, receiver, arguments, argumentNames, LateBoundAccessKind.Unknown, groupOpt, objType)
End Function
End Class
End Namespace
|
kelltrick/roslyn
|
src/Compilers/VisualBasic/Portable/Binding/Binder_Latebound.vb
|
Visual Basic
|
apache-2.0
| 11,422
|
' 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 InterpolatedStringExpressionStructureProvider
Inherits AbstractSyntaxNodeStructureProvider(Of InterpolatedStringExpressionSyntax)
Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken,
node As InterpolatedStringExpressionSyntax,
ByRef spans As TemporaryArray(Of BlockSpan),
optionProvider As BlockStructureOptionProvider,
cancellationToken As CancellationToken)
If node.DollarSignDoubleQuoteToken.IsMissing OrElse
node.DoubleQuoteToken.IsMissing Then
Return
End If
spans.Add(New BlockSpan(
type:=BlockTypes.Expression,
isCollapsible:=True,
textSpan:=node.Span,
autoCollapse:=True,
isDefaultCollapsed:=False))
End Sub
End Class
End Namespace
|
eriawan/roslyn
|
src/Features/VisualBasic/Portable/Structure/Providers/InterpolatedStringExpressionStructureProvider.vb
|
Visual Basic
|
apache-2.0
| 1,480
|
' 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 System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
''' <summary>
''' This class watches for buffer-based events, tracks the dirty regions, and invokes the formatter as appropriate
''' </summary>
Partial Friend Class CommitBufferManager
Inherits ForegroundThreadAffinitizedObject
Private ReadOnly _buffer As ITextBuffer
Private ReadOnly _commitFormatter As ICommitFormatter
Private ReadOnly _inlineRenameService As IInlineRenameService
Private _referencingViews As Integer
''' <summary>
''' An object to use as a sync lock for <see cref="_referencingViews"/>.
''' </summary>
Private ReadOnly _referencingViewsLock As Object = New Object()
''' <summary>
''' The tracking span which is the currently "dirty" region in the buffer. May be null if there is no dirty region.
''' </summary>
Private _dirtyState As DirtyState
Private _documentBeforePreviousEdit As Document
''' <summary>
''' The number of times BeginSuppressingCommits() has been called.
''' </summary>
Private _suppressions As Integer
Public Sub New(
buffer As ITextBuffer,
commitFormatter As ICommitFormatter,
inlineRenameService As IInlineRenameService,
threadingContext As IThreadingContext)
MyBase.New(threadingContext, assertIsForeground:=False)
Contract.ThrowIfNull(buffer)
Contract.ThrowIfNull(commitFormatter)
Contract.ThrowIfNull(inlineRenameService)
_buffer = buffer
_commitFormatter = commitFormatter
_inlineRenameService = inlineRenameService
End Sub
Public Sub AddReferencingView()
ThisCanBeCalledOnAnyThread()
SyncLock _referencingViewsLock
_referencingViews += 1
If _referencingViews = 1 Then
AddHandler _buffer.Changing, AddressOf OnTextBufferChanging
AddHandler _buffer.Changed, AddressOf OnTextBufferChanged
End If
End SyncLock
End Sub
Public Sub RemoveReferencingView()
ThisCanBeCalledOnAnyThread()
SyncLock _referencingViewsLock
' If someone enables line commit with a file already open, we might end up decrementing
' the ref count too many times, so only do work if we are still above 0.
If _referencingViews > 0 Then
_referencingViews -= 1
If _referencingViews = 0 Then
RemoveHandler _buffer.Changed, AddressOf OnTextBufferChanged
RemoveHandler _buffer.Changing, AddressOf OnTextBufferChanging
End If
End If
End SyncLock
End Sub
Public ReadOnly Property HasDirtyRegion As Boolean
Get
Return _dirtyState IsNot Nothing
End Get
End Property
''' <summary>
''' Commits any dirty region, if one exists.
'''
''' To improve perf, passing false to isExplicitFormat will avoid semantic checks when expanding
''' the formatting span to an entire block
''' </summary>
Public Sub CommitDirty(isExplicitFormat As Boolean, cancellationToken As CancellationToken)
If _inlineRenameService.ActiveSession IsNot Nothing Then
_dirtyState = Nothing
Return
End If
If _dirtyState Is Nothing Then
Return
End If
' Is something else in the commit process suppressing the commit?
If _suppressions > 0 Then
Return
End If
Try
' Start to suppress commits to ensure we don't have any sort of re-entrancy in this process.
' We've seen bugs (17015) where waits triggered by some computation might re-enter.
Using BeginSuppressingCommits()
' It's possible that an edit may already be in progress. In this scenario, there's
' really nothing we can do, so we'll just skip the format
If _buffer.EditInProgress Then
Return
End If
Dim dirtyRegion = _dirtyState.DirtyRegion.GetSpan(_buffer.CurrentSnapshot)
Dim info As FormattingInfo
If Not TryComputeExpandedSpanToFormat(dirtyRegion, info, cancellationToken) Then
Return
End If
Dim useSemantics = info.UseSemantics
If useSemantics AndAlso Not isExplicitFormat Then
' Avoid using semantics for formatting extremely large dirty spans without an explicit request
' from the user. The "large span threshold" is 7000 lines. The 7000 line threshold is an
' estimated value accounting for a lower-bound of the algorithmic complexity of text
' differencing in designer cases along with measurements of a pathological example demonstrated
' at 14000 lines. We expect Windows Forms designer formatting operations to run in under ~15
' seconds on average current hardware when nearing the threshold.
Dim startLineNumber = 0
Dim startCharIndex = 0
Dim endLineNumber = 0
Dim endCharIndex = 0
info.SpanToFormat.GetLinesAndCharacters(startLineNumber, startCharIndex, endLineNumber, endCharIndex)
If endLineNumber - startLineNumber > 7000 Then
useSemantics = False
End If
End If
Dim tree = _dirtyState.BaseDocument.GetSyntaxTreeSynchronously(cancellationToken)
_commitFormatter.CommitRegion(info.SpanToFormat, isExplicitFormat, useSemantics, dirtyRegion, _dirtyState.BaseSnapshot, tree, cancellationToken)
End Using
Finally
' We may have tracked a dirty region while committing or it may have been aborted.
' In any case, we want to guarantee we have no dirty region once we're done
_dirtyState = Nothing
End Try
End Sub
Private Structure FormattingInfo
Public UseSemantics As Boolean
Public SpanToFormat As SnapshotSpan
End Structure
Public Sub ExpandDirtyRegion(snapshotSpan As SnapshotSpan)
If _dirtyState Is Nothing Then
Dim document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges()
If document IsNot Nothing Then
_dirtyState = New DirtyState(snapshotSpan, snapshotSpan.Snapshot, document)
End If
Else
_dirtyState = _dirtyState.WithExpandedDirtySpan(snapshotSpan)
End If
End Sub
Private Function TryComputeExpandedSpanToFormat(dirtySpan As SnapshotSpan, ByRef formattingInfo As FormattingInfo, cancellationToken As CancellationToken) As Boolean
Dim document = dirtySpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
formattingInfo.UseSemantics = True
Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken)
' No matter what, we will always include the dirty span
Dim finalSpanStart = dirtySpan.Start.Position
Dim finalSpanEnd = dirtySpan.End.Position
' Find the containing statements
Dim startingStatementInfo = ContainingStatementInfo.GetInfo(dirtySpan.Start, tree, cancellationToken)
If startingStatementInfo IsNot Nothing Then
finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.TextSpan.Start)
If startingStatementInfo.MatchingBlockConstruct IsNot Nothing Then
' If we're expanding backwards because of editing an end construct, we don't wan to run
' expensive semantic formatting checks. We really just want to fix up indentation.
formattingInfo.UseSemantics = finalSpanStart <= startingStatementInfo.MatchingBlockConstruct.SpanStart
finalSpanStart = Math.Min(finalSpanStart, startingStatementInfo.MatchingBlockConstruct.SpanStart)
End If
End If
Dim endingStatementInfo = If(ContainingStatementInfo.GetInfo(dirtySpan.End, tree, cancellationToken), startingStatementInfo)
If endingStatementInfo IsNot Nothing Then
finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.TextSpan.End)
If endingStatementInfo.MatchingBlockConstruct IsNot Nothing Then
finalSpanEnd = Math.Max(finalSpanEnd, endingStatementInfo.MatchingBlockConstruct.Span.End)
End If
End If
Dim startingLine = dirtySpan.Snapshot.GetLineFromPosition(finalSpanStart)
If startingLine.LineNumber = 0 Then
finalSpanStart = 0
Else
' We want to include the line break into the line before
finalSpanStart = dirtySpan.Snapshot.GetLineFromLineNumber(startingLine.LineNumber - 1).End
End If
formattingInfo.SpanToFormat = New SnapshotSpan(dirtySpan.Snapshot, Span.FromBounds(finalSpanStart, finalSpanEnd))
Return True
End Function
Public Function IsMovementBetweenStatements(oldPoint As SnapshotPoint, newPoint As SnapshotPoint, cancellationToken As CancellationToken) As Boolean
' If they are the same line, then definitely no
If oldPoint.GetContainingLine().LineNumber = newPoint.GetContainingLine().LineNumber Then
Return False
End If
Dim document = newPoint.Snapshot.GetOpenDocumentInCurrentContextWithChanges()
If document Is Nothing Then
Return False
End If
Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken)
Dim oldStatement = ContainingStatementInfo.GetInfo(oldPoint, tree, cancellationToken)
Dim newStatement = ContainingStatementInfo.GetInfo(newPoint, tree, cancellationToken)
If oldStatement Is Nothing AndAlso newStatement Is Nothing Then
Return True
End If
If (oldStatement Is Nothing) <> (newStatement Is Nothing) Then
Return True
End If
Return oldStatement.TextSpan <> newStatement.TextSpan
End Function
Private Sub OnTextBufferChanging(sender As Object, e As TextContentChangingEventArgs)
If _dirtyState Is Nothing Then
' Grab the current document for the text buffer before it changes so we can get any
' cached versions
Dim documentBeforePreviousEdit = e.Before.GetOpenDocumentInCurrentContextWithChanges()
If documentBeforePreviousEdit IsNot Nothing Then
_documentBeforePreviousEdit = documentBeforePreviousEdit
' Kick off a task to eagerly force compute InternalsVisibleTo semantics for all the references.
' This provides a noticeable perf improvement when code cleanup is subsequently invoked on this document.
Task.Run(Async Function()
Await ForceComputeInternalsVisibleToAsync(documentBeforePreviousEdit, CancellationToken.None).ConfigureAwait(False)
End Function)
End If
End If
End Sub
Private Sub OnTextBufferChanged(sender As Object, e As TextContentChangedEventArgs)
' Before we do anything else, ensure the field is nulled back out
Dim documentBeforePreviousEdit = _documentBeforePreviousEdit
_documentBeforePreviousEdit = Nothing
If e.Changes.Count = 0 Then
Return
End If
' If this is a reiterated version, then it's part of undo/redo and we should ignore it
If e.AfterVersion.ReiteratedVersionNumber <> e.AfterVersion.VersionNumber Then
Return
End If
' Add this region into our dirty region
Dim encompassingNewSpan = New SnapshotSpan(e.After, Span.FromBounds(e.Changes.First().NewPosition, e.Changes.Last().NewEnd))
If _dirtyState Is Nothing Then
' Some times, we won't get a documentBeforePreviousEdit. This happens because sometimes OnTextBufferChanging
' isn't called before OnTextBufferChanged in undo scenarios. In those cases, since we can't set up valid state,
' just throw it out
If documentBeforePreviousEdit IsNot Nothing Then
_dirtyState = New DirtyState(encompassingNewSpan, e.Before, documentBeforePreviousEdit)
End If
Else
_dirtyState = _dirtyState.WithExpandedDirtySpan(encompassingNewSpan)
End If
End Sub
Private Async Function ForceComputeInternalsVisibleToAsync(document As Document, cancellationToken As CancellationToken) As Task
Dim project = document.Project
Dim compilation = Await project.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
For Each reference In project.ProjectReferences
Dim refProject = project.Solution.GetProject(reference.ProjectId)
If refProject IsNot Nothing Then
Dim refCompilation = Await refProject.GetCompilationAsync(cancellationToken).ConfigureAwait(False)
refCompilation.Assembly().GivesAccessTo(compilation.Assembly)
End If
Next
For Each reference In project.MetadataReferences
Dim refAssemblyOrModule = compilation.GetAssemblyOrModuleSymbol(reference)
If refAssemblyOrModule.MatchesKind(SymbolKind.Assembly) Then
Dim refAssembly = DirectCast(refAssemblyOrModule, IAssemblySymbol)
refAssembly.GivesAccessTo(compilation.Assembly)
End If
Next
End Function
''' <summary>
''' Suppresses future commits, causing all calls to CommitDirty() to be a simple no-op, even
''' if there is a dirty span.
''' </summary>
''' <returns>An IDisposable that should be disposed when the caller wants to resume
''' submissions.</returns>
Friend Function BeginSuppressingCommits() As IDisposable
_suppressions += 1
Return New SuppressionHandle(Me)
End Function
Private Class SuppressionHandle
Implements IDisposable
Private _manager As CommitBufferManager
Public Sub New(manager As CommitBufferManager)
Contract.ThrowIfNull(manager)
_manager = manager
End Sub
Public Sub Dispose() Implements IDisposable.Dispose
_manager._suppressions -= 1
_manager = Nothing
End Sub
End Class
End Class
End Namespace
|
davkean/roslyn
|
src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManager.vb
|
Visual Basic
|
apache-2.0
| 16,061
|
' 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),
options As BlockStructureOptions,
cancellationToken As CancellationToken)
spans.AddIfNotNull(CreateBlockSpanFromBlock(
node, node.UsingStatement, autoCollapse:=False,
type:=BlockTypes.Statement, isCollapsible:=True))
End Sub
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Features/VisualBasic/Portable/Structure/Providers/UsingBlockStructureProvider.vb
|
Visual Basic
|
mit
| 1,234
|
' 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.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class LocalRewriter
Public Overrides Function VisitDelegateCreationExpression(node As BoundDelegateCreationExpression) As BoundNode
' if there is a stub needed because of a delegate relaxation, the DelegateCreationNode has
' it stored in RelaxationLambdaOpt.
' The lambda rewriter will then take care of the code generation later on.
If node.RelaxationLambdaOpt Is Nothing Then
Debug.Assert(node.RelaxationReceiverPlaceholderOpt Is Nothing OrElse Me.inExpressionLambda)
Return MyBase.VisitDelegateCreationExpression(node)
Else
Dim placeholderOpt As BoundRValuePlaceholder = node.RelaxationReceiverPlaceholderOpt
Dim captureTemp As SynthesizedLocal = Nothing
If placeholderOpt IsNot Nothing Then
If Me.inExpressionLambda Then
Me.AddPlaceholderReplacement(placeholderOpt, VisitExpression(node.ReceiverOpt))
Else
captureTemp = New SynthesizedLocal(Me.currentMethodOrLambda, placeholderOpt.Type, SynthesizedLocalKind.DelegateRelaxationReceiver, syntaxOpt:=placeholderOpt.Syntax)
Dim actualReceiver = New BoundLocal(placeholderOpt.Syntax, captureTemp, captureTemp.Type).MakeRValue
Me.AddPlaceholderReplacement(placeholderOpt, actualReceiver)
End If
End If
Dim relaxationLambda = DirectCast(Me.Visit(node.RelaxationLambdaOpt), BoundLambda)
If placeholderOpt IsNot Nothing Then
Me.RemovePlaceholderReplacement(placeholderOpt)
End If
Dim result As BoundExpression = New BoundConversion(
relaxationLambda.Syntax,
relaxationLambda,
ConversionKind.Lambda Or ConversionKind.Widening,
checked:=False,
explicitCastInCode:=False,
Type:=node.Type,
hasErrors:=node.HasErrors)
If captureTemp IsNot Nothing Then
Dim receiverToCapture As BoundExpression = VisitExpressionNode(node.ReceiverOpt)
Dim capture = New BoundAssignmentOperator(receiverToCapture.Syntax,
New BoundLocal(receiverToCapture.Syntax,
captureTemp, captureTemp.Type),
receiverToCapture.MakeRValue(),
suppressObjectClone:=True,
Type:=captureTemp.Type)
result = New BoundSequence(
result.Syntax,
ImmutableArray.Create(Of LocalSymbol)(captureTemp),
ImmutableArray.Create(Of BoundExpression)(capture),
result,
result.Type)
End If
Return result
End If
End Function
End Class
End Namespace
|
mono/roslyn
|
src/Compilers/VisualBasic/Portable/Lowering/LocalRewriter/LocalRewriter_DelegateCreation.vb
|
Visual Basic
|
apache-2.0
| 3,733
|
' CodeContracts
'
' Copyright (c) Microsoft Corporation
'
' All rights reserved.
'
' 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.
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated by a tool.
' Runtime Version:4.0.30109.1
'
' Changes to this file may cause incorrect behavior and will be lost if
' the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Namespace My.Resources
'This class was auto-generated by the StronglyTypedResourceBuilder
'class via a tool like ResGen or Visual Studio.
'To add or remove a member, edit your .ResX file then rerun ResGen
'with the /str option, or rebuild your VS project.
'''<summary>
''' A strongly-typed resource class, for looking up localized strings, etc.
'''</summary>
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0"), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
Friend Module Resources
Private resourceMan As Global.System.Resources.ResourceManager
Private resourceCulture As Global.System.Globalization.CultureInfo
'''<summary>
''' Returns the cached ResourceManager instance used by this class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("ClassLibrary1.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
|
ndykman/CodeContracts
|
Documentation/Talks/2010/Padova/Stack/ClassLibrary1/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 3,853
|
' 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.VisualBasic.UnitTests
Public Class CodeGenUnstructuredErrorHandling
Inherits BasicTestBase
<Fact()>
Public Sub Erl_Property_SimpleBehaviourMultipleLabels()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline(err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[5
10
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_NestedTryCatch()
'The ERL is correct even though the error occurred within a nested try catch construct
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Try
Err.Raise(5)
Console.writeline("Incorrect Code Path")
Catch ex as exception
Console.writeline("Inner" & err.Number)
Console.writeline(err.erl)
End Try
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Inner5
10
No Error]]>)
End Sub
<Fact()>
Public Sub Erl_Property_NestedTryCatchNoPropagateToOuter()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Try
11:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
Catch ex as exception
Console.writeline("Inner" & err.Number)
Console.writeline(err.erl)
End Try
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Inner5
11
No Error]]>)
End Sub
<Fact()>
Public Sub Erl_Property_DuplicateLabels()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Try
10:
Err.Raise(5)
Catch ex as exception
End Try
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_MultiplyDefined1, "10").WithArguments("10"))
End Sub
<Fact()>
Public Sub Erl_Property_NonSequentialLineNumbers()
'The line numbers do not need to be sequential
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
10:
Try
1:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
1
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_LabelIntegerMaxValueValue()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
1:
Try
2147483647:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
2147483647
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_LabelGreaterThanIntegerMaxValueValue()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
1:
Try
2147483648:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_NonNumericLabels()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Blah:
Try
Foo:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
Goo:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_NoLabels()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
Err.Raise(5)
Console.writeline("Incorrect Code Path")
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_ThrowExceptionInsteadOfErrorRaiseLambdaInvocation()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Dim x = SUB()
Throw New exception ("Exception Instead Of Error")
End Sub
20:
x()
30:
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
20
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_NestedLambdasAndLabelInLambdaSameLabelInCallerAndLambda()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
10:
Dim x = Sub()
throw new exception ("Exception Instead Of Error")
Console.writeline("Incorrect Code Path")
End Sub
Dim y = SUB()
30:
x()
Console.writeline("Incorrect Code Path")
End Sub
20:
y()
30:
Console.writeline("Incorrect Code Path")
Console.writeline("No Error")
Catch ex as exception
Console.writeline("Outer" & err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Outer5
20
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_OnErrorRetainsValueUntilCleared()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
1:
On error resume next
Throw New Exception("test")
2:
Console.writeline(Err.Number)
Console.writeline(Err.Erl)
3:
Console.writeline("Finish")
Console.writeline(Err.Erl)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[5
1
Finish
1
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_OnErrorRetainsValueUntilClearedWithClear()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
1:
On error resume next
Throw New Exception("test")
2:
Console.writeline(Err.Number)
Console.writeline(Err.Erl)
Err.Clear
3:
Console.writeline("Finish")
Console.writeline(Err.Erl)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[5
1
Finish
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_UnhandledErrorDontBubbleUp()
'There is no label in main and the label from SubMethod is not bubbled up.
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
SubMethod()
Catch
Console.writeline("Finish")
Console.writeline(Err.Erl)
End Try
End Sub
Sub SubMethod
1:
On error goto -1
Throw New Exception("test")
2:
Console.writeline(Err.Number)
Console.writeline(Err.Erl)
Err.Clear
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Finish
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_InClassAndStructureTypes()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Dim obj_c as new c1
obj_c.Method
obj_C.p1= 1
Dim obj_s as new s1
obj_s.Method
dim z= obj_s.P1
End Sub
End Module
Public Class C1
Sub Method()
1:
On Error Resume Next
Err.Raise(2)
2:
Console.Writeline(Err.Erl)
Err.Clear
3:
Console.Writeline(Err.Erl) 'This should be 0
Err.Raise(2)
Console.Writeline(Err.Erl) 'This should be 3
4:
Console.Writeline(Err.Erl) 'This should still be 3
End Sub
Public Property P1 as Integer
Get
return 1
End Get
Set (v as Integer)
21:
On Error Resume Next
Err.Raise(2)
22:
Console.Writeline(Err.Erl)
Err.Clear
23:
Console.Writeline(Err.Erl) 'This should be 0
Err.Raise(2)
Console.Writeline(Err.Erl) 'This should be 3
24:
Console.Writeline(Err.Erl) 'This should still be 3
End Set
End Property
End Class
Public Structure S1
Shared x as integer =1
Sub Method()
11:
On Error Resume Next
Err.Raise(2)
12:
Console.Writeline(Err.Erl)
Err.Clear
13:
Console.Writeline(Err.Erl) 'This should be 0
Err.Raise(2)
Console.Writeline(Err.Erl) 'This should be 3
14:
Console.Writeline(Err.Erl) 'This should still be 3
End Sub
Public Readonly Property P1
Get
21:
On Error Resume Next
Err.Raise(2)
22:
Console.Writeline(Err.Erl)
Err.Clear
23:
Console.Writeline(Err.Erl) 'This should be 0
Err.Raise(2)
Console.Writeline(Err.Erl) 'This should be 3
24:
Console.Writeline(Err.Erl) 'This should still be 3
End Get
End Property
End Structure
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[1
0
3
3
21
0
23
23
11
0
13
13
21
0
23
23
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_InGenericType()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Dim obj_c as new c1(of integer)
obj_c.Method(of String)
End Sub
End Module
Public Class C1(of t)
Sub Method(of u)
On error resume next
10:
Err.Raise(3)
20:
Console.Writeline(Err.erl)
30:
Console.Writeline(Err.erl)
err.Clear
40:
Console.Writeline(Err.erl)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[10
10
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_InGenericTypeSharedMethod()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
c1(of integer).Method(of String)
End Sub
End Module
Public Class C1(of t)
Shared Sub Method(of u)
On error resume next
10:
Err.Raise(3)
20:
Console.Writeline(Err.erl)
30:
Console.Writeline(Err.erl)
err.Clear
40:
Console.Writeline(Err.erl)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[10
10
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_InheritenceScenario()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Dim o as new c1
o.a
Dim o2 as new derived
o2.a
Dim o3 as C1 = new derived
o3.a
End Sub
End Module
Public Class C1
overridable Sub A()
10:
On error Resume next
Err.Raise(10)
20:
Console.Writeline(Err.Erl)
End Sub
End Class
Public Class Derived : Inherits c1
Overrides Sub A()
21:
On error Resume next
Err.Raise(10)
22:
Console.Writeline(Err.Erl)
End Sub
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[10
21
21
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_CallingMethodThroughInterface()
'Verify No problems with erl because of calling using interface
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Dim i as igoo = new c1
i.Testmethod
End Sub
End Module
Public Class C1 : Implements Igoo
Sub T1 implements Igoo.Testmethod
On error resume next
10:
Err.Raise(3)
20:
Console.Writeline(Err.erl)
30:
Console.Writeline(Err.erl)
err.Clear
40:
Console.Writeline(Err.erl)
End Sub
End Class
Interface Igoo
Sub Testmethod()
End Interface
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[10
10
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_CallingMethodWithDelegate()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Public Delegate Sub DelSub()
Sub main
On error resume next
1:
Dim d as DelSub
d = addressof TestMethod
d()
2:
Console.Writeline(Err.Erl)
End Sub
Sub TestMethod()
21:
On error Resume next
Err.Raise(10)
22:
Console.Writeline(Err.Erl)
Err.Clear
23:
Console.Writeline(Err.Erl)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[21
0
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_CollectionInitializer()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
On error resume next
1:
Dim d as new System.Collections.Generic.list(of C1) From {new c1 with {.p1=1}}
2:
Console.Writeline(Err.Erl) 'This should be 0
End Sub
End Module
Class C1
Public Property P1 as integer
Get
Return 1
End Get
Set( v as integer)
21:
On error Resume next
Err.Raise(10)
22:
Console.Writeline(Err.Erl)
Err.Clear
23:
Console.Writeline(Err.Erl)
End Set
End Property
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[21
0
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_MultipleHandlers()
' Known behavior with multiple handlers causing bogus out of memory exception
' Won't Fix the VB Runtime in Roslyn but captured the current behavior
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Foo()
On Error Resume Next
1:
Err.Raise(5)
2:
Console.WriteLine(Err.Erl)
On Error GoTo 0
On Error GoTo 3
Err.Raise(6)
3:
Console.WriteLine(Err.Erl)
On Error GoTo 0
On Error GoTo 4
Err.Raise(7)
4:
Console.WriteLine(Err.Erl)
Console.WriteLine("Finish")
End Sub
Sub main()
Try
Foo()
Catch ex As OutOfMemoryException
Console.WriteLine("Expected Exception Occurred")
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[1
2
Expected Exception Occurred
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_MultipleHandlersWithResume()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
On error goto Errhandler
1:
Err.Raise(5)
2:
On error Goto 0
On error Goto SecondHandler
3:
Err.Raise(5)
Exit Sub
ErrHandler:
Console.Writeline(Err.Erl)
resume next
exit sub
SecondHandler:
Console.Writeline(Err.Erl)
resume next
exit sub
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[1
3
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_InvalidNumericLabel()
'More a test of Invalid Label but as the label is used for ERL I wanted to make sure that this didn't compile
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
On error Resume next
-1:'Invalid Label
Console.Writeline("Invalid Label")
0:
1:
Err.Raise(5)
Console.Writeline(Err.Erl)
2:
On error Goto 0
On error Goto 3:
Err.Raise(6)
Console.Writeline(Err.Erl)
3:
On error Goto 3:
Err.Raise(7)
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "-"))
End Sub
<Fact()>
Public Sub Erl_Property_NoHandlerOnInner_WithDuplicateLabelInDifferentMethod()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
1:
Foo
Exit Sub
Catch
2:
Console.Writeline(Err.Erl)
End Try
End Sub
Sub Foo()
2:
Err.raise(4)
Console.Writeline("Incorrect Code Path")
End Sub
End Module]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[1
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_TypeCharsOnLabels()
'More a test of Invalid Label but as the label is used for ERL I wanted to make sure that this didn't compile
'Using type characters which would be valid for numerics
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub main
Try
1L:
Foo
Exit Sub
Catch
2S:
Console.Writeline(Err.Erl)
End Try
End Sub
Sub Foo()
Try
1%:
Err.Raise(1)
Exit Sub
Catch
Console.Writeline(Err.Erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe).VerifyDiagnostics(Diagnostic(ERRID.ERR_Syntax, "1L"),
Diagnostic(ERRID.ERR_Syntax, "2S"),
Diagnostic(ERRID.ERR_Syntax, "1%"))
End Sub
<Fact()>
Public Sub Erl_Property_WithinAsyncMethods()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Dim tcs As AutoResetEvent
Sub main()
1:
Async_Caller()
Console.WriteLine(Err.Erl)
End Sub
Public async Sub Async_Caller()
11:
Try
tcs = New AutoResetEvent(False)
Await Foob()
tcs.WaitOne()
Catch ex As Exception
Console.WriteLine(Err.Erl)
Throw
End Try
End Sub
Async Function Foob() As task
Try
21:
Dim i = Await Test1()
Catch ex As Exception
Console.WriteLine(Err.Erl)
Finally
Console.WriteLine(Err.Erl)
tcs.Set()
End Try
End Function
Async Function Test1() As Task(Of Integer)
31:
Err.Raise(5)
Await Task.Delay(10)
Return 1
End Function
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[21
0
0
]]>)
End Sub
<Fact()>
Public Sub Erl_Property_WithinAsyncMethods_Bug654704()
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports Microsoft.VisualBasic
Imports System.Threading
Imports System.Threading.Tasks
Module Module1
Dim tcs As AutoResetEvent
Sub main()
1:
Async_Caller()
Console.WriteLine(Err.Erl)
End Sub
Public async Sub Async_Caller()
11:
Try
tcs = New AutoResetEvent(False)
Await Foob()
tcs.WaitOne()
Catch ex As Exception
Console.WriteLine(Err.Erl)
Throw
End Try
End Sub
Async Function Foob() As task
Try
21:
Dim i = Await Test1()
Catch ex As Exception
Console.WriteLine(Err.Erl)
Finally
Console.WriteLine(Err.Erl)
tcs.Set()
End Try
End Function
Async Function Test1() As Task(Of Integer)
31:
Err.Raise(5)
Return 1
End Function
End Module
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithReferences(source, {MscorlibRef_v4_0_30316_17626, MsvbRef_v4_0_30319_17929}, TestOptions.ReleaseExe)
CompileAndVerify(compilation)
End Sub
<Fact()>
Public Sub Erl_Property_WithinIteratorMethods()
'This is having try catches at each level and ensuring the
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Imports System.Collections.Generic
Imports Microsoft.VisualBasic
Module Module1
Sub main()
1:
Try
IteratorMethod()
Catch
Console.writeline("Exception")
Console.writeline(Err.erl)
End Try
'Normal
Try
NormalMethod()
Catch
Console.writeline("Exception")
Console.writeline(Err.erl)
End Try
End Sub
Public Sub NormalMethod()
110:
111:
Try
For Each i In abcdef()
Next
Catch
Console.writeline("Exception")
Console.WriteLine(Err.Erl)
Throw
End Try
End Sub
Function abcdef() As Integer()
120:
121:
Try
Err.Raise(5)
Return {1, 2, 3}
Catch
Console.writeline("Exception")
Console.WriteLine(Err.Erl)
Throw
End Try
End Function
Public Sub IteratorMethod()
10:
11:
Try
Dim x As New Scenario1
Dim index As Integer = 0
For Each i In x
index += 1
Next
Catch
Console.writeline("Exception")
Console.WriteLine(Err.Erl)
Throw
End Try
End Sub
End Module
Public Class Scenario1
Implements IEnumerable(Of Integer)
Public Iterator Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of Integer) Implements System.Collections.Generic.IEnumerable(Of Integer).GetEnumerator
20:
21:
Try
Throw New Exception("Test")
Yield 10
Catch
Console.writeline("Exception")
Console.WriteLine(Err.Erl)
Throw
End Try
220:
End Function
Public Iterator Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
29:
22:
Try
Throw New Exception("Test2")
Yield 10
Catch
Console.writeline("Exception")
Console.WriteLine(Err.Erl)
Throw
End Try
30:
End Function
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlibAndVBRuntime(source, TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:=<![CDATA[Exception
21
Exception
11
Exception
1
Exception
121
Exception
111
Exception
1]]>)
End Sub
<Fact()>
Public Sub Erl_Property_With_VBCore()
'Error Object Doesn't exist for VBCore - so this should generate correct diagnostics
Dim source =
<compilation name="ErrorHandling">
<file name="a.vb">
<![CDATA[
Imports System
Module Module1
Sub main
Try
10:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline(err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
]]>
</file>
</compilation>
Dim compilation = CompilationUtils.CreateCompilationWithReferences(source,
references:={MscorlibRef, SystemRef, SystemCoreRef},
options:=TestOptions.ReleaseDll.WithEmbedVbCoreRuntime(True)).VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "Err").WithArguments("Err"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "err").WithArguments("err"),
Diagnostic(ERRID.ERR_NameNotDeclared1, "err").WithArguments("err"))
End Sub
<Fact()>
Public Sub ERL_Property_CodeGenVerify()
'Simple Verification of IL to determine that Labels and types are as expected
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Imports Microsoft.VisualBasic
Module Module1
Sub Main
Try
10:
Err.Raise(5)
Console.writeline("Incorrect Code Path")
20:
Console.writeline("No Error")
Catch ex as exception
Console.writeline(err.Number)
Console.writeline(err.erl)
End Try
End Sub
End Module
</file>
</compilation>,
expectedOutput:=<![CDATA[5
10]]>).
VerifyIL("Module1.Main",
<![CDATA[{
// Code size 89 (0x59)
.maxstack 6
.locals init (Integer V_0,
System.Exception V_1) //ex
.try
{
IL_0000: ldc.i4.s 10
IL_0002: stloc.0
IL_0003: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject"
IL_0008: ldc.i4.5
IL_0009: ldnull
IL_000a: ldnull
IL_000b: ldnull
IL_000c: ldnull
IL_000d: callvirt "Sub Microsoft.VisualBasic.ErrObject.Raise(Integer, Object, Object, Object, Object)"
IL_0012: ldstr "Incorrect Code Path"
IL_0017: call "Sub System.Console.WriteLine(String)"
IL_001c: ldc.i4.s 20
IL_001e: stloc.0
IL_001f: ldstr "No Error"
IL_0024: call "Sub System.Console.WriteLine(String)"
IL_0029: leave.s IL_0058
}
catch System.Exception
{
IL_002b: dup
IL_002c: ldloc.0
IL_002d: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception, Integer)"
IL_0032: stloc.1
IL_0033: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject"
IL_0038: callvirt "Function Microsoft.VisualBasic.ErrObject.get_Number() As Integer"
IL_003d: call "Sub System.Console.WriteLine(Integer)"
IL_0042: call "Function Microsoft.VisualBasic.Information.Err() As Microsoft.VisualBasic.ErrObject"
IL_0047: callvirt "Function Microsoft.VisualBasic.ErrObject.get_Erl() As Integer"
IL_004c: call "Sub System.Console.WriteLine(Integer)"
IL_0051: call "Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"
IL_0056: leave.s IL_0058
}
IL_0058: ret
}
]]>)
End Sub
End Class
End Namespace
|
mmitche/roslyn
|
src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenUnstructuredErrorHandling.vb
|
Visual Basic
|
apache-2.0
| 33,480
|
' 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.Text
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Partial Friend Class CrefCompletionProvider
Inherits CompletionListProvider
Private Shared ReadOnly CrefFormat As SymbolDisplayFormat =
New SymbolDisplayFormat(
globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameOnly,
propertyStyle:=SymbolDisplayPropertyStyle.NameOnly,
genericsOptions:=SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions:=SymbolDisplayMiscellaneousOptions.UseSpecialTypes)
Public Overrides Function IsTriggerCharacter(text As SourceText, characterPosition As Integer, options As OptionSet) As Boolean
Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options)
End Function
Public Overrides Async Function ProduceCompletionListAsync(context As CompletionListContext) As Task
Dim document = context.Document
Dim position = context.Position
Dim cancellationToken = context.CancellationToken
Dim tree = Await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(False)
Dim token = tree.GetTargetToken(position, cancellationToken)
If IsCrefTypeParameterContext(token) Then
Return
End If
' To get a Speculative SemanticModel (which is much faster), we need to
' walk up to the node the DocumentationTrivia is attached to.
Dim parentNode = token.Parent?.FirstAncestorOrSelf(Of DocumentationCommentTriviaSyntax)()?.ParentTrivia.Token.Parent
If parentNode Is Nothing Then
Return
End If
Dim semanticModel = Await document.GetSemanticModelForNodeAsync(parentNode, cancellationToken).ConfigureAwait(False)
Dim workspace = document.Project.Solution.Workspace
Dim symbols = GetSymbols(token, semanticModel, cancellationToken)
If Not symbols.Any() Then
Return
End If
Dim text = Await document.GetTextAsync(cancellationToken).ConfigureAwait(False)
Dim filterSpan = CompletionUtilities.GetTextChangeSpan(text, position)
Dim items = CreateCompletionItems(workspace, semanticModel, symbols, token.SpanStart, filterSpan)
context.AddItems(items)
If IsFirstCrefParameterContext(token) Then
' Include Of in case they're typing a type parameter
context.AddItem(CreateOfCompletionItem(filterSpan))
End If
context.MakeExclusive(True)
End Function
Private Shared Function IsCrefTypeParameterContext(token As SyntaxToken) As Boolean
Return (token.IsChildToken(Function(t As TypeArgumentListSyntax) t.OfKeyword) OrElse
token.IsChildSeparatorToken(Function(t As TypeArgumentListSyntax) t.Arguments)) AndAlso
token.Parent?.FirstAncestorOrSelf(Of XmlCrefAttributeSyntax)() IsNot Nothing
End Function
Private Shared Function IsCrefStartContext(token As SyntaxToken) As Boolean
' cases:
' <see cref="x|
' <see cref='x|
If token.IsChildToken(Function(x As XmlCrefAttributeSyntax) x.StartQuoteToken) Then
Return True
End If
' cases:
' <see cref="|
' <see cref='|
If token.Parent.IsKind(SyntaxKind.XmlString) AndAlso token.Parent.IsParentKind(SyntaxKind.XmlAttribute) Then
Dim xmlAttribute = DirectCast(token.Parent.Parent, XmlAttributeSyntax)
Dim xmlName = TryCast(xmlAttribute.Name, XmlNameSyntax)
If xmlName?.LocalName.ValueText = "cref" Then
Return True
End If
End If
Return False
End Function
Private Shared Function IsCrefParameterListContext(token As SyntaxToken) As Boolean
' cases:
' <see cref="M(|
' <see cref="M(x, |
Return IsFirstCrefParameterContext(token) OrElse
token.IsChildSeparatorToken(Function(x As CrefSignatureSyntax) x.ArgumentTypes)
End Function
Private Shared Function IsFirstCrefParameterContext(ByRef token As SyntaxToken) As Boolean
Return token.IsChildToken(Function(x As CrefSignatureSyntax) x.OpenParenToken)
End Function
Private Shared Function GetSymbols(token As SyntaxToken, semanticModel As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of ISymbol)
If IsCrefStartContext(token) Then
Return semanticModel.LookupSymbols(token.SpanStart)
ElseIf IsCrefParameterListContext(token) Then
Return semanticModel.LookupNamespacesAndTypes(token.SpanStart)
ElseIf token.IsChildToken(Function(x As QualifiedNameSyntax) x.DotToken) Then
Return GetQualifiedSymbols(DirectCast(token.Parent, QualifiedNameSyntax), token, semanticModel, cancellationToken)
End If
Return SpecializedCollections.EmptyEnumerable(Of ISymbol)
End Function
Private Shared Iterator Function GetQualifiedSymbols(qualifiedName As QualifiedNameSyntax, token As SyntaxToken, semanticModel As SemanticModel, cancellationToken As CancellationToken) As IEnumerable(Of ISymbol)
Dim leftSymbol = semanticModel.GetSymbolInfo(qualifiedName.Left, cancellationToken).Symbol
Dim leftType = semanticModel.GetTypeInfo(qualifiedName.Left, cancellationToken).Type
Dim container = TryCast(If(leftSymbol, leftType), INamespaceOrTypeSymbol)
For Each symbol In semanticModel.LookupSymbols(token.SpanStart, container)
Yield symbol
Next
Dim namedTypeContainer = TryCast(container, INamedTypeSymbol)
If namedTypeContainer IsNot Nothing Then
For Each constructor In namedTypeContainer.Constructors
If Not constructor.IsStatic Then
Yield constructor
End If
Next
End If
End Function
Private Iterator Function CreateCompletionItems(workspace As Workspace, semanticModel As SemanticModel, symbols As IEnumerable(Of ISymbol), position As Integer, filterSpan As TextSpan) As IEnumerable(Of CompletionItem)
Dim builder = SharedPools.Default(Of StringBuilder).Allocate()
Try
For Each symbol In symbols
builder.Clear()
Yield CreateCompletionItem(workspace, semanticModel, symbol, position, filterSpan, builder)
Next
Finally
SharedPools.Default(Of StringBuilder).ClearAndFree(builder)
End Try
End Function
Private Function CreateCompletionItem(workspace As Workspace, semanticModel As SemanticModel, symbol As ISymbol, position As Integer, filterSpan As TextSpan, builder As StringBuilder) As CompletionItem
If symbol.IsUserDefinedOperator() Then
builder.Append("Operator ")
End If
builder.Append(symbol.ToDisplayString(CrefFormat))
Dim parameters = symbol.GetParameters()
If Not parameters.IsDefaultOrEmpty Then
builder.Append("("c)
For i = 0 To parameters.Length - 1
If i > 0 Then
builder.Append(", ")
End If
Dim parameter = parameters(i)
If parameter.RefKind = RefKind.Ref Then
builder.Append("ByRef ")
End If
builder.Append(parameter.Type.ToMinimalDisplayString(semanticModel, position))
Next
builder.Append(")"c)
ElseIf symbol.Kind = SymbolKind.Method
builder.Append("()")
End If
Dim displayString = builder.ToString()
Return New CompletionItem(Me, displayString, filterSpan, glyph:=symbol.GetGlyph(),
descriptionFactory:=CommonCompletionUtilities.CreateDescriptionFactory(workspace, semanticModel, position, symbol),
rules:=ItemRules.Instance)
End Function
Private Function CreateOfCompletionItem(span As TextSpan) As CompletionItem
Return New CompletionItem(Me, "Of", span, glyph:=Glyph.Keyword,
description:=RecommendedKeyword.CreateDisplayParts("Of", VBFeaturesResources.OfKeywordToolTip))
End Function
End Class
End Namespace
|
MihaMarkic/roslyn-prank
|
src/Features/VisualBasic/Portable/Completion/CompletionProviders/CrefCompletionProvider.vb
|
Visual Basic
|
apache-2.0
| 9,451
|
'------------------------------------------------------------------------------
' <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("VBHelloWorld.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
Carlm-MS/orleans
|
Samples/VBHelloWorld/HelloWorld/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,718
|
' 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
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Diagnostics
Imports Microsoft.VisualBasic.CompilerServices
Imports Microsoft.VisualBasic.CompilerServices.ExceptionUtils
Imports Microsoft.VisualBasic.CompilerServices.Utils
Namespace Microsoft.VisualBasic
<DebuggerTypeProxy(GetType(Collection.CollectionDebugView))>
<DebuggerDisplay("Count = {Count}")>
Public NotInheritable Class Collection : Implements ICollection, IList
Private m_CultureInfo As CultureInfo 'The CultureInfo used for key comparisons
Private m_KeyedNodesHash As Generic.Dictionary(Of String, Node) 'Hashtable mapping key (string) -> Node, contains only items added to the collection with a key
Private m_ItemsList As FastList 'Doubly-linked list of Node containing all items in the collection
Private m_Iterators As List(Of Object) 'List of iterators currently iterating this collection
Public Sub New()
MyBase.New()
Initialize(GetCultureInfo())
End Sub
'*****************************************************************************
'These methods are 1 based
'*****************************************************************************
''' <summary>
''' Add an item to the collection
''' </summary>
''' <param name="Item"></param>
''' <param name="Key"></param>
''' <param name="Before"></param>
''' <param name="After"></param>
Public Sub Add(ByVal Item As Object, Optional ByVal Key As String = Nothing, Optional ByVal Before As Object = Nothing, Optional ByVal After As Object = Nothing)
'Before and After are mutually exclusive
If (Before IsNot Nothing) AndAlso (After IsNot Nothing) Then
Throw New ArgumentException(SR.Collection_BeforeAfterExclusive)
End If
'Create a new node
Dim newNode As Node = New Node(Key, Item)
'If a key was specified, add the new node to the hashtable of keys. If this is
' a duplicate key, we'll get an argument exception. This prevents us from
' having to do a hashtable look-up to verify the key is unique.
'However, we then have to be careful to remove the node from the hashtable if we fail to add the item to the
' list because the Before or After keys were bad.
If Key IsNot Nothing Then
Try
m_KeyedNodesHash.Add(Key, newNode)
Catch ex As ArgumentException
Debug.Assert(m_KeyedNodesHash.ContainsKey(Key), "We got an argumentexception from a hashtable add, but it wasn't a duplicate key.")
' Duplicate key. Throw our own exception and our own message.
Throw VbMakeException(New ArgumentException(SR.Collection_DuplicateKey), vbErrors.DuplicateKey)
End Try
End If
Try
'Add the item to list and also (if a key was specified) to the hashtable
If (Before Is Nothing) AndAlso (After Is Nothing) Then 'Neither Before nor After have been specified
'Add the value to the linked list
m_ItemsList.Add(newNode)
ElseIf Before IsNot Nothing Then
'Before has been specified
Dim beforeString As String = TryCast(Before, String)
If beforeString IsNot Nothing Then
Dim BeforeNode As Node = Nothing
If Not m_KeyedNodesHash.TryGetValue(beforeString, BeforeNode) Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Before)), NameOf(Before))
End If
Debug.Assert(BeforeNode IsNot Nothing)
m_ItemsList.InsertBefore(newNode, BeforeNode)
Else
m_ItemsList.Insert(CInt(Before) - 1, newNode) 'Convert from 1 based to 0 based.
End If
Else
'After has been specified
Dim afterString As String = TryCast(After, String)
If afterString IsNot Nothing Then
Dim AfterNode As Node = Nothing
If Not m_KeyedNodesHash.TryGetValue(afterString, AfterNode) Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(After)), NameOf(After))
End If
Debug.Assert(AfterNode IsNot Nothing)
m_ItemsList.InsertAfter(newNode, AfterNode)
Else
m_ItemsList.Insert(CInt(After), newNode) 'Conversion from 1 based to 0 based offsets need to add 1.
End If
End If
Catch ex As OutOfMemoryException
Throw
Catch ex As Threading.ThreadAbortException
Throw
Catch ex As StackOverflowException
Throw
Catch ex As Exception
'We couldn't add the item to the list because the Before or After key was not found. We need to back out the
' insert that we did into the hash table.
If Key IsNot Nothing Then
m_KeyedNodesHash.Remove(Key)
End If
Throw
End Try
'Adjust the ForEach iterators
AdjustEnumeratorsOnNodeInserted(newNode)
End Sub
''' <summary>
''' Clears all items in the collection
''' </summary>
Public Sub Clear()
m_KeyedNodesHash.Clear()
m_ItemsList.Clear()
'Notify the enumerators
Dim i As Integer = m_Iterators.Count - 1
While i >= 0
Dim ref As WeakReference = DirectCast(m_Iterators(i), WeakReference)
If ref.IsAlive Then
Dim enumerator As ForEachEnum = CType(ref.Target, ForEachEnum)
If Not enumerator Is Nothing Then
enumerator.AdjustOnListCleared()
End If
Else
m_Iterators.RemoveAt(i)
End If
i -= 1
End While
End Sub
''' <summary>
''' Returns true if the given key is in the collection
''' </summary>
''' <param name="Key"></param>
''' <returns>True - the given key is in the collection. False otherwise.</returns>
Public Function Contains(ByVal Key As String) As Boolean
If Key Is Nothing Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Key)), NameOf(Key))
End If
Return m_KeyedNodesHash.ContainsKey(Key)
End Function
Public Overloads Sub Remove(ByVal Key As String)
Dim node As Node = Nothing
If m_KeyedNodesHash.TryGetValue(Key, node) Then
Debug.Assert(node IsNot Nothing)
'Adjust the ForEach iterators
AdjustEnumeratorsOnNodeRemoved(node) 'Must be done before the prev/next pointers are removed
'Remove the item from the list and hash table (we know it has a key)
Debug.Assert(node.m_Key IsNot Nothing, "How can that be? We just found it by its key.")
m_KeyedNodesHash.Remove(Key)
m_ItemsList.RemoveNode(node)
'Remove prev/next pointers because the iterators will be thrown off if this isn't done. Also it's easier for debugging.
node.m_Prev = Nothing
node.m_Next = Nothing
Else
Debug.Assert(node Is Nothing)
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Key)), NameOf(Key))
End If
End Sub
Public Overloads Sub Remove(ByVal Index As Integer)
IndexCheck(Index)
Dim node As Node = m_ItemsList.RemoveAt(Index - 1) '0 based
Debug.Assert(node IsNot Nothing, "Should have thrown exception rather than return Nothing")
AdjustEnumeratorsOnNodeRemoved(node) 'Must be done before the prev/next pointers are removed
'Remove from the hash table if it has a key
If node.m_Key IsNot Nothing Then
m_KeyedNodesHash.Remove(node.m_Key)
End If
'Remove prev/next pointers because the iterators will be thrown off if this isn't done. Also it's easier for debugging.
node.m_Prev = Nothing
node.m_Next = Nothing
End Sub
Default Public Overloads ReadOnly Property Item(ByVal Index As Integer) As Object
'This method uses 1 based arrays.
Get
IndexCheck(Index)
Dim node As Node = m_ItemsList.Item(Index - 1)
Debug.Assert(node IsNot Nothing, "Should have thrown rather than returning Nothing")
Return node.m_Value
End Get
End Property
Default Public Overloads ReadOnly Property Item(ByVal Key As String) As Object
Get
If Key Is Nothing Then
'Backwards compat - throw IndexOutOfRange if Key = Nothing
Throw New IndexOutOfRangeException(SR.Argument_CollectionIndex)
End If
Dim node As Node = Nothing
If Not m_KeyedNodesHash.TryGetValue(Key, node) Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, "Index"), NameOf(Key))
End If
Debug.Assert(node IsNot Nothing)
Return node.m_Value
End Get
End Property
<System.ComponentModel.EditorBrowsable(ComponentModel.EditorBrowsableState.Advanced)>
Default Public Overloads ReadOnly Property Item(ByVal Index As Object) As Object
Get
If (TypeOf Index Is String) OrElse (TypeOf Index Is Char) OrElse (TypeOf Index Is Char()) Then
' Index is string and is being treated as key
Dim key As String = CStr(Index)
Return Me.Item(key)
Else
' Index is being treated as numeric expression
Dim indexValue As Integer
Try
indexValue = CInt(Index)
Catch ex As StackOverflowException
Throw ex
Catch ex As OutOfMemoryException
Throw ex
Catch ex As System.Threading.ThreadAbortException
Throw ex
Catch
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(Index)), NameOf(Index))
End Try
Return Me.Item(indexValue)
End If
End Get
End Property
Public ReadOnly Property Count() As Integer
Get
Return m_ItemsList.Count
End Get
End Property
Public Function GetEnumerator() As IEnumerator
' Remove Dead Iterators if any from Iterator list m_Iterators
Dim oldWeakref As WeakReference
Dim i As Integer = m_Iterators.Count - 1
While (i >= 0)
oldWeakref = CType(m_Iterators(i), WeakReference)
If Not oldWeakref.IsAlive Then
m_Iterators.RemoveAt(i)
End If
i -= 1
End While
' Create A New Iterator, add to Iterator List and return
Dim enumerator As ForEachEnum = New ForEachEnum(Me)
Dim weakref As WeakReference = New WeakReference(enumerator)
enumerator.WeakRef = weakref
m_Iterators.Add(weakref)
Return enumerator
End Function
Friend Sub RemoveIterator(ByVal weakref As WeakReference)
m_Iterators.Remove(weakref)
End Sub
Friend Sub AddIterator(ByVal weakref As WeakReference)
m_Iterators.Add(weakref)
End Sub
'Returns the first node in the linked list
Friend Function GetFirstListNode() As Node
Return m_ItemsList.GetFirstListNode()
End Function
Friend NotInheritable Class Node
'Constructor. Key or Value may be Nothing
Friend Sub New(ByVal Key As String, ByVal Value As Object)
m_Value = Value
m_Key = Key
End Sub
Friend m_Value As Object 'The value.
Friend m_Key As String 'The key. If Nothing, the collection item has no user-specified key.
Friend m_Next As Node 'Doubly-linked list pointer to the next node
Friend m_Prev As Node 'Doubly-linked list pointer to the previous node
End Class 'Node
''' <summary>
''' Debugger proxy for the Collection class. Provides a view of the collection
''' that just displays the collection contents.
''' </summary>
Friend NotInheritable Class CollectionDebugView
<DebuggerBrowsable(DebuggerBrowsableState.Never)>
Private m_InstanceBeingWatched As Collection
Public Sub New(ByVal RealClass As Collection)
m_InstanceBeingWatched = RealClass
End Sub
'Returns an array with all items in the collection.
<DebuggerBrowsable(DebuggerBrowsableState.RootHidden)>
Public ReadOnly Property Items() As Object()
Get
Dim count As Integer = m_InstanceBeingWatched.Count
If count = 0 Then
Return Nothing
End If
Dim results(count) As Object
results(0) = SR.EmptyPlaceHolderMessage
For Index As Integer = 1 To count
Dim newNode As Node = m_InstanceBeingWatched.InternalItemsList.Item(Index - 1)
results(Index) = New KeyValuePair(newNode.m_Key, newNode.m_Value)
Next Index
Return results
End Get
End Property
End Class
''' <summary>
''' Initialize all internal structures to set up an empty collection.
''' </summary>
''' <param name="CultureInfo">the culture info to use for key comparisons for the lifetime of this collection.</param>
''' <param name="StartingHashCapacity"></param>
Private Sub Initialize(ByVal CultureInfo As CultureInfo, Optional ByVal StartingHashCapacity As Integer = 0)
Debug.Assert(CultureInfo IsNot Nothing)
If StartingHashCapacity > 0 Then
m_KeyedNodesHash = New Generic.Dictionary(Of String, Node)(StartingHashCapacity, StringComparer.Create(CultureInfo, ignoreCase:=True))
Else
m_KeyedNodesHash = New Generic.Dictionary(Of String, Node)(StringComparer.Create(CultureInfo, ignoreCase:=True))
End If
m_ItemsList = New FastList()
m_Iterators = New List(Of Object)
m_CultureInfo = CultureInfo
End Sub
Private NotInheritable Class FastList
Private m_StartOfList As Node
Private m_EndOfList As Node
Private m_Count As Integer
Friend Sub New()
MyBase.New()
End Sub
Friend Sub Add(ByVal Node As Node)
If m_StartOfList Is Nothing Then
m_StartOfList = Node
Else
m_EndOfList.m_Next = Node
Node.m_Prev = m_EndOfList
End If
m_EndOfList = Node
m_Count += 1
End Sub
'Searches for a given value in the list. Returns its node's index or -1 if not found.
Friend Function IndexOfValue(ByVal Value As Object) As Integer
Dim currentNode As Node = m_StartOfList
Dim index As Integer = 0
While Not currentNode Is Nothing
If DataIsEqual(currentNode.m_Value, Value) Then
Return index
End If
currentNode = currentNode.m_Next
index += 1
End While
Return -1
End Function
Friend Sub RemoveNode(ByVal NodeToBeDeleted As Node)
Debug.Assert(NodeToBeDeleted IsNot Nothing, "How can we remove a non-existent node ?")
DeleteNode(NodeToBeDeleted, NodeToBeDeleted.m_Prev)
End Sub
'Removes the node at the given index.
' Returns the node that was removed
Friend Function RemoveAt(ByVal Index As Integer) As Node
Dim currentNode As Node = m_StartOfList
Dim currentIndex As Integer = 0
Dim prevNode As Node = Nothing
While currentIndex < Index AndAlso (currentNode IsNot Nothing)
prevNode = currentNode
currentNode = currentNode.m_Next
currentIndex += 1
End While
If (currentNode Is Nothing) Then
Throw New ArgumentOutOfRangeException(NameOf(Index))
End If
DeleteNode(currentNode, prevNode)
Return currentNode
End Function
Friend Function Count() As Integer
Return m_Count
End Function
Friend Sub Clear()
m_StartOfList = Nothing
m_EndOfList = Nothing
m_Count = 0
End Sub
'Retrieves the node at the given index (0-based)
Friend ReadOnly Property Item(ByVal Index As Integer) As Node
Get
Dim node As Node = GetNodeAtIndex(Index)
If (node Is Nothing) Then
Throw New ArgumentOutOfRangeException(NameOf(Index))
End If
Return node
End Get
End Property
Friend Sub Insert(ByVal Index As Integer, ByVal Node As Node)
Dim prevNode As Node = Nothing
' (Index > m_Count) is here for a reason. We allow insertion immediately beyond the end of the
' list i.e. if there are 0 to m_Count -1 elements, we allow insertion into the
' m_Count index
If (Index < 0) OrElse (Index > m_Count) Then
Throw New ArgumentOutOfRangeException(NameOf(Index))
End If
Dim nodeAtIndex As Node = GetNodeAtIndex(Index, prevNode) 'Note: PrevNode passed ByRef
Insert(Node, prevNode, nodeAtIndex)
End Sub
'Inserts a node into the list.
' The item is inserted before NodeToInsertBefore (may not be Nothing).
Friend Sub InsertBefore(ByVal Node As Node, ByVal NodeToInsertBefore As Node)
Debug.Assert(NodeToInsertBefore IsNot Nothing, "FastList.InsertBefore: NodeToInsertBefore may not be nothing")
Insert(Node, NodeToInsertBefore.m_Prev, NodeToInsertBefore)
End Sub
'Inserts a node into the list.
' The item is inserted after NodeToInsertAfter (may not be Nothing).
Friend Sub InsertAfter(ByVal Node As Node, ByVal NodeToInsertAfter As Node)
Debug.Assert(NodeToInsertAfter IsNot Nothing, "FastList.InsertAfter: NodeToInsertAfter may not be nothing")
Insert(Node, NodeToInsertAfter, NodeToInsertAfter.m_Next)
End Sub
'Returns the first node in the list
Friend Function GetFirstListNode() As Node
Return m_StartOfList
End Function
Private Function DataIsEqual(ByVal obj1 As Object, ByVal obj2 As Object) As Boolean
If obj1 Is obj2 Then
Return True
End If
If obj1.GetType() Is obj2.GetType() Then
Return Object.Equals(obj1, obj2)
Else
Return False
End If
End Function
Private Function GetNodeAtIndex(ByVal Index As Integer, Optional ByRef PrevNode As Node = Nothing) As Node
Dim currentNode As Node = m_StartOfList
Dim currentIndex As Integer = 0
PrevNode = Nothing
While currentIndex < Index AndAlso (currentNode IsNot Nothing)
PrevNode = currentNode
currentNode = currentNode.m_Next
currentIndex += 1
End While
Return currentNode
End Function
'Inserts the given node into the list between the two given nodes (may be Nothing at the beginning/end of the list)
Private Sub Insert(ByVal Node As Node, ByVal PrevNode As Node, ByVal CurrentNode As Node)
Node.m_Next = CurrentNode
If Not CurrentNode Is Nothing Then
CurrentNode.m_Prev = Node
End If
If PrevNode Is Nothing Then
m_StartOfList = Node
Else
PrevNode.m_Next = Node
Node.m_Prev = PrevNode
End If
If Node.m_Next Is Nothing Then
m_EndOfList = Node
End If
m_Count += 1
End Sub
Private Sub DeleteNode(ByVal NodeToBeDeleted As Node, ByVal PrevNode As Node)
Debug.Assert(NodeToBeDeleted IsNot Nothing, "How can we delete a non-existent node ?")
If PrevNode Is Nothing Then ' are we are deleting the first node ?
Debug.Assert(NodeToBeDeleted Is m_StartOfList, "How can any node besides the first node not have a previous node ?")
m_StartOfList = m_StartOfList.m_Next
If m_StartOfList Is Nothing Then
m_EndOfList = Nothing
Else
m_StartOfList.m_Prev = Nothing
End If
Else
PrevNode.m_Next = NodeToBeDeleted.m_Next
If PrevNode.m_Next Is Nothing Then
m_EndOfList = PrevNode
Else
PrevNode.m_Next.m_Prev = PrevNode
End If
End If
m_Count -= 1
End Sub
End Class 'FastList
'NOTE: This structure exists so that the debugger windows can show the items in a collection. See the Items property.
Private Structure KeyValuePair
Private m_Key As Object
Private m_Value As Object
Friend Sub New(ByVal NewKey As Object, ByVal NewValue As Object)
m_Key = NewKey
m_Value = NewValue
End Sub
Public ReadOnly Property Key() As Object
Get
Return m_Key
End Get
End Property
Public ReadOnly Property Value() As Object
Get
Return m_Value
End Get
End Property
End Structure
Private Sub AdjustEnumeratorsOnNodeInserted(ByVal NewNode As Node)
AdjustEnumeratorsHelper(NewNode, ForEachEnum.AdjustIndexType.Insert)
End Sub
Private Sub AdjustEnumeratorsOnNodeRemoved(ByVal RemovedNode As Node)
AdjustEnumeratorsHelper(RemovedNode, ForEachEnum.AdjustIndexType.Remove)
End Sub
Private Sub AdjustEnumeratorsHelper(ByVal NewOrRemovedNode As Node, ByVal Type As ForEachEnum.AdjustIndexType)
Debug.Assert(NewOrRemovedNode IsNot Nothing, "AdjustIndexes: Node shouldn't be Nothing")
Dim weakref As WeakReference
Dim i As Integer = m_Iterators.Count - 1
While (i >= 0)
weakref = CType(m_Iterators(i), WeakReference)
If weakref.IsAlive Then
Dim enumerator As ForEachEnum = CType(weakref.Target, ForEachEnum)
If Not enumerator Is Nothing Then
enumerator.Adjust(NewOrRemovedNode, Type) '1 based
End If
Else
m_Iterators.RemoveAt(i)
End If
i -= 1
End While
End Sub
Private Sub IndexCheck(ByVal Index As Integer)
If (Index < 1 OrElse Index > m_ItemsList.Count) Then
Throw New IndexOutOfRangeException(SR.Argument_CollectionIndex)
End If
End Sub
Private Function InternalItemsList() As FastList
Return m_ItemsList
End Function
#Region "Interface Implementation"
'*****************************************************************************
'These methods are 0 based.
'*****************************************************************************
Private Function ICollectionGetEnumerator() As IEnumerator Implements ICollection.GetEnumerator
Return GetEnumerator()
End Function
Private ReadOnly Property ICollectionCount() As Integer Implements ICollection.Count
Get
Return m_ItemsList.Count
End Get
End Property
Private ReadOnly Property ICollectionIsSynchronized() As Boolean Implements ICollection.IsSynchronized
Get
Return False
End Get
End Property
Private ReadOnly Property ICollectionSyncRoot() As Object Implements ICollection.SyncRoot
Get
Return Me
End Get
End Property
Private ReadOnly Property IListIsFixedSize() As Boolean Implements IList.IsFixedSize
Get
Return False
End Get
End Property
Private ReadOnly Property IListIsReadOnly() As Boolean Implements IList.IsReadOnly
Get
Return False
End Get
End Property
Private Sub ICollectionCopyTo(ByVal [array] As System.Array, ByVal index As Integer) Implements ICollection.CopyTo
If [array] Is Nothing Then
Throw New ArgumentNullException(NameOf(array), SR.Format(SR.Argument_InvalidNullValue1, NameOf(array)))
End If
If [array].Rank <> 1 Then
Throw New ArgumentException(SR.Format(SR.Argument_RankEQOne1, NameOf(array)), NameOf(array))
End If
If (index < 0) OrElse ([array].Length - index < Count) Then
Throw New ArgumentException(SR.Format(SR.Argument_InvalidValue1, NameOf(index)), NameOf(index))
End If
Dim i As Integer
Dim objArray As Object() = TryCast(array, Object())
If objArray IsNot Nothing Then
For i = 1 To Count
objArray(index + i - 1) = Me.Item(i)
Next i
Else
For i = 1 To Count
[array].SetValue(Me.Item(i), index + i - 1)
Next i
End If
End Sub
Private Function IListAdd(ByVal value As Object) As Integer Implements IList.Add
Add(value, Nothing)
Return m_ItemsList.Count - 1 'IList is 0 based. Return a 0-based index. If m_ItemsList.Count is zero, we threw during Add() so no need to gate the Count = 0 case.
End Function
Private Sub IListInsert(ByVal index As Integer, ByVal value As Object) Implements IList.Insert
Dim newNode As New Node(Nothing, value)
m_ItemsList.Insert(index, newNode) 'FastList is 0-indexed just like IList, so no transformation of "index" needed
'No key, so no need to add to the hash table.
'Adjust the ForEach iterators
AdjustEnumeratorsOnNodeInserted(newNode)
End Sub
Private Sub IListRemoveAt(ByVal index As Integer) Implements IList.RemoveAt
Dim node As Node = m_ItemsList.RemoveAt(index) '0 based
Debug.Assert(node IsNot Nothing, "Should have thrown exception rather than return Nothing")
AdjustEnumeratorsOnNodeRemoved(node) 'Adjust the ForEach iterators
If node.m_Key IsNot Nothing Then
m_KeyedNodesHash.Remove(node.m_Key)
End If
node.m_Prev = Nothing
node.m_Next = Nothing
End Sub
Private Sub IListRemove(ByVal value As Object) Implements IList.Remove
Dim index As Integer
index = IListIndexOf(value)
If index <> -1 Then
IListRemoveAt(index)
End If
'No exception thrown if not found
End Sub
Private Sub IListClear() Implements IList.Clear
Clear()
End Sub
Private Property IListItem(ByVal index As Integer) As Object Implements IList.Item
Get
Dim node As Node
node = m_ItemsList.Item(index)
Return node.m_Value
End Get
Set(ByVal value As Object)
Dim node As Node = m_ItemsList.Item(index)
node.m_Value = value
End Set
End Property
Private Function IListContains(ByVal value As Object) As Boolean Implements IList.Contains
Return (IListIndexOf(value) <> -1)
End Function
Private Function IListIndexOf(ByVal value As Object) As Integer Implements IList.IndexOf
Return m_ItemsList.IndexOfValue(value)
End Function
#End Region
End Class 'Collection
End Namespace
|
Jiayili1/corefx
|
src/Microsoft.VisualBasic/src/Microsoft/VisualBasic/Collection.vb
|
Visual Basic
|
mit
| 30,541
|
Imports System
Imports System.Data
Imports System.Collections
Imports System.Web.UI
Imports Telerik.Web.UI
Imports SistFoncreagro.BussinessEntities
Imports SistFoncreagro.BussinesLogic
Public Class FrmBienes
Inherits System.Web.UI.Page
Dim _bienMueble As New BIENMUEBLE
Dim bienMueble As BIENMUEBLE
Dim bienMueblePadre As BIENMUEBLE
Dim bienMuebleBL As New BienMuebleBL
Dim IdBienMueble As String
Dim _PlanContable1 As PlanContable
Dim PlanContableBL As New PlanContableBL
Dim _catalogo As Catalogo
Dim catalogoBL As New CatalogoBL
Dim _Responsable As New ResponsableBienMueble
Dim ResponsableBL As New ResponsableBienMuebleBL
Dim _EstadoBien As New EstadoBienMueble
Dim EstadoBienBL As New EstadoBienMuebleBL
Dim _clasificacion As Clasificacion
Dim clasificacionBL As New ClasificacionBL
Dim ParametrosBL As New ParametrosBL
Dim Proveedor As New ProveedorClienteBL
Dim _Proveedor As ProveedorCliente
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
IdBienMueble = Request.QueryString("IdBienMueble")
Me.RadComboBox1.Filter = 1
Me.RadComboBox2.Filter = 1
Me.RadComboBox3.Filter = 1
Me.RadComboBox4.Filter = 1
Me.RadComboBox6.Filter = 1
Me.RadComboBox7.Filter = 1
Me.RadComboBox8.Filter = 1
Me.RadComboBox9.Filter = 1
Me.RadComboBox10.Filter = 1
Me.RadComboBox11.Filter = 1
'para agregarle un evento
Me.ImageButton7.Attributes.Add("onClick", "Abrir(); return false;")
Me.ImageButton8.Attributes.Add("onClick", "Abrir1(); return false;")
Me.TextBox3.Attributes.Add("onChange", "ponerCeros();")
If Page.IsPostBack = False Then
Me.txtDate.Text = Now
If IdBienMueble > 0 Then
'para recuperar datos de transaccion
bienMueble = bienMuebleBL.GetBIENMUEBLEByIdBienMueble(IdBienMueble)
_catalogo = catalogoBL.GetAllFromCatalogoByIdCatalogo(bienMueble.IdCatalogo)
Me.RadComboBox1.DataSourceID = "odsCatalogoBusqueda"
Me.odsCatalogoBusqueda.SelectParameters("tipo").DefaultValue = 0
Me.odsCatalogoBusqueda.SelectParameters("parametro").DefaultValue = _catalogo.Descripcion
Me.RadComboBox1.DataBind()
Me.RadComboBox1.SelectedValue = bienMueble.IdCatalogo
'PARA QUE EL CATALOGO YA NO SE PUEDA EDITAR
Me.RadComboBox1.Enabled = False
Me.TextBox1.Text = bienMueble.Codigo
Me.RadComboBox2.SelectedValue = bienMueble.IdProyecto
If bienMueble.IdCCosto > 0 Then
Me.RadComboBox3.SelectedValue = bienMueble.IdCCosto
End If
Me.RadioButtonList1.SelectedValue = bienMueble.Tipo
If bienMueble.Donacion = "S" Then
Me.CheckBox1.Checked = True
Else
Me.CheckBox1.Checked = False
End If
Me.DropDownList1.SelectedValue = bienMueble.Conservacion
Me.txtDate.Text = bienMueble.FechaIngreso
Me.RadNumericTextBox3.Text = bienMueble.Costo
If bienMueble.IdProveedorCliente > 0 Then
Me.RadComboBox4.SelectedValue = bienMueble.IdProveedorCliente
End If
If bienMueble.IdTipoDocumento > 0 Then
Me.DropDownList4.SelectedValue = bienMueble.IdTipoDocumento
End If
If bienMueble.NroDocumento > 0 Then
Me.TextBox2.Text = bienMueble.NroDocumento
End If
Me.TextBox3.Text = bienMueble.SerieDocumento
If bienMueble.IdBienPadre > 0 Then
bienMueblePadre = bienMuebleBL.GetBIENMUEBLEByIdBienMueble(bienMueble.IdBienPadre)
Me.RadComboBox9.DataSourceID = "OdsBienPadre"
Me.OdsBienPadre.SelectParameters("Texto").DefaultValue = bienMueblePadre.Codigo
Me.RadComboBox9.DataBind()
Me.RadComboBox9.SelectedValue = bienMueble.IdBienPadre
End If
Me.TextBox10.Text = bienMueble.Descripcion
If bienMueble.IdMarca > 0 Then
Me.RadComboBox10.SelectedValue = bienMueble.IdMarca
End If
Me.TextBox4.Text = bienMueble.Modelo
Me.TextBox5.Text = bienMueble.Serie
Me.TextBox6.Text = bienMueble.Placa
Me.TextBox7.Text = bienMueble.Motor
Me.TextBox8.Text = bienMueble.Color
Me.TextBox9.Text = bienMueble.Otro
Me.TextBox11.Text = bienMueble.CodigoReferencia
Me.RadComboBox11.SelectedValue = bienMueble.IdOficina
If bienMueble.IdPlanCuenta > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(bienMueble.IdPlanCuenta)
Me.RadComboBox6.DataSourceID = "odsPlanContable1"
Me.odsPlanContable1.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox6.DataBind()
Me.RadComboBox6.SelectedValue = bienMueble.IdPlanCuenta
End If
If bienMueble.IdPlanDepreciacion > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(bienMueble.IdPlanDepreciacion)
Me.RadComboBox7.DataSourceID = "odsPlanContable2"
Me.odsPlanContable2.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox7.DataBind()
Me.RadComboBox7.SelectedValue = bienMueble.IdPlanDepreciacion
End If
If bienMueble.IdPlanDepreciacion1 > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(bienMueble.IdPlanDepreciacion1)
Me.RadComboBox8.DataSourceID = "odsPlanContable3"
Me.odsPlanContable3.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox8.DataBind()
Me.RadComboBox8.SelectedValue = bienMueble.IdPlanDepreciacion1
End If
If bienMueble.IdProveedorCliente > 0 Then
_Proveedor = Proveedor.GetAllFromProveedorClienteById(bienMueble.IdProveedorCliente)
Me.RadComboBox4.DataSourceID = "odsProveedor"
Me.odsProveedor.SelectParameters("Parametro").DefaultValue = _Proveedor.Ruc
Me.RadComboBox4.DataBind()
Me.RadComboBox4.SelectedValue = bienMueble.IdProveedorCliente
End If
End If
End If
End Sub
Protected Sub RadComboBox1_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox1.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.Catalogo)).CodigoDescripcion.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.Catalogo)).IdCatalogo.ToString()
End Sub
Protected Sub RadComboBox1_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox1.ItemsRequested
If e.Text.Length > 2 Then
Me.odsCatalogoBusqueda.SelectParameters("parametro").DefaultValue = e.Text.ToString
Me.RadComboBox1.DataBind()
End If
End Sub
Protected Sub RadComboBox4_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox4.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.ProveedorCliente)).Ruc.ToString() + " " + (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.ProveedorCliente)).RazonSocial.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.ProveedorCliente)).IdProveedorCliente.ToString()
End Sub
Protected Sub RadComboBox4_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox4.ItemsRequested
If e.Text.Length > 2 Then
Me.RadComboBox4.DataSourceID = "odsProveedor"
Me.odsProveedor.SelectParameters("Parametro").DefaultValue = e.Text.ToString
Me.RadComboBox4.DataBind()
End If
End Sub
Protected Sub RadComboBox6_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox6.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).Cuenta.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).IdPlan.ToString()
End Sub
Protected Sub RadComboBox6_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox6.ItemsRequested
If e.Text.Length > 1 Then
Me.RadComboBox6.DataSourceID = "odsPlanContable1"
Me.odsPlanContable1.SelectParameters("Texto").DefaultValue = e.Text.ToString
Me.RadComboBox6.DataBind()
End If
End Sub
Protected Sub RadComboBox7_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox7.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).Cuenta.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).IdPlan.ToString()
End Sub
Protected Sub RadComboBox7_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox7.ItemsRequested
If e.Text.Length > 1 Then
Me.RadComboBox7.DataSourceID = "odsPlanContable2"
Me.odsPlanContable2.SelectParameters("Texto").DefaultValue = e.Text.ToString
Me.RadComboBox7.DataBind()
End If
End Sub
Protected Sub RadComboBox8_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox8.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).Cuenta.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.PlanContable)).IdPlan.ToString()
End Sub
Protected Sub RadComboBox8_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox8.ItemsRequested
If e.Text.Length > 1 Then
Me.RadComboBox8.DataSourceID = "odsPlanContable3"
Me.odsPlanContable3.SelectParameters("Texto").DefaultValue = e.Text.ToString
Me.RadComboBox8.DataBind()
End If
End Sub
Protected Sub ImageButton3_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton3.Click
Dim cadena_java As String
_bienMueble.Color = Me.TextBox8.Text
_bienMueble.Conservacion = Me.DropDownList1.SelectedValue
_bienMueble.Costo = Me.RadNumericTextBox3.Text
_bienMueble.Descripcion = Me.TextBox10.Text
If Me.CheckBox1.Checked Then
_bienMueble.Donacion = "S"
Else
_bienMueble.Donacion = "N"
End If
_bienMueble.FechaIngreso = Me.txtDate.Text
_bienMueble.IdBienMueble = IdBienMueble
If Me.RadComboBox9.SelectedValue.Length > 0 Then
_bienMueble.IdBienPadre = Me.RadComboBox9.SelectedValue
Else
_bienMueble.IdBienPadre.Equals(DBNull.Value)
End If
_bienMueble.IdCatalogo = Me.RadComboBox1.SelectedValue
If Me.RadComboBox3.SelectedValue.Length > 0 Then
_bienMueble.IdCCosto = Me.RadComboBox3.SelectedValue
Else
_bienMueble.IdCCosto.Equals(DBNull.Value)
End If
If Me.RadComboBox10.SelectedValue.Length > 0 Then
_bienMueble.IdMarca = Me.RadComboBox10.SelectedValue
Else
_bienMueble.IdMarca.Equals(DBNull.Value)
End If
_bienMueble.IdOficina = Me.RadComboBox11.SelectedValue
_bienMueble.IdPlanCuenta = Me.RadComboBox6.SelectedValue
If Me.RadComboBox7.SelectedValue.Length > 0 Then
_bienMueble.IdPlanDepreciacion = Me.RadComboBox7.SelectedValue
Else
_bienMueble.IdPlanDepreciacion.Equals(DBNull.Value)
End If
If Me.RadComboBox8.SelectedValue.Length > 0 Then
_bienMueble.IdPlanDepreciacion1 = Me.RadComboBox8.SelectedValue
Else
_bienMueble.IdPlanDepreciacion1.Equals(DBNull.Value)
End If
If Me.RadComboBox4.SelectedValue.Length > 0 Then
_bienMueble.IdProveedorCliente = Me.RadComboBox4.SelectedValue
Else
_bienMueble.IdProveedorCliente.Equals(DBNull.Value)
End If
_bienMueble.IdProyecto = Me.RadComboBox2.SelectedValue
If Me.DropDownList4.SelectedValue > 0 Then
_bienMueble.IdTipoDocumento = Me.DropDownList4.SelectedValue
Else
_bienMueble.IdTipoDocumento.Equals(DBNull.Value)
End If
_bienMueble.IdUsuario = Session("IdUser")
_bienMueble.Modelo = Me.TextBox4.Text
_bienMueble.Motor = Me.TextBox7.Text
If Me.TextBox2.Text <> "" Then
_bienMueble.NroDocumento = Me.TextBox2.Text
Else
_bienMueble.NroDocumento.Equals(DBNull.Value)
End If
_bienMueble.Otro = Me.TextBox9.Text
_bienMueble.Placa = Me.TextBox6.Text
_bienMueble.Serie = Me.TextBox5.Text
_bienMueble.SerieDocumento = Me.TextBox3.Text
_bienMueble.Tipo = Me.RadioButtonList1.SelectedValue
_bienMueble.CodigoReferencia = Me.TextBox11.Text
If Me.RadioButtonList1.SelectedValue = "A" And Me.RadNumericTextBox3.Text = 0 Then
cadena_java = _
"<script type='text/javascript'> " & _
" alert('¡Para que el Bien sea Activo debe ingresar el Valor de Compra!'); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "AlertaX", cadena_java.ToString, False)
Else
If IdBienMueble > 0 Then
bienMuebleBL.SaveBIENMUEBLE(_bienMueble)
Else
IdBienMueble = bienMuebleBL.SaveBIENMUEBLE(_bienMueble)
End If
Response.Redirect("FrmBienes.aspx?IdBienMueble=" + IdBienMueble.ToString)
End If
End Sub
Protected Sub RadComboBox9_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemEventArgs) Handles RadComboBox9.ItemDataBound
e.Item.Text = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.BIENMUEBLE)).Bien.ToString()
e.Item.Value = (DirectCast(e.Item.DataItem, SistFoncreagro.BussinessEntities.BIENMUEBLE)).IdBienMueble.ToString()
End Sub
Protected Sub RadComboBox9_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs) Handles RadComboBox9.ItemsRequested
If e.Text.Length > 2 Then
Me.RadComboBox9.DataSourceID = "OdsBienPadre"
Me.OdsBienPadre.SelectParameters("Texto").DefaultValue = e.Text.ToString
Me.RadComboBox9.DataBind()
End If
End Sub
Protected Sub ImageButton4_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton4.Click
Response.Redirect("FrmBienes.aspx?IdBienMueble=0")
End Sub
Protected Sub RadGrid1_InsertCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.InsertCommand
Dim userControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
If CType(userControl.FindControl("txtDate2"), TextBox).Text.Length > 0 Then
_Responsable.FechaFin = CType(userControl.FindControl("txtDate2"), TextBox).Text
Else
_Responsable.FechaFin.Equals(DBNull.Value)
End If
_Responsable.FechaInicio = CType(userControl.FindControl("txtDate1"), TextBox).Text
_Responsable.IdBienMueble = IdBienMueble
_Responsable.IdPersonal = CType(userControl.FindControl("RadComboBox1"), RadComboBox).SelectedValue
_Responsable.Observacion = CType(userControl.FindControl("TextBox1"), TextBox).Text
ResponsableBL.SaveRESPONSABLEBIENMUEBLE(_Responsable)
End Sub
Protected Sub RadGrid1_DeleteCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.DeleteCommand
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
Dim id As Int32
id = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdResponsable")
ResponsableBL.DeleteRESPONSABLEBIENMUEBLE(id)
End Sub
Protected Sub RadGrid1_UpdateCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid1.UpdateCommand
Dim userControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
_Responsable.IdResponsable = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdResponsable")
If CType(userControl.FindControl("txtDate2"), TextBox).Text.Length > 0 Then
_Responsable.FechaFin = CType(userControl.FindControl("txtDate2"), TextBox).Text
Else
_Responsable.FechaFin.Equals(DBNull.Value)
End If
_Responsable.FechaInicio = CType(userControl.FindControl("txtDate1"), TextBox).Text
_Responsable.IdBienMueble = IdBienMueble
_Responsable.IdPersonal = CType(userControl.FindControl("RadComboBox1"), RadComboBox).SelectedValue
_Responsable.Observacion = CType(userControl.FindControl("TextBox1"), TextBox).Text
ResponsableBL.SaveRESPONSABLEBIENMUEBLE(_Responsable)
End Sub
Protected Sub RadGrid2_InsertCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid2.InsertCommand
Dim userControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
_EstadoBien.FechaInicio = CType(userControl.FindControl("txtDate1"), TextBox).Text
_EstadoBien.IdBienMueble = IdBienMueble
_EstadoBien.IdTipo = CType(userControl.FindControl("RadComboBox1"), RadComboBox).SelectedValue
_EstadoBien.Observacion = CType(userControl.FindControl("TextBox1"), TextBox).Text
_EstadoBien.DocumentoBaja = CType(userControl.FindControl("TextBox3"), TextBox).Text
If CType(userControl.FindControl("RadComboBox2"), RadComboBox).Text.Length > 0 Then
_EstadoBien.IdMotivo = CType(userControl.FindControl("RadComboBox2"), RadComboBox).SelectedValue
Else
_EstadoBien.IdMotivo.Equals(DBNull.Value)
End If
If CType(userControl.FindControl("CheckBox1"), CheckBox).Checked Then
_EstadoBien.BajaContable = "S"
Else
_EstadoBien.BajaContable = "N"
End If
If CType(userControl.FindControl("CheckBox2"), CheckBox).Checked Then
_EstadoBien.BajaPatrimonio = "S"
Else
_EstadoBien.BajaPatrimonio = "N"
End If
EstadoBienBL.SaveESTADOBIENMUEBLE(_EstadoBien)
End Sub
Protected Sub RadGrid2_UpdateCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid2.UpdateCommand
Dim userControl As UserControl = CType(e.Item.FindControl(GridEditFormItem.EditFormUserControlID), UserControl)
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
_EstadoBien.IdEstado = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdEstado")
_EstadoBien.FechaInicio = CType(userControl.FindControl("txtDate1"), TextBox).Text
_EstadoBien.IdBienMueble = IdBienMueble
_EstadoBien.IdTipo = CType(userControl.FindControl("RadComboBox1"), RadComboBox).SelectedValue
_EstadoBien.Observacion = CType(userControl.FindControl("TextBox1"), TextBox).Text
_EstadoBien.DocumentoBaja = CType(userControl.FindControl("TextBox3"), TextBox).Text
If CType(userControl.FindControl("RadComboBox2"), RadComboBox).Text.Length > 0 Then
_EstadoBien.IdMotivo = CType(userControl.FindControl("RadComboBox2"), RadComboBox).SelectedValue
Else
_EstadoBien.IdMotivo.Equals(DBNull.Value)
End If
If CType(userControl.FindControl("CheckBox1"), CheckBox).Checked Then
_EstadoBien.BajaContable = "S"
Else
_EstadoBien.BajaContable = "N"
End If
If CType(userControl.FindControl("CheckBox2"), CheckBox).Checked Then
_EstadoBien.BajaPatrimonio = "S"
Else
_EstadoBien.BajaPatrimonio = "N"
End If
EstadoBienBL.SaveESTADOBIENMUEBLE(_EstadoBien)
End Sub
Protected Sub RadGrid2_DeleteCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadGrid2.DeleteCommand
Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
Dim id As Int32
id = editedItem.OwnerTableView.DataKeyValues(editedItem.ItemIndex)("IdEstado")
EstadoBienBL.DeleteESTADOBIENMUEBLE(id)
End Sub
Protected Sub RadAjaxManager1_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles RadAjaxManager1.AjaxRequest
If e.Argument = "ActualizarLista" Then
Me.RadComboBox4.DataBind()
ElseIf e.Argument = "ActualizarLista1" Then
Me.RadComboBox10.DataBind()
End If
End Sub
Protected Sub RadComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs) Handles RadComboBox1.SelectedIndexChanged
_clasificacion = clasificacionBL.GetCLASIFICACIONByIdCatalogo(Me.RadComboBox1.SelectedValue)
If _clasificacion.IdPlanActivoFijo > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(_clasificacion.IdPlanActivoFijo)
Me.RadComboBox6.DataSourceID = "odsPlanContable1"
Me.odsPlanContable1.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox6.DataBind()
Me.RadComboBox6.SelectedValue = _clasificacion.IdPlanActivoFijo
End If
If _clasificacion.IdPlanDepreciacion > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(_clasificacion.IdPlanDepreciacion)
Me.RadComboBox7.DataSourceID = "odsPlanContable2"
Me.odsPlanContable2.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox7.DataBind()
Me.RadComboBox7.SelectedValue = _clasificacion.IdPlanDepreciacion
End If
If _clasificacion.IdPlanDepreciacion1 > 0 Then
_PlanContable1 = PlanContableBL.GetPLANCONTABLEByIdPlan(_clasificacion.IdPlanDepreciacion1)
Me.RadComboBox8.DataSourceID = "odsPlanContable3"
Me.odsPlanContable3.SelectParameters("Texto").DefaultValue = _PlanContable1.Nombre
Me.RadComboBox8.DataBind()
Me.RadComboBox8.SelectedValue = _clasificacion.IdPlanDepreciacion1
End If
End Sub
Protected Sub RadNumericTextBox3_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles RadNumericTextBox3.TextChanged
Dim valor As Decimal
valor = ParametrosBL.GetValorUIT(Me.txtDate.Text).valor
If Me.RadNumericTextBox3.Text >= valor / 4 Then
Me.RadioButtonList1.SelectedValue = "A"
Else
Me.RadioButtonList1.SelectedValue = "C"
End If
End Sub
Protected Sub txtDate_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtDate.TextChanged
Dim valor As Decimal
Try
valor = ParametrosBL.GetValorUIT(Me.txtDate.Text).valor
If Me.RadNumericTextBox3.Text >= valor / 4 Then
Me.RadioButtonList1.SelectedValue = "A"
Else
Me.RadioButtonList1.SelectedValue = "C"
End If
Catch ex As Exception
Dim cadena_java As String = _
"<script type='text/javascript'> " & _
" Alerta('¡Debe ingresar el valor de la UIT!'); " & _
Chr(60) & "/script>"
ScriptManager.RegisterStartupScript(Page, GetType(Page), "AlertaX", cadena_java.ToString, False)
End Try
End Sub
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Patrimonio/Formularios/FrmBienes.aspx.vb
|
Visual Basic
|
mit
| 25,224
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("VBFindContacts2")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("Independentsoft")>
<Assembly: AssemblyProduct("VBFindContacts2")>
<Assembly: AssemblyCopyright("Copyright © Independentsoft 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("038aebe3-4014-4887-bf50-de4bd9a2f75d")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBFindContacts2/My Project/AssemblyInfo.vb
|
Visual Basic
|
mit
| 1,178
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmRPfilter
#Region "Windows Form Designer generated code "
<System.Diagnostics.DebuggerNonUserCode()> Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
If Disposing Then
If Not components Is Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(Disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
Public ToolTip1 As System.Windows.Forms.ToolTip
Public WithEvents cmdExit As System.Windows.Forms.Button
Public WithEvents cmdPrint As System.Windows.Forms.Button
Public WithEvents cmdNamespace As System.Windows.Forms.Button
Public WithEvents lblHeading As System.Windows.Forms.Label
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmRPfilter))
Me.components = New System.ComponentModel.Container()
Me.ToolTip1 = New System.Windows.Forms.ToolTip(components)
Me.cmdExit = New System.Windows.Forms.Button
Me.cmdPrint = New System.Windows.Forms.Button
Me.cmdNamespace = New System.Windows.Forms.Button
Me.lblHeading = New System.Windows.Forms.Label
Me.SuspendLayout()
Me.ToolTip1.Active = True
Me.BackColor = System.Drawing.Color.FromARGB(224, 224, 224)
Me.Text = "Select the filter for your Report"
Me.ClientSize = New System.Drawing.Size(462, 123)
Me.Location = New System.Drawing.Point(4, 23)
Me.ControlBox = False
Me.KeyPreview = True
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable
Me.Enabled = True
Me.MaximizeBox = True
Me.MinimizeBox = True
Me.Cursor = System.Windows.Forms.Cursors.Default
Me.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.ShowInTaskbar = True
Me.HelpButton = False
Me.WindowState = System.Windows.Forms.FormWindowState.Normal
Me.Name = "frmRPfilter"
Me.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdExit.Text = "E&xit"
Me.cmdExit.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(178, Byte))
Me.cmdExit.Size = New System.Drawing.Size(97, 52)
Me.cmdExit.Location = New System.Drawing.Point(363, 66)
Me.cmdExit.TabIndex = 3
Me.cmdExit.TabStop = False
Me.cmdExit.BackColor = System.Drawing.SystemColors.Control
Me.cmdExit.CausesValidation = True
Me.cmdExit.Enabled = True
Me.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdExit.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdExit.Name = "cmdExit"
Me.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdPrint.Text = "&Print"
Me.cmdPrint.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(178, Byte))
Me.cmdPrint.Size = New System.Drawing.Size(97, 52)
Me.cmdPrint.Location = New System.Drawing.Point(159, 66)
Me.cmdPrint.TabIndex = 2
Me.cmdPrint.BackColor = System.Drawing.SystemColors.Control
Me.cmdPrint.CausesValidation = True
Me.cmdPrint.Enabled = True
Me.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdPrint.TabStop = True
Me.cmdPrint.Name = "cmdPrint"
Me.cmdNamespace.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
Me.cmdNamespace.Text = "&Filter"
Me.cmdNamespace.Font = New System.Drawing.Font("Arial", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(178, Byte))
Me.cmdNamespace.Size = New System.Drawing.Size(97, 52)
Me.cmdNamespace.Location = New System.Drawing.Point(363, 3)
Me.cmdNamespace.TabIndex = 1
Me.cmdNamespace.TabStop = False
Me.cmdNamespace.BackColor = System.Drawing.SystemColors.Control
Me.cmdNamespace.CausesValidation = True
Me.cmdNamespace.Enabled = True
Me.cmdNamespace.ForeColor = System.Drawing.SystemColors.ControlText
Me.cmdNamespace.Cursor = System.Windows.Forms.Cursors.Default
Me.cmdNamespace.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.cmdNamespace.Name = "cmdNamespace"
Me.lblHeading.Text = "Using the ""Stock Item Selector"" ....."
Me.lblHeading.Size = New System.Drawing.Size(349, 52)
Me.lblHeading.Location = New System.Drawing.Point(3, 3)
Me.lblHeading.TabIndex = 0
Me.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft
Me.lblHeading.BackColor = System.Drawing.SystemColors.Control
Me.lblHeading.Enabled = True
Me.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText
Me.lblHeading.Cursor = System.Windows.Forms.Cursors.Default
Me.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.lblHeading.UseMnemonic = True
Me.lblHeading.Visible = True
Me.lblHeading.AutoSize = False
Me.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
Me.lblHeading.Name = "lblHeading"
Me.Controls.Add(cmdExit)
Me.Controls.Add(cmdPrint)
Me.Controls.Add(cmdNamespace)
Me.Controls.Add(lblHeading)
Me.ResumeLayout(False)
Me.PerformLayout()
End Sub
#End Region
End Class
|
nodoid/PointOfSale
|
VB/4PosBackOffice.NET/frmRPfilter.Designer.vb
|
Visual Basic
|
mit
| 6,029
|
Option Explicit On
Option Strict On
Namespace CompuMaster.Calendar
''' <summary>
''' A range of months
''' </summary>
Public Class MonthRange
Implements IComparable
Public Sub New(firstPeriod As CompuMaster.Calendar.Month, lastPeriod As CompuMaster.Calendar.Month)
If firstPeriod Is Nothing Then Throw New ArgumentNullException(NameOf(firstPeriod))
If lastPeriod Is Nothing Then Throw New ArgumentNullException(NameOf(lastPeriod))
If firstPeriod > lastPeriod Then Throw New ArgumentException("First period must be before last period")
Me._FirstMonth = firstPeriod
Me._LastMonth = lastPeriod
End Sub
Private _FirstMonth As CompuMaster.Calendar.Month
Public ReadOnly Property FirstMonth As CompuMaster.Calendar.Month
Get
Return _FirstMonth
End Get
End Property
Private _LastMonth As CompuMaster.Calendar.Month
Public ReadOnly Property LastMonth As CompuMaster.Calendar.Month
Get
Return _LastMonth
End Get
End Property
Public Overrides Function ToString() As String
Return Me.FirstMonth.ToString & " - " & Me.LastMonth.ToString
End Function
''' <summary>
''' Compares a value to the current instance value
''' </summary>
''' <param name="obj"></param>
''' <returns>-1 if value is smaller, +1 if value is greater, 0 if value equals</returns>
Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
Return Me.CompareTo(CType(obj, MonthRange))
End Function
''' <summary>
''' Equals method for MonthRange classes
''' </summary>
''' <param name="obj"></param>
''' <returns></returns>
Public Overrides Function Equals(obj As Object) As Boolean
If ReferenceEquals(Me, obj) Then
Return True
End If
If obj Is Nothing Then
Return False
End If
If GetType(MonthRange).IsInstanceOfType(obj) = False Then
Return False
End If
Return Me.FirstMonth = CType(obj, MonthRange).FirstMonth AndAlso Me.LastMonth = CType(obj, MonthRange).LastMonth
End Function
''' <summary>
''' Equals method for MonthRange classes
''' </summary>
''' <param name="value"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Overloads Function Equals(ByVal value As MonthRange) As Boolean
If value IsNot Nothing Then
If Me.FirstMonth = value.FirstMonth AndAlso Me.LastMonth = value.LastMonth Then
Return True
Else
Return False
End If
Else
Return False
End If
End Function
''' <summary>
''' Compares a value to the current instance value
''' </summary>
''' <param name="value"></param>
''' <returns>-1 if value is smaller, +1 if value is greater, 0 if value equals</returns>
Public Function CompareTo(value As MonthRange) As Integer
If value Is Nothing Then
Return 1
ElseIf Me.FirstMonth < value.FirstMonth Then
Return -1
ElseIf Me.FirstMonth > value.FirstMonth Then
Return 1
ElseIf Me.LastMonth < value.LastMonth Then
Return -1
ElseIf Me.LastMonth > value.LastMonth Then
Return 1
Else
Return 0
End If
End Function
''' <summary>
''' Equals operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator =(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return True
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return False
Else
Return value1.Equals(value2)
End If
End Operator
''' <summary>
''' Not-Equals operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator <>(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return False
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return True
Else
Return Not value1.Equals(value2)
End If
End Operator
''' <summary>
''' Smaller than operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator <(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return False
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return True
Else
Return value1.CompareTo(value2) < 0
End If
End Operator
''' <summary>
''' Greater than operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator >(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return False
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return False
Else
Return value1.CompareTo(value2) > 0
End If
End Operator
''' <summary>
''' Smaller than operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator <=(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return True
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return True
Else
Return value1.CompareTo(value2) <= 0
End If
End Operator
''' <summary>
''' Greater than operator for Month classes
''' </summary>
''' <param name="value1"></param>
''' <param name="value2"></param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Operator >=(ByVal value1 As MonthRange, ByVal value2 As MonthRange) As Boolean
If value1 Is Nothing And value2 Is Nothing Then
Return True
ElseIf value1 Is Nothing And value2 IsNot Nothing Then
Return False
Else
Return value1.CompareTo(value2) >= 0
End If
End Operator
''' <summary>
''' The number of months covered by the range
''' </summary>
''' <returns></returns>
Public ReadOnly Property MonthCount As Integer
Get
Return Me._LastMonth - Me._FirstMonth + 1
End Get
End Property
Private _Months As Month()
#Disable Warning CA1819 ' Properties should not return arrays
''' <summary>
''' All months covered by the range
''' </summary>
''' <returns></returns>
Public ReadOnly Property Months As Month()
#Enable Warning CA1819 ' Properties should not return arrays
Get
If _Months Is Nothing Then
Dim AllMonths As New List(Of Month)
Dim CurrentMonth As Month = Me._FirstMonth
Do While CurrentMonth <= Me._LastMonth
AllMonths.Add(CurrentMonth)
CurrentMonth = CurrentMonth.NextPeriod
Loop
_Months = AllMonths.ToArray
End If
Return _Months
End Get
End Property
''' <summary>
''' Is a specified Month a member of this range
''' </summary>
''' <param name="value"></param>
''' <returns></returns>
Public Function Contains(value As Month) As Boolean
Return value >= Me.FirstMonth AndAlso value <= Me.LastMonth
End Function
''' <summary>
''' Is a specified MonthRange a member of this range
''' </summary>
''' <param name="value"></param>
''' <returns></returns>
Public Function Contains(value As MonthRange) As Boolean
If value Is Nothing Then Throw New ArgumentNullException(NameOf(value))
Return value.FirstMonth >= Me.FirstMonth AndAlso value.LastMonth <= Me.LastMonth
End Function
End Class
End Namespace
|
CompuMasterGmbH/CompuMaster.Calendar
|
CompuMaster.Calendar/MonthRange.vb
|
Visual Basic
|
mit
| 9,552
|
Imports System.Xml
Imports System.Globalization
Imports System.Linq
Namespace Ventrian.NewsArticles.API.MetaWebLog
Friend Class XmlrpcRequest
#Region "Private Members"
Private _inputParams As List(Of XmlNode)
#End Region
#Region "Constructor"
Public Sub New(input As HttpContext)
Dim inputXml = ParseRequest(input)
LoadXmlRequest(inputXml)
End Sub
#End Region
#Region "Properties"
Public Property AppKey As String
Public Property BlogId As String
Public Property MediaObject As MetaMediaInfo
Public Property MethodName As String
Public Property NumberOfPosts As Integer
Public Property Password As String
Public Property Post As MetaPostInfo
Public Property PostId As String
Public Property Publish As Boolean
Public Property UserName As String
#End Region
#Region "Methods"
Private Shared Function GetMediaObject(node As XmlNode) As MetaMediaInfo
Dim name = node.SelectSingleNode("value/struct/member[name='name']")
Dim type = node.SelectSingleNode("value/struct/member[name='type']")
Dim bits = node.SelectSingleNode("value/struct/member[name='bits']")
Dim temp = New MetaMediaInfo() With { _
.name = If(name Is Nothing, String.Empty, name.LastChild.InnerText), _
.type = If(type Is Nothing, "notsent", type.LastChild.InnerText), _
.bits = Convert.FromBase64String(If(bits Is Nothing, String.Empty, bits.LastChild.InnerText)) _
}
Return temp
End Function
Private Shared Function GetPost(node As XmlNode) As MetaPostInfo
Dim temp = New MetaPostInfo()
' Require Title and Description
Dim title = node.SelectSingleNode("value/struct/member[name='title']")
If title Is Nothing Then
Throw New MetaException("05", "Page Struct Element, Title, not Sent.")
End If
temp.title = title.LastChild.InnerText
Dim description = node.SelectSingleNode("value/struct/member[name='description']")
If description Is Nothing Then
Throw New MetaException("05", "Page Struct Element, Description, not Sent.")
End If
temp.description = description.LastChild.InnerText
Dim link = node.SelectSingleNode("value/struct/member[name='link']")
temp.link = If(link Is Nothing, String.Empty, link.LastChild.InnerText)
Dim excerpt = node.SelectSingleNode("value/struct/member[name='mt_excerpt']")
temp.excerpt = If(excerpt Is Nothing, String.Empty, excerpt.LastChild.InnerText)
Dim cats = New List(Of String)()
Dim categories = node.SelectSingleNode("value/struct/member[name='categories']")
If categories IsNot Nothing Then
Dim categoryArray = categories.LastChild
Dim categoryArrayNodes As XmlNodeList = categoryArray.SelectNodes("array/data/value/string")
If categoryArrayNodes IsNot Nothing Then
For Each objNode As XmlNode In categoryArrayNodes
cats.Add(objNode.InnerText)
Next
End If
End If
temp.categories = cats
' postDate has a few different names to worry about
Dim dateCreated = node.SelectSingleNode("value/struct/member[name='dateCreated']")
Dim pubDate = node.SelectSingleNode("value/struct/member[name='pubDate']")
If dateCreated IsNot Nothing Then
Try
Dim tempDate = dateCreated.LastChild.InnerText
temp.postDate = DateTime.ParseExact(tempDate, "yyyyMMdd'T'HH':'mm':'ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
Catch ex As Exception
' Ignore PubDate Error
Debug.WriteLine(ex.Message)
End Try
ElseIf pubDate IsNot Nothing Then
Try
Dim tempPubDate = pubDate.LastChild.InnerText
temp.postDate = DateTime.ParseExact(tempPubDate, "yyyyMMdd'T'HH':'mm':'ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)
Catch ex As Exception
' Ignore PubDate Error
Debug.WriteLine(ex.Message)
End Try
End If
' WLW tags implementation using mt_keywords
Dim tags = New List(Of String)()
Dim keywords = node.SelectSingleNode("value/struct/member[name='mt_keywords']")
If keywords IsNot Nothing Then
Dim tagsList = keywords.LastChild.InnerText
For Each item As String In tagsList.Split(","c)
If (item.Trim() <> "") Then
tags.Add(item.Trim())
End If
Next
End If
temp.tags = tags
Return temp
End Function
Private Sub LoadXmlRequest(xml As String)
Dim request = New XmlDocument()
Try
If Not (xml.StartsWith("<?xml") OrElse xml.StartsWith("<method")) Then
xml = xml.Substring(xml.IndexOf("<?xml", StringComparison.Ordinal))
End If
request.LoadXml(xml)
Catch ex As Exception
Throw New MetaException("01", String.Format("Invalid XMLRPC Request. ({0})", ex.Message))
End Try
' Method name is always first
If request.DocumentElement IsNot Nothing Then
MethodName = request.DocumentElement.ChildNodes(0).InnerText
End If
' Throw New MetaException("01", xml.ToString())
' Parameters are next (and last)
Dim xmlParams As XmlNodeList = request.SelectNodes("/methodCall/params/param")
If xmlParams IsNot Nothing Then
_inputParams = xmlParams.Cast(Of XmlNode)().ToList()
End If
' Determine what params are what by method name
Select Case MethodName
Case "metaWeblog.newPost"
BlogId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
Post = GetPost(_inputParams(3))
Publish = _inputParams(4).InnerText <> "0" AndAlso _inputParams(4).InnerText <> "false"
Exit Select
Case "metaWeblog.editPost"
PostId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
Post = GetPost(_inputParams(3))
Publish = _inputParams(4).InnerText <> "0" AndAlso _inputParams(4).InnerText <> "false"
Exit Select
Case "metaWeblog.getPost"
PostId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
Exit Select
Case "metaWeblog.newMediaObject"
BlogId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
MediaObject = GetMediaObject(_inputParams(3))
Exit Select
Case "metaWeblog.getCategories", "wp.getTags"
BlogId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
Exit Select
Case "metaWeblog.getRecentPosts"
BlogId = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
NumberOfPosts = Int32.Parse(_inputParams(3).InnerText, CultureInfo.InvariantCulture)
Exit Select
Case "blogger.getUsersBlogs", "metaWeblog.getUsersBlogs"
AppKey = _inputParams(0).InnerText
UserName = _inputParams(1).InnerText
Password = _inputParams(2).InnerText
Exit Select
Case "blogger.deletePost"
AppKey = _inputParams(0).InnerText
PostId = _inputParams(1).InnerText
UserName = _inputParams(2).InnerText
Password = _inputParams(3).InnerText
Publish = _inputParams(4).InnerText <> "0" AndAlso _inputParams(4).InnerText <> "false"
Exit Select
Case Else
Throw New MetaException("02", String.Format("Unknown Method. ({0})", MethodName))
End Select
End Sub
Private Shared Function ParseRequest(context As HttpContext) As String
Dim buffer = New Byte(context.Request.InputStream.Length - 1) {}
context.Request.InputStream.Position = 0
context.Request.InputStream.Read(buffer, 0, buffer.Length)
Return Encoding.UTF8.GetString(buffer)
End Function
#End Region
End Class
End Namespace
|
ventrian/News-Articles
|
API/MetaWebLog/XmlrpcRequest.vb
|
Visual Basic
|
mit
| 9,706
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rImportacion_ValoresArticulos"
'-------------------------------------------------------------------------------------------'
Partial Class rImportacion_ValoresArticulos
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
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 lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loSeleccion As New StringBuilder()
loSeleccion.AppendLine("")
loSeleccion.AppendLine("SELECT YEAR(Importaciones.Fec_Ini) AS Ano, ")
loSeleccion.AppendLine(" MONTH(Importaciones.Fec_Ini) AS Mes, ")
loSeleccion.AppendLine(" Importaciones.Fec_Ini AS Fec_Ini, ")
loSeleccion.AppendLine(" Importaciones.Expediente AS Expediente, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Tip_Ori AS Tip_Ori, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Doc_Ori AS Doc_Ori, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Ren_Ori AS Ren_Ori,")
loSeleccion.AppendLine(" Renglones_Importaciones.Cod_Art AS Cod_Art, ")
loSeleccion.AppendLine(" Articulos.Cod_Dep AS Departamento, ")
loSeleccion.AppendLine(" Articulos.Cod_Cla AS Clase, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Can_Art1 AS Can_Art1, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Fob AS Mon_Fob, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Seg AS Mon_Seg, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Fle AS Mon_Fle, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Cif AS Mon_Cif, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Alm AS Mon_Alm, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ipt AS Mon_Ipt, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Por AS Mon_Por, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Tra AS Mon_Tra, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Per AS Mon_Per, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ban AS Mon_Ban, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Adu AS Mon_Adu, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Arc AS Mon_Arc, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ots1 AS Mon_Ots1, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ots2 AS Mon_Ots2, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ots3 AS Mon_Ots3, ")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Ara AS Mon_Ara,")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Gas_Fij AS Mon_Gas_Fij,")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Gas_Adi AS Mon_Gas_Adi,")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Com_Pag AS Mon_Com_Pag,")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Gas_Com AS Mon_Gas_Com,")
loSeleccion.AppendLine(" Renglones_Importaciones.Mon_Net AS Mon_Net,")
loSeleccion.AppendLine(" ROUND(Renglones_Importaciones.Mon_Net/ ")
loSeleccion.AppendLine(" (CASE WHEN Renglones_Importaciones.Can_Art1>0 ")
loSeleccion.AppendLine(" THEN Renglones_Importaciones.Can_Art1 ")
loSeleccion.AppendLine(" ELSE 1 END), 2) AS Mon_Net_Uni")
loSeleccion.AppendLine("FROM Importaciones ")
loSeleccion.AppendLine(" JOIN Renglones_Importaciones ")
loSeleccion.AppendLine(" ON (Renglones_Importaciones.Documento = Importaciones.Documento) ")
loSeleccion.AppendLine(" JOIN Articulos")
loSeleccion.AppendLine(" ON (Articulos.Cod_Art = Renglones_Importaciones.Cod_Art) ")
loSeleccion.AppendLine(" WHERE Importaciones.Documento BETWEEN " & lcParametro0Desde)
loSeleccion.AppendLine(" AND " & lcParametro0Hasta)
loSeleccion.AppendLine(" AND Importaciones.Fec_Ini BETWEEN " & lcParametro1Desde)
loSeleccion.AppendLine(" AND " & lcParametro1Hasta)
loSeleccion.AppendLine(" AND Importaciones.Cod_Pro BETWEEN " & lcParametro2Desde)
loSeleccion.AppendLine(" AND " & lcParametro2Hasta)
loSeleccion.AppendLine(" AND Renglones_Importaciones.Cod_Art BETWEEN " & lcParametro3Desde)
loSeleccion.AppendLine(" AND " & lcParametro3Hasta)
loSeleccion.AppendLine(" AND Importaciones.Cod_Mon BETWEEN " & lcParametro4Desde)
loSeleccion.AppendLine(" AND " & lcParametro4Hasta)
loSeleccion.AppendLine("ORDER BY " & lcOrdenamiento & ", Importaciones.Fec_Ini, Importaciones.Fec_Fin")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
loSeleccion.AppendLine("")
Dim loServicios As New cusDatos.goDatos
Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loSeleccion.ToString(), "curReportes")
'-------------------------------------------------------------------------------------------'
' Selección de opcion por excel (Microsoft Excel - xls)
'-------------------------------------------------------------------------------------------'
If (Me.Request.QueryString("salida").ToLower() = "xls") Then
' Genera el archivo a partir de la tabla de datos y termina la ejecución
Me.mGenerarArchivoExcel(laDatosReporte)
End If
'-------------------------------------------------------------------------------------------------------
' 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("rImportacion_ValoresArticulos", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrImportacion_ValoresArticulos.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
Private Sub mGenerarArchivoExcel(ByVal loDatos As DataSet)
'-------------------------------------------------------------------------------------------'
' Prepara los datos para enviarlos al servicio web de Excel. '
'-------------------------------------------------------------------------------------------'
Dim loSalida As New IO.MemoryStream()
loDatos.WriteXml(loSalida, XmlWriteMode.WriteSchema)
'-------------------------------------------------------------------------------------------'
' Prepara los parámetros adicionales para enviarlos junto con los datos.'
'-------------------------------------------------------------------------------------------'
Dim lnDecimalesMonto As Integer = goOpciones.pnDecimalesParaMonto
Dim lnDecimalesCantidad As Integer = goOpciones.pnDecimalesParaCantidad
Dim lnDecimalesPorcentaje As Integer = goOpciones.pnDecimalesParaPorcentaje
Dim loParametros As New NameValueCollection()
loParametros.Add("lcNombreEmpresa", cusAplicacion.goEmpresa.pcNombre)
loParametros.Add("lcRifEmpresa", cusAplicacion.goEmpresa.pcRifEmpresa)
loParametros.Add("lnDecimalesMonto", lnDecimalesMonto.ToString())
loParametros.Add("lnDecimalesCantidad", lnDecimalesCantidad.ToString())
loParametros.Add("lnDecimalesPorcentaje", lnDecimalesPorcentaje.ToString())
Dim loClienteWeb As New System.Net.WebClient()
loClienteWeb.QueryString = loParametros
'-------------------------------------------------------------------------------------------'
' Envía los datos y parámetros, y espera la respuesta. '
'-------------------------------------------------------------------------------------------'
Dim loRespuesta As Byte()
Try
Dim lcRuta As String = Me.MapPath("~\Framework\Xml\ParametrosGlobales.xml")
Dim loParam As New System.Xml.XmlDocument()
loParam.Load(lcRuta)
Dim lcServicio As String = loParam.DocumentElement.GetAttribute("Servicios")
loRespuesta = loClienteWeb.UploadData(lcServicio & "/Reportes/rImportacion_ValoresArticulos_xlsx.aspx", loSalida.GetBuffer())
Catch ex As Exception
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Proceso no Completado", _
"No fue posible generar el reporte solicitado. Información Adicional: <br/>" & _
ex.ToString(), vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, "600px", "500px")
Return
End Try
'-------------------------------------------------------------------------------------------'
' Vemos si la respuesta es TextoPlano (error) o no (el archivo Excel '
' generado). Si el tipo está vacio : error desconocido. '
'-------------------------------------------------------------------------------------------'
Dim loTipoRespuesta As String = loClienteWeb.ResponseHeaders("Content-Type")
If String.IsNullOrEmpty(loTipoRespuesta) Then
'-------------------------------------------------------------------------------------------'
'Error no especificado!
'-------------------------------------------------------------------------------------------'
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Proceso no Completado", _
"No fue posible generar el reporte solicitado. Información Adicional: El servicio que genera la salida XSLX no responde.<br/>", _
vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, "600px", "500px")
Return
ElseIf loTipoRespuesta.ToLower().StartsWith("text/plain") Then
Dim lcMensaje As String = UTF32Encoding.UTF8.GetString(loRespuesta)
lcMensaje = Me.Server.HtmlEncode(lcMensaje)
Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Proceso no Completado", _
"No fue posible generar el reporte solicitado. Información Adicional: <br/>" & _
lcMensaje, vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, "600px", "500px")
Return
Else
'-------------------------------------------------------------------------------------------'
'Generación exitosa: la respuesta es el archivo en excel para descargar
'-------------------------------------------------------------------------------------------'
Me.Response.Clear()
Me.Response.Buffer = True
Me.Response.AppendHeader("content-disposition", "attachment; filename=rImportacion_ValoresArticulos.xlsx")
Me.Response.ContentType = "application/excel"
Me.Response.BinaryWrite(loRespuesta)
Me.Response.End()
End If
End Sub
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
Try
loObjetoReporte.Close()
Catch loExcepcion As Exception
End Try
End Sub
End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo
'-------------------------------------------------------------------------------------------'
' RJG: 27/06/15: Programacion inicial.
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rImportacion_ValoresArticulos.aspx.vb
|
Visual Basic
|
mit
| 16,708
|
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 draftDocument As SolidEdgeDraft.DraftDocument = Nothing
Dim sheet As SolidEdgeDraft.Sheet = Nothing
Dim leaders As SolidEdgeFrameworkSupport.Leaders = 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
draftDocument = CType(documents.Add("SolidEdge.DraftDocument"), SolidEdgeDraft.DraftDocument)
sheet = draftDocument.ActiveSheet
leaders = CType(sheet.Leaders, SolidEdgeFrameworkSupport.Leaders)
leaders.ClearStyle()
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.Leaders.ClearStyle.vb
|
Visual Basic
|
mit
| 1,444
|
Namespace Commands
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>08/02/2014 18:08:02</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Caerus\_Commands\Generated\DirectoryCommands.tt</generator-source>
''' <generator-template>Text-Templates\Classes\VB_Object.tt</generator-template>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Caerus\_Commands\Generated\DirectoryCommands.tt", "1")> _
<Leviathan.Commands.Command(ResourceContainingType:=GetType(DirectoryCommands), ResourceName:="CommandDetails", Name:="directory", Description:="@commandDirectoryDescription@", Hidden:=False)> _
Partial Public Class DirectoryCommands
Inherits System.Object
#Region " Public Constructors "
''' <summary>Parametered Constructor (1 Parameters)</summary>
Public Sub New( _
ByVal _Host As Leviathan.Commands.ICommandsExecution _
)
MyBase.New()
Host = _Host
End Sub
#End Region
#Region " Public Constants "
''' <summary>Public Shared Reference to the Name of the Property: Host</summary>
''' <remarks></remarks>
Public Const PROPERTY_HOST As String = "Host"
#End Region
#Region " Private Variables "
''' <summary>Private Data Storage Variable for Property: Host</summary>
''' <remarks></remarks>
Private m_Host As Leviathan.Commands.ICommandsExecution
#End Region
#Region " Public Properties "
''' <summary>Provides Access to the Property: Host</summary>
''' <remarks></remarks>
Public Property Host() As Leviathan.Commands.ICommandsExecution
Get
Return m_Host
End Get
Set(value As Leviathan.Commands.ICommandsExecution)
m_Host = value
End Set
End Property
#End Region
End Class
End Namespace
|
thiscouldbejd/Caerus
|
_Commands/Generated/DirectoryCommands.vb
|
Visual Basic
|
mit
| 1,911
|
Module Variables
Sub Main()
End Sub
End Module
|
Shawn1874/CodeSamplesVisualBasic
|
VisualBasicFundamentals/Variables/Variables.vb
|
Visual Basic
|
mit
| 61
|
Imports System
Imports System.Net
Imports System.Threading
Imports System.Threading.Tasks
Imports FluentFTP
Namespace Examples
Friend Module DirectoryExistsExample
Sub DirectoryExists()
Using conn = New FtpClient("127.0.0.1", "ftptest", "ftptest")
conn.Connect()
If conn.DirectoryExists("/full/or/relative/path") Then
' do something
End If
End Using
End Sub
Async Function DirectoryExistsAsync() As Task
Dim token = New CancellationToken()
Using conn = New FtpClient("127.0.0.1", "ftptest", "ftptest")
Await conn.ConnectAsync(token)
If Await conn.DirectoryExistsAsync("/full/or/relative/path") Then
' do something
End If
End Using
End Function
End Module
End Namespace
|
robinrodricks/FluentFTP
|
FluentFTP.VBExamples/DirectoryExists.vb
|
Visual Basic
|
mit
| 738
|
Imports System.Windows.Forms
Imports System.Xml
Imports System.Xml.Serialization
Public Class ItemBrowser
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Public Sub XMLTreeItem(Item As Object)
Try
'Section 0, serialize the object to XML.
Dim xf As New XmlSerializer(Item.GetType)
Dim stream As New IO.StringWriter
xf.Serialize(stream, Item)
'MsgBox(stream.ToString)
' SECTION 1. Create a DOM Document and load the XML data into it.
Dim dom As New XmlDocument()
dom.LoadXml(stream.ToString)
' SECTION 2. Initialize the treeview control.
MainTree.Nodes.Clear()
MainTree.Nodes.Add(New TreeNode(dom.DocumentElement.Name))
Dim tNode As New TreeNode()
tNode = MainTree.Nodes(0)
' SECTION 3. Populate the TreeView with the DOM nodes.
AddNode(dom.DocumentElement, tNode)
Catch xmlEx As XmlException
MessageBox.Show(xmlEx.Message)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Try
NodeCount.Text = MainTree.GetNodeCount(True).ToString + " nodes (" + MainTree.Nodes(0).GetNodeCount(False).ToString + " parents)"
Catch ex As Exception
NodeCount.Text = "Can't Count Nodes."
End Try
Me.Show()
End Sub
Private Sub AddNode(ByRef inXmlNode As XmlNode, ByRef inTreeNode As TreeNode)
Dim xNode As XmlNode
Dim tNode As TreeNode
Dim nodeList As XmlNodeList
Dim i As Integer
' Loop through the XML nodes until the leaf is reached.
' Add the nodes to the TreeView during the looping process.
If inXmlNode.HasChildNodes() Then
nodeList = inXmlNode.ChildNodes
For i = 0 To nodeList.Count - 1
xNode = inXmlNode.ChildNodes(i)
inTreeNode.Nodes.Add(New TreeNode(xNode.Name))
tNode = inTreeNode.Nodes(i)
AddNode(xNode, tNode)
Next
Else
' Here you need to pull the data from the XmlNode based on the
' type of node, whether attribute values are required, and so forth.
inTreeNode.Text = (inXmlNode.OuterXml).Trim
End If
End Sub
Private Sub CollapseAllToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CollapseAllToolStripMenuItem.Click
MainTree.CollapseAll()
End Sub
Private Sub ExpandAllToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExpandAllToolStripMenuItem.Click
End Sub
Private Sub FindButton_Click(sender As Object, e As EventArgs) Handles FindButton.Click
MainTree.CollapseAll()
resetnodes(MainTree.Nodes)
findnode(FindSearchBox.Text, MainTree.Nodes)
End Sub
Sub findnode(ByVal SearchText As String, ByVal Nodes As TreeNodeCollection)
For Each Node As TreeNode In Nodes
If Node.Text.ToUpper.Contains(SearchText.ToUpper) Then
Node.Expand()
ExpandParent(Node)
Node.BackColor = Drawing.Color.LightCoral
End If
findnode(SearchText, Node.Nodes)
Next
End Sub
Sub resetnodes(ByVal nodes As TreeNodeCollection)
For Each Node As TreeNode In nodes
Node.BackColor = System.Drawing.Color.White
resetnodes(Node.Nodes)
Next
End Sub
Sub ExpandParent(Node As TreeNode)
Node.Parent.Expand()
Try
ExpandParent(Node.Parent)
Catch ex As Exception
End Try
End Sub
Private Sub EverythingToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EverythingToolStripMenuItem.Click
MainTree.ExpandAll()
End Sub
Private Sub SelectedOnlyToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SelectedOnlyToolStripMenuItem.Click
MainTree.SelectedNode.ExpandAll()
End Sub
End Class
|
WhiteHingeLtd/Framework
|
Framework/ItemBrowser.vb
|
Visual Basic
|
mit
| 4,103
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("GhostBridge.Sample.VBNet.NUnit")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("GhostBridge.Sample.VBNet.NUnit")>
<Assembly: AssemblyCopyright("Copyright © 2013")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("d7a4772c-09f6-41b3-a2c3-58fd5d540128")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
|
vurt007/ghost-bridge
|
src/GhostBridge.Sample.VBNet.NUnit/My Project/AssemblyInfo.vb
|
Visual Basic
|
apache-2.0
| 1,213
|
' 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
Public Class WithBlockSemanticModelTests
Inherits FlowTestBase
#Region "Symbol / Type Info"
<Fact>
Sub WithAliasedStaticField()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Imports Alias1 = ClassWithField
Class ClassWithField
Public Shared field1 As String = "a"
End Class
Module WithAliasedStaticField
Sub Main()
With Alias1.field1 'BIND:"Alias1.field1"
Dim newString = .Replace("a", "b")
End With
End Sub
End Module
</file>
</compilation>)
Dim tree = compilation.SyntaxTrees.Single()
Dim model = compilation.GetSemanticModel(tree)
Dim withExpression = DirectCast(tree.GetCompilationUnitRoot().DescendantNodes().Where(Function(n) n.Kind = SyntaxKind.SimpleMemberAccessExpression).First(), MemberAccessExpressionSyntax)
Assert.Equal("Alias1", model.GetAliasInfo(DirectCast(withExpression.Expression, IdentifierNameSyntax)).ToDisplayString())
Assert.False(model.GetConstantValue(withExpression).HasValue)
Dim typeInfo = model.GetTypeInfo(withExpression)
Assert.Equal("String", typeInfo.Type.ToDisplayString())
Assert.Equal("String", typeInfo.ConvertedType.ToDisplayString())
Dim conv = model.GetConversion(withExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Dim symbolInfo = model.GetSymbolInfo(withExpression)
Assert.Equal("Public Shared field1 As String", symbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Field, symbolInfo.Symbol.Kind)
Assert.Equal(0, symbolInfo.CandidateSymbols.Length)
Assert.Equal(0, model.GetMemberGroup(withExpression).Length)
End Sub
<Fact>
Sub WithDeclaresAnonymousLocalSymbolAndTypeInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocalSymbolAndTypeInfo
Sub Main()
With New With {.A = 1, .B = "2"} 'BIND:"New With {.A = 1, .B = "2"}"
.A = .B
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticInfo = CompilationUtils.GetSemanticInfoSummary(Of AnonymousObjectCreationExpressionSyntax)(compilation, "a.vb")
Assert.Null(semanticInfo.Alias)
Assert.False(semanticInfo.ConstantValue.HasValue)
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.Type.ToDisplayString())
Assert.Equal("<anonymous type: A As Integer, B As String>", semanticInfo.ConvertedType.ToDisplayString())
Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind)
Assert.Equal("Public Sub New(A As Integer, B As String)", semanticInfo.Symbol.ToDisplayString()) ' should get constructor for anonymous type
Assert.Equal(SymbolKind.Method, semanticInfo.Symbol.Kind)
Assert.Equal(0, semanticInfo.CandidateSymbols.Length)
Assert.Equal(0, semanticInfo.MemberGroup.Length)
End Sub
<Fact(), WorkItem(544083, "DevDiv")>
Sub WithSpeculativeSymbolInfo()
Dim compilation = CompilationUtils.CreateCompilationWithMscorlib(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
Property Property2 As String
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function() .Property1 'BINDHERE
End With
End Sub
End Module
</file>
</compilation>)
Dim semanticModel = GetSemanticModel(compilation, "a.vb")
Dim position = compilation.SyntaxTrees.Single().ToString().IndexOf("'BINDHERE", StringComparison.Ordinal)
Dim expr = SyntaxFactory.ParseExpression(".property2")
Dim speculativeTypeInfo = semanticModel.GetSpeculativeTypeInfo(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal("String", speculativeTypeInfo.ConvertedType.ToDisplayString())
Dim conv = semanticModel.GetSpeculativeConversion(position, expr, SpeculativeBindingOption.BindAsExpression)
Assert.Equal(ConversionKind.Identity, conv.Kind)
Assert.Equal("String", speculativeTypeInfo.Type.ToDisplayString())
Dim speculativeSymbolInfo = semanticModel.GetSpeculativeSymbolInfo(position, SyntaxFactory.ParseExpression(".property2"), SpeculativeBindingOption.BindAsExpression)
Assert.Equal("Public Property Property2 As String", speculativeSymbolInfo.Symbol.ToDisplayString())
Assert.Equal(SymbolKind.Property, speculativeSymbolInfo.Symbol.Kind)
End Sub
#End Region
#Region "FlowAnalysis"
<Fact>
Sub UseWithVariableInNestedLambda()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Class C1
Property Property1 As Integer
End Class
Module Module1
Sub Main()
Dim x As New C1()
With x
Dim f = Function()
[|Return .Property1|]
End Function
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn)
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside)
Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowResults.ReadOutside))
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Equal("f, x", GetSymbolNamesSortedAndJoined(dataFlowResults.WrittenOutside))
Assert.Empty(controlFlowResults.EntryPoints)
Assert.False(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
Assert.Equal(1, controlFlowResults.ExitPoints.Count)
End Sub
<Fact>
Sub WithDeclaresAnonymousLocalDataFlow()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module WithDeclaresAnonymousLocal
Sub Main()
With New With {.A = 1, .B = "2"}
[|.A = .B|]
End With
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Empty(dataFlowResults.DataFlowsIn) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Empty(dataFlowResults.ReadInside) ' assume anonymous locals don't show
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside) ' assume anonymous locals don't show
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
<Fact>
Sub EmptyWith()
Dim analysis = CompileAndAnalyzeControlAndDataFlow(
<compilation>
<file name="a.vb">
Module Module1
Sub Main()
Dim x As Object()
[|With x
End With|]
End Sub
End Module
</file>
</compilation>)
Dim controlFlowResults = analysis.Item1
Dim dataFlowResults = analysis.Item2
Assert.Empty(dataFlowResults.VariablesDeclared)
Assert.Empty(dataFlowResults.AlwaysAssigned)
Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowResults.DataFlowsIn))
Assert.Empty(dataFlowResults.DataFlowsOut)
Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowResults.ReadInside))
Assert.Empty(dataFlowResults.ReadOutside)
Assert.Empty(dataFlowResults.WrittenInside)
Assert.Empty(dataFlowResults.WrittenOutside)
Assert.Empty(controlFlowResults.ExitPoints)
Assert.Empty(controlFlowResults.EntryPoints)
Assert.True(controlFlowResults.EndPointIsReachable)
Assert.True(controlFlowResults.StartPointIsReachable)
End Sub
#End Region
End Class
End Namespace
|
ManishJayaswal/roslyn
|
src/Compilers/VisualBasic/Test/Semantic/Semantics/WithBlockSemanticModelTests.vb
|
Visual Basic
|
apache-2.0
| 9,031
|
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyDescription("EIDSS Notification Service")>
<Assembly: CLSCompliant(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("9B195A2B-ECEE-4C24-8ACA-689DF56D9C7D")>
|
EIDSS/EIDSS-Legacy
|
EIDSS v6.1/vb/EIDSS/EIDSS_NOTIFICATION_SVC/AssemblyInfo.vb
|
Visual Basic
|
bsd-2-clause
| 570
|
' 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
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 Shared Function GetNormalTypeConstructors(
document As Document,
objectCreationExpression As ObjectCreationExpressionSyntax,
semanticModel As SemanticModel,
structuralTypeDisplayService As IStructuralTypeDisplayService,
normalType As INamedTypeSymbol,
within As ISymbol,
options As SignatureHelpOptions, cancellationToken As CancellationToken) As (items As IList(Of SignatureHelpItem), selectedItem As Integer?)
Dim accessibleConstructors = normalType.InstanceConstructors.
WhereAsArray(Function(c) c.IsAccessibleWithin(within)).
FilterToVisibleAndBrowsableSymbolsAndNotUnsafeSymbols(options.HideAdvancedMembers, semanticModel.Compilation).
Sort(semanticModel, objectCreationExpression.SpanStart)
If Not accessibleConstructors.Any() Then
Return Nothing
End If
Dim documentationCommentFormattingService = document.GetLanguageService(Of IDocumentationCommentFormattingService)()
Dim items = accessibleConstructors.Select(
Function(c) ConvertNormalTypeConstructor(c, objectCreationExpression, semanticModel, structuralTypeDisplayService, documentationCommentFormattingService)).ToList()
Dim currentConstructor = semanticModel.GetSymbolInfo(objectCreationExpression, cancellationToken)
Dim selectedItem = TryGetSelectedIndex(accessibleConstructors, currentConstructor.Symbol)
Return (items, selectedItem)
End Function
Private Shared Function ConvertNormalTypeConstructor(constructor As IMethodSymbol, objectCreationExpression As ObjectCreationExpressionSyntax, semanticModel As SemanticModel,
structuralTypeDisplayService As IStructuralTypeDisplayService,
documentationCommentFormattingService As IDocumentationCommentFormattingService) As SignatureHelpItem
Dim position = objectCreationExpression.SpanStart
Dim item = CreateItem(
constructor, semanticModel, position,
structuralTypeDisplayService,
constructor.IsParams(),
constructor.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService),
GetNormalTypePreambleParts(constructor, semanticModel, position), GetSeparatorParts(),
GetNormalTypePostambleParts(),
constructor.Parameters.Select(Function(p) Convert(p, semanticModel, position, documentationCommentFormattingService)).ToList())
Return item
End Function
Private Shared Function GetNormalTypePreambleParts(method As IMethodSymbol, semanticModel As SemanticModel, position As Integer) As IList(Of SymbolDisplayPart)
Dim result = New List(Of SymbolDisplayPart)()
result.AddRange(method.ContainingType.ToMinimalDisplayParts(semanticModel, position))
result.Add(Punctuation(SyntaxKind.OpenParenToken))
Return result
End Function
Private Shared Function GetNormalTypePostambleParts() As IList(Of SymbolDisplayPart)
Return {Punctuation(SyntaxKind.CloseParenToken)}
End Function
End Class
End Namespace
|
CyrusNajmabadi/roslyn
|
src/Features/VisualBasic/Portable/SignatureHelp/ObjectCreationExpressionSignatureHelpProvider.NormalType.vb
|
Visual Basic
|
mit
| 4,095
|
' 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.Concurrent
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class GroupTypeInferenceLambda
Public Function InferLambdaReturnType(delegateParams As ImmutableArray(Of ParameterSymbol)) As TypeSymbol
' Return type of the lambda must be an Anonymous Type corresponding to the following initializer:
' New With {key .$VB$ItAnonymous = <delegates's second parameter> }
If delegateParams.Length <> 2 Then
Return Nothing
Else
Return Compilation.AnonymousTypeManager.ConstructAnonymousTypeSymbol(
New AnonymousTypeDescriptor(
ImmutableArray.Create(New AnonymousTypeField(GeneratedNameConstants.ItAnonymous,
delegateParams(1).Type,
Syntax.QueryClauseKeywordOrRangeVariableIdentifier.GetLocation(),
True)),
Syntax.QueryClauseKeywordOrRangeVariableIdentifier.GetLocation(),
True))
End If
End Function
End Class
End Namespace
|
sharwell/roslyn
|
src/Compilers/VisualBasic/Portable/BoundTree/GroupTypeInferenceLambda.vb
|
Visual Basic
|
mit
| 1,753
|
'---------------------------------------------------------------------
' <copyright file="StateChange.vb" company="Microsoft">
' Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
' </copyright>
'---------------------------------------------------------------------
Imports System
Imports Microsoft.OData.Client
Imports System.IO
Imports System.Net
Imports System.Linq
Imports System.Xml.Linq
Imports System.Text
Imports System.Collections.Generic
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports AstoriaUnitTests.Data
Imports AstoriaUnitTests.Stubs
Imports Microsoft.Test.ModuleCore
Partial Public Class ClientModule
<TestClass()> Public Class StateChange
Private Shared web As TestWebRequest = Nothing
Private sentRequests As New List(Of HttpWebRequest)()
Private ctx As NorthwindSimpleModel.NorthwindContext = Nothing
#Region "Initialize DataService and create new context for each text"
<ClassInitialize()> Public Shared Sub PerClassSetup(ByVal context As TestContext)
web = TestWebRequest.CreateForInProcessWcf
web.DataServiceType = ServiceModelData.Northwind.ServiceModelType
web.StartService()
End Sub
<ClassCleanup()> Public Shared Sub PerClassCleanup()
If Not web Is Nothing Then
web.Dispose()
End If
End Sub
<TestInitialize()> Public Sub PerTestSetup()
Me.ctx = New NorthwindSimpleModel.NorthwindContext(web.ServiceRoot)
Me.ctx.EnableAtom = True
Me.ctx.Format.UseAtom()
AddHandler Me.ctx.SendingRequest2, AddressOf SendingRequestListenHttpMethod
End Sub
<TestCleanup()> Public Sub PerTestCleanup()
Me.ctx = Nothing
Me.sentRequests.Clear()
End Sub
Private Sub SendingRequestListenHttpMethod(ByVal sender As Object, ByVal args As SendingRequest2EventArgs)
Dim httpRequestMessage = TryCast(args.RequestMessage, HttpWebRequestMessage)
If httpRequestMessage IsNot Nothing Then
Dim httpRequest = httpRequestMessage.HttpWebRequest
sentRequests.Add(httpRequest)
End If
End Sub
#End Region
<TestCategory("Partition2")> <TestMethod()> Public Sub EntityStates()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZZ", "Microsoft")
Assert.IsFalse(ctx.Detach(customer), "detach false")
Assert.AreEqual(SaveChangesOptions.None, ctx.SaveChangesDefaultOptions, "SaveChangesDefaultOptions")
Try
ctx.UpdateObject(customer)
Assert.Fail("expected ArgumentException")
Catch ex As ArgumentException
End Try
Try
ctx.DeleteObject(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
ValidateEntityStates()
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.None, 0, 0, "Nothing")
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods()
' AddObject
ctx.AddToCustomers(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
Assert.IsTrue(ctx.Detach(customer), "detach true")
ValidateEntityStates()
ValidateLinkStates()
ctx.AddToCustomers(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
Try
ctx.AddToCustomers(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AddObject("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("Customers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
ctx.UpdateObject(customer) ' expect no change
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
ctx.DeleteObject(customer)
ValidateEntityStates()
ValidateLinkStates()
ctx.AddToCustomers(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
' POST
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "POST")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST")
Try
ctx.AddToCustomers(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AddObject("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("Customers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Util.SaveChanges(ctx, SaveChangesOptions.None, 0, 0, "Unchanged")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods()
' PATCH
ctx.UpdateObject(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Modified)
ValidateLinkStates()
Try
ctx.AddToCustomers(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AddObject("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("Customers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "PATCH")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("PATCH")
' DeleteObject
ctx.DeleteObject(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
ctx.UpdateObject(customer) ' expect no change
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
ctx.DeleteObject(customer) ' expect no change
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
Try
ctx.AddToCustomers(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AddObject("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("Customers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
' DELETE
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "DELETE")
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods("DELETE")
' AttachTo
ctx.AttachTo("Customers", customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
Try
ctx.AddToCustomers(customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AddObject("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("Customers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
Try
ctx.AttachTo("NotCustomers", customer)
Assert.Fail("expected InvalidOperationException")
Catch ex As InvalidOperationException
End Try
' PUT fail
ctx.UpdateObject(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Modified)
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.ReplaceOnUpdate, 0, 1, "PUT fail")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Modified)
ValidateLinkStates()
ValidateRequestMethods("PUT")
' POST again
ctx.Detach(customer)
ctx.AddToCustomers(customer)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "POST again")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST")
' PUT
ctx.UpdateObject(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Modified)
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.ReplaceOnUpdate, 1, 0, "PUT")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("PUT")
' Cleanup DELETE
ctx.DeleteObject(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "Cleanup")
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods("DELETE")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub CollectionLinkStates_AddDelete()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZY", "Microsoft")
Dim order = NorthwindSimpleModel.Orders.CreateOrders(9999)
' Add everything
ctx.AddToCustomers(customer)
ctx.AddToOrders(order)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Customer, Add Order")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST", "POST")
ctx.AddLink(customer, "Orders", order)
ctx.DeleteObject(order)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Customer -> Order, delete order")
ValidateEntityObjects(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST", "DELETE")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub CollectionLinkStates_AddSetDelete()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZX", "Microsoft")
Dim order = NorthwindSimpleModel.Orders.CreateOrders(9999)
' Add everything
ctx.AddToCustomers(customer)
ctx.AddToOrders(order)
ctx.SetLink(order, "Customers", customer)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Modified)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Customer, Add Order")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("POST", "POST")
ctx.AddLink(customer, "Orders", order)
ctx.DeleteObject(order)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Customer -> Order, delete order")
ValidateEntityObjects(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST", "DELETE")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub CollectionLinkStates_AddSetDelete_Batch()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZU", "Microsoft")
Dim order = NorthwindSimpleModel.Orders.CreateOrders(9999)
' Add everything
ctx.AddToCustomers(customer)
ctx.AddToOrders(order)
ctx.SetLink(order, "Customers", customer)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Modified)
Util.SaveChanges(ctx, SaveChangesOptions.BatchWithSingleChangeset, 3, 0, "Add Customer, Add Order")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("POST")
ctx.DeleteObject(order)
Util.SaveChanges(ctx, SaveChangesOptions.BatchWithSingleChangeset, 1, 0, "Add Customer -> Order, delete order")
ValidateEntityObjects(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("POST")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub CollectionLinkStates_AddAdd_Delete()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZW", "Microsoft")
Dim order = NorthwindSimpleModel.Orders.CreateOrders(9999)
' Add everything
ctx.AddToCustomers(customer)
ctx.AddToOrders(order)
ctx.AddLink(customer, "Orders", order)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Added)
ctx.Detach(order)
ValidateEntityObjects(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates()
ctx.AddToOrders(order)
ctx.AddLink(customer, "Orders", order)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Added)
Util.SaveChanges(ctx, SaveChangesOptions.None, 3, 0, "Add Customer, Add Order w/ Collection Link")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("POST", "POST", "POST") ' it's a collection, not a reference link
ctx.DeleteLink(customer, "Orders", order)
ctx.DeleteObject(customer)
ValidateEntityObjects(order, customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Deleted)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Delete Customer->Order, Delete Customer")
ValidateEntityObjects(order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("DELETE", "DELETE")
ctx.DeleteObject(order)
ValidateEntityObjects(order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates()
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "delete all batch")
ValidateEntityObjects()
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods("DELETE")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub CollectionLinkStates_Add_Add_Delete()
Dim customer = NorthwindSimpleModel.Customers.CreateCustomers("ZZZV", "Microsoft")
Dim order = NorthwindSimpleModel.Orders.CreateOrders(9998)
' Add everything
ctx.AddToCustomers(customer)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "Add Customer")
ValidateRequestMethods("POST")
ctx.AddToOrders(order)
ctx.AddLink(customer, "Orders", order)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Added)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Add Order w/ Link")
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("POST", "POST")
ctx.DeleteLink(customer, "Orders", order)
ctx.DeleteObject(order)
ValidateEntityObjects(customer, order)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Deleted)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Delete Delete order")
ValidateEntityObjects(customer)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates()
ValidateRequestMethods("DELETE", "DELETE")
ctx.DeleteObject(customer)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "cleanup Delete")
ValidateEntityObjects()
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods("DELETE")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub ReferenceLinkStates()
Dim child = NorthwindSimpleModel.Territories.CreateTerritories("888886", "Astoria")
Dim parent = NorthwindSimpleModel.Region.CreateRegion(999996, "Software")
child.Region = parent
ctx.AddToRegion(parent)
ctx.AddToTerritories(child)
ctx.SetLink(child, "Region", parent)
ValidateEntityObjects(parent, child)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Added, Microsoft.OData.Client.EntityStates.Added)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Modified)
Util.SaveChanges(ctx, SaveChangesOptions.None, 2, 0, "Add Territories, Add Region w/ Reference Link")
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Unchanged)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("POST", "POST") ' it's a reference link
ctx.DeleteObject(parent)
ValidateEntityObjects(child, parent)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
Util.SaveChanges(ctx, SaveChangesOptions.None, 0, 1, "Delete Region w/ Reference Link")
ValidateEntityObjects(child, parent)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Unchanged, Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
ValidateRequestMethods("DELETE")
ctx.DeleteObject(child)
ValidateEntityObjects(parent, child)
ValidateEntityStates(Microsoft.OData.Client.EntityStates.Deleted, Microsoft.OData.Client.EntityStates.Deleted)
ValidateLinkStates(Microsoft.OData.Client.EntityStates.Unchanged)
Util.SaveChanges(ctx, SaveChangesOptions.BatchWithSingleChangeset, 2, 0, "Cleanup batch")
ValidateEntityStates()
ValidateLinkStates()
ValidateRequestMethods("POST")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub DeleteEntityAsync()
Dim uriBefore As Uri = Nothing
Dim uriAfter As Uri = Nothing
Dim entityTemp As NorthwindSimpleModel.Customers = Nothing
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZT", "Microsoft")
ctx.AddToCustomers(customer1)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "Create first customer")
ctx.SaveChanges()
ctx.DeleteObject(customer1)
Assert.IsTrue(ctx.TryGetUri(customer1, uriBefore))
Dim asyncResult = ctx.BeginSaveChanges(SaveChangesOptions.None, Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Assert.IsTrue(ctx.TryGetUri(customer1, uriAfter))
Assert.IsTrue(ctx.TryGetEntity(uriBefore, entityTemp))
Assert.AreSame(customer1, entityTemp, "should be same customer1")
Assert.AreEqual(uriBefore, uriAfter, "uri should be the same")
ctx.EndSaveChanges(asyncResult)
Assert.IsFalse(ctx.TryGetUri(customer1, uriAfter))
Assert.IsFalse(ctx.TryGetEntity(uriBefore, customer1))
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub DeleteEntityFail()
Dim uriBefore As Uri = Nothing
Dim uriAfter As Uri = Nothing
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZS", "Microsoft")
ctx.AttachTo("Customers", customer1)
Assert.IsTrue(ctx.TryGetUri(customer1, uriBefore))
ctx.DeleteObject(customer1)
Dim asyncResult = ctx.BeginSaveChanges(Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Assert.IsTrue(ctx.TryGetUri(customer1, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link1 changed")
Try
ctx.EndSaveChanges(asyncResult)
Assert.Fail("expected exception")
Catch ex As DataServiceRequestException
End Try
uriAfter = Nothing
Assert.IsTrue(ctx.TryGetUri(customer1, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link2 changed")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub DeleteFailAddSucceed()
Dim uriBefore As Uri = Nothing
Dim uriAfter As Uri = Nothing
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZR", "Microsoft")
ctx.AttachTo("Customers", customer1)
Assert.IsTrue(ctx.TryGetUri(customer1, uriBefore))
ctx.DeleteObject(customer1)
Dim customer2 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZR", "Microsoft")
ctx.AddToCustomers(customer2)
Dim asyncResult = ctx.BeginSaveChanges(SaveChangesOptions.ContinueOnError, Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Assert.IsFalse(ctx.TryGetUri(customer1, uriAfter))
Assert.IsTrue(ctx.TryGetUri(customer2, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link1 changed")
Try
ctx.EndSaveChanges(asyncResult)
Assert.Fail("expected exception")
Catch ex As DataServiceRequestException
End Try
uriAfter = Nothing
Assert.IsFalse(ctx.TryGetUri(customer1, uriAfter))
Assert.IsTrue(ctx.TryGetUri(customer2, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link2 changed")
ctx.Detach(customer2)
ctx.SaveChanges()
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub AddSucceedDeleteSucceed()
Dim uriBefore As Uri = Nothing
Dim uriAfter As Uri = Nothing
Dim customer2 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZQ", "Microsoft")
ctx.AddToCustomers(customer2)
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZQ", "Microsoft")
ctx.AttachTo("Customers", customer1)
Assert.IsTrue(ctx.TryGetUri(customer1, uriBefore))
ctx.DeleteObject(customer1)
Dim asyncResult = ctx.BeginSaveChanges(SaveChangesOptions.ContinueOnError, Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Assert.IsFalse(ctx.TryGetUri(customer1, uriAfter))
Assert.IsTrue(ctx.TryGetUri(customer2, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link1 changed")
'Try
ctx.EndSaveChanges(asyncResult) ' weird scenario because database is now empty, but client has 1 unchanged
'Assert.Fail("expected exception")
'Catch ex As DataServiceRequestException
'End Try
uriAfter = Nothing
Assert.IsFalse(ctx.TryGetUri(customer1, uriAfter))
Assert.IsTrue(ctx.TryGetUri(customer2, uriAfter))
Assert.AreEqual(uriBefore, uriAfter, "link2 changed")
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub SameKeyDeleteAdd()
' batching not in this list because the server will error
For Each saveChangeOption In New SaveChangesOptions() {SaveChangesOptions.None, SaveChangesOptions.ReplaceOnUpdate, SaveChangesOptions.ContinueOnError}
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZP", "Microsoft")
ctx.AddToCustomers(customer1)
Util.SaveChanges(ctx, saveChangeOption, 1, 0, "Create first customer")
ctx.SaveChanges()
ctx.DeleteObject(customer1)
Dim customer2 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZP", "Microsoft")
ctx.AddToCustomers(customer2)
Util.SaveChanges(ctx, saveChangeOption, 2, 0, "Delete customer, add new customer that has same Uri " & saveChangeOption.ToString())
ctx.DeleteObject(customer2)
Util.SaveChanges(ctx, saveChangeOption, 1, 0, "cleanup")
Next
End Sub
<TestCategory("Partition2")> <TestMethod()> Public Sub SameKeyDeleteAdd_Verify()
Dim uriBefore As Uri = Nothing
Dim uriAfter As Uri = Nothing
Dim uriTemp As Uri = Nothing
Dim entityTemp As NorthwindSimpleModel.Customers = Nothing
Dim customer1 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZO", "Microsoft")
ctx.AddToCustomers(customer1)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "Create first customer")
ctx.SaveChanges()
Assert.IsTrue(ctx.TryGetUri(customer1, uriBefore))
ctx.DeleteObject(customer1)
Dim customer2 = NorthwindSimpleModel.Customers.CreateCustomers("ZZZO", "Microsoft")
ctx.AddToCustomers(customer2)
Dim asyncResult = ctx.BeginSaveChanges(SaveChangesOptions.None, Nothing, Nothing)
asyncResult.AsyncWaitHandle.WaitOne()
Assert.IsFalse(ctx.TryGetUri(customer1, uriTemp))
Assert.IsTrue(ctx.TryGetUri(customer2, uriAfter))
Assert.IsTrue(ctx.TryGetEntity(uriBefore, entityTemp))
Assert.AreSame(customer2, entityTemp, "should be same customer2")
Assert.AreEqual(uriBefore, uriAfter, "uri should be the same")
ctx.EndSaveChanges(asyncResult)
Assert.IsTrue(ctx.TryGetUri(customer2, uriTemp))
Assert.AreEqual(uriAfter, uriTemp, "uri should be the same")
ctx.DeleteObject(customer2)
Util.SaveChanges(ctx, SaveChangesOptions.None, 1, 0, "cleanup")
End Sub
Private Sub ValidateEntityObjects(ByVal ParamArray objects As Object())
Dim entities = ctx.Entities
Assert.AreEqual(objects.Length, entities.Count, "Entity count")
For i As Int32 = 0 To objects.Length - 1
Assert.IsTrue(Object.ReferenceEquals(objects(i), entities.Item(i).Entity), "Entities[{0}].Entity differs", i)
Next
End Sub
Private Sub ValidateEntityStates(ByVal ParamArray states As Microsoft.OData.Client.EntityStates())
Dim entities = ctx.Entities
Dim x = String.Concat((From m In entities Select m.State).ToArray())
Assert.AreEqual(states.Length, entities.Count, "Entity count {0}", x)
For i As Int32 = 0 To states.Length - 1
Assert.AreEqual(states(i), entities.Item(i).State, "Entities[{0}].State", i)
Next
End Sub
Private Sub ValidateLinkStates(ByVal ParamArray states As Microsoft.OData.Client.EntityStates())
Dim entities = ctx.Links
Dim x = String.Concat((From m In entities Select m.State).Cast(Of Object)().ToArray())
Assert.AreEqual(states.Length, entities.Count, "Link count {0}", x)
For i As Int32 = 0 To states.Length - 1
Assert.AreEqual(states(i), entities.Item(i).State, "Entities[{0}].State", i)
Next
End Sub
Private Sub ValidateRequestMethods(ByVal ParamArray methods As String())
Dim x = String.Concat((From m In Me.sentRequests Select m.Method).ToArray())
Assert.AreEqual(methods.Length, Me.sentRequests.Count, "SendingRequest count {0}", x)
For i As Int32 = 0 To methods.Length - 1
Assert.AreEqual(methods(i), Me.sentRequests.Item(i).Method, "SendingRequest[{0}].Method", i)
Next
Me.sentRequests.Clear()
End Sub
End Class
End Class
|
hotchandanisagar/odata.net
|
test/FunctionalTests/Tests/DataServices/UnitTests/ClientUnitTests/StateChange.vb
|
Visual Basic
|
mit
| 33,364
|
Namespace CRM
<SupportedActionsSDK(True, False, False, False)>
<DataServiceKey("QuotationID")>
Public Class [AcceptQuotation]
'''<summary>0 = No action (Default), 1 = create sales order, 2 = create sales invoice, 3 = create project.</summary>
Public Property [Action] As Int32
'''<summary>Create a project work breakdown structure. Only needed when ProjectBudgetType = 2.</summary>
Public Property [CreateProjectWBS] As Boolean?
'''<summary>Division code</summary>
Public Property [Division] As Int32
'''<summary>Contains the error message if an error occurred during the acception of the quotation.</summary>
Public Property [ErrorMessage] As String
'''<summary>The journal in which the sales invoice will be booked. Mandatory for Action = 2.</summary>
Public Property [InvoiceJournal] As Int32
'''<summary>The budget type of the project that will be created. Default = 0.</summary>
Public Property [ProjectBudgetType] As Int32?
'''<summary>The code of the project that will be created. Mandatory for Action = 3.</summary>
Public Property [ProjectCode] As String
'''<summary>The description of the project that will be created. Mandatory for Action = 3.</summary>
Public Property [ProjectDescription] As String
'''<summary>The invoicing date of the project. Mandatory for ProjectInvoicingAction = 2.</summary>
Public Property [ProjectInvoiceDate] As DateTime?
'''<summary>The project invoicing action. 0 = None (Default), 1 = Create invoice terms, 2 = As quoted.</summary>
Public Property [ProjectInvoicingAction] As Int32?
'''<summary>The prepaid type. Mandatory for ProjectType = 5. 1 = Retainer, 2 = Hour type bundle.</summary>
Public Property [ProjectPrepaindTypes] As Int32?
'''<summary>PriceAgreement.</summary>
Public Property [ProjectPriceAgreement] As Double?
'''<summary>Contains information if the project was successfully created.</summary>
Public Property [ProjectSuccess] As String
'''<summary>The type of the project that will be created. 2 = Fixed price (Default), 3 = Time and Material, 4 = Non billable, 5 = Prepaid.</summary>
Public Property [ProjectType] As Int32?
'''<summary>Identifier of the quotation.</summary>
Public Property [QuotationID] As Guid
'''<summary>Reason why the quotation was accepted.</summary>
Public Property [ReasonCode] As Guid?
'''<summary>Contains information if the sales invoice was successfully created.</summary>
Public Property [SalesInvoiceSuccess] As String
'''<summary>Contains information if the sales order was successfully created.</summary>
Public Property [SalesOrderSuccess] As String
'''<summary>Contains information if the quotation was successfully accepted.</summary>
Public Property [SuccessMessage] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [Account]
'''<summary>Reference to the accountant of the customer. Conditions: The referred accountant must have value > 0 in the field IsAccountant</summary>
Public Property [Accountant] As Guid?
'''<summary>ID of the account manager</summary>
Public Property [AccountManager] As Guid?
'''<summary>Name of the account manager</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountManagerFullName] As String
'''<summary>Number of the account manager </summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountManagerHID] As Int32?
'''<summary>Reference to Activity sector of the account</summary>
Public Property [ActivitySector] As Guid?
'''<summary>Reference to Activity sub-sector of the account</summary>
Public Property [ActivitySubSector] As Guid?
'''<summary>Visit address first line</summary>
Public Property [AddressLine1] As String
'''<summary>Visit address second line</summary>
Public Property [AddressLine2] As String
'''<summary>Visit address third line</summary>
Public Property [AddressLine3] As String
'''<summary>Collection of Bank accounts</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [BankAccounts] As IEnumerable(Of Models.CRM.BankAccount)
'''<summary>Indicates if the account is blocked</summary>
Public Property [Blocked] As Boolean?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [BRIN] As Guid?
'''<summary>Reference to the business type of the account</summary>
Public Property [BusinessType] As Guid?
'''<summary>Indicates the default for the possibility to drop ship when an item is linked to a supplier</summary>
Public Property [CanDropShip] As Boolean?
'''<summary>Chamber of commerce number</summary>
Public Property [ChamberOfCommerce] As String
'''<summary>Visit address City</summary>
Public Property [City] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Classification] As String
'''<summary>Account classification 1</summary>
Public Property [Classification1] As Guid?
'''<summary>Account classification 2</summary>
Public Property [Classification2] As Guid?
'''<summary>Account classification 3</summary>
Public Property [Classification3] As Guid?
'''<summary>Account classification 4</summary>
Public Property [Classification4] As Guid?
'''<summary>Account classification 5</summary>
Public Property [Classification5] As Guid?
'''<summary>Account classification 6</summary>
Public Property [Classification6] As Guid?
'''<summary>Account classification 7</summary>
Public Property [Classification7] As Guid?
'''<summary>Account classification 8</summary>
Public Property [Classification8] As Guid?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ClassificationDescription] As String
'''<summary>Unique key, fixed length numeric string with leading spaces, length 18. IMPORTANT: When you use OData $filter on this field you have to make sure the filter parameter contains the leading spaces</summary>
Public Property [Code] As String
'''<summary>Code under which your own company is known at the account</summary>
Public Property [CodeAtSupplier] As String
'''<summary>Reference to Company size of the account</summary>
Public Property [CompanySize] As Guid?
'''<summary>Consolidation scenario (Time & Billing). Values: 0 = No consolidation, 1 = Item, 2 = Item + Project, 3 = Item + Employee, 4 = Item + Employee + Project, 5 = Project + WBS + Item, 6 = Project + WBS + Item + Employee. Item means in this case including Unit and Price, these also have to be the same to consolidate</summary>
Public Property [ConsolidationScenario] As Byte?
'''<summary>Date of the latest control of account data with external web service</summary>
Public Property [ControlledDate] As DateTime?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Costcenter] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CostcenterDescription] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CostPaid] As Byte
'''<summary>Country code</summary>
Public Property [Country] As String
'''<summary>Country name</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CountryName] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Maximum amount of credit for Purchase. If no value has been defined, there is no credit limit</summary>
Public Property [CreditLinePurchase] As Double?
'''<summary>Maximum amount of credit for sales. If no value has been defined, there is no credit limit</summary>
Public Property [CreditLineSales] As Double?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Currency] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CustomerSince] As DateTime?
'''<summary>DATEV creditor code for Germany legislation</summary>
Public Property [DatevCreditorCode] As String
'''<summary>DATEV debtor code for Germany legislation</summary>
Public Property [DatevDebtorCode] As String
'''<summary>Default discount percentage for purchase. This is stored as a fraction. ie 5.5% is stored as .055</summary>
Public Property [DiscountPurchase] As Double?
'''<summary>Default discount percentage for sales. This is stored as a fraction. ie 5.5% is stored as .055</summary>
Public Property [DiscountSales] As Double?
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Document] As Guid?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [DunsNumber] As String
'''<summary>E-Mail address of the account</summary>
Public Property [Email] As String
'''<summary>Determines in combination with the start date if the account is active. If the current date is > end date the account is inactive</summary>
Public Property [EndDate] As DateTime?
'''<summary>RegistrationDate</summary>
Public Property [EstablishedDate] As DateTime?
'''<summary>Fax number</summary>
Public Property [Fax] As String
'''<summary>Default (corporate) GL offset account for purchase (cost)</summary>
Public Property [GLAccountPurchase] As Guid?
'''<summary>Default (corporate) GL offset account for sales (revenue)</summary>
Public Property [GLAccountSales] As Guid?
'''<summary>Default GL account for Accounts Payable</summary>
Public Property [GLAP] As Guid?
'''<summary>Default GL account for Accounts Receivable</summary>
Public Property [GLAR] As Guid?
'''<summary>Indicates whether a customer has withholding tax on sales</summary>
Public Property [HasWithholdingTaxSales] As Boolean?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Suppressed warning message when there is duplication on the DATEV code</summary>
Public Property [IgnoreDatevWarningMessage] As Boolean
'''<summary>Intrastat Area</summary>
Public Property [IntraStatArea] As String
'''<summary>Intrastat delivery method</summary>
Public Property [IntraStatDeliveryTerm] As String
'''<summary>System for Intrastat</summary>
Public Property [IntraStatSystem] As String
'''<summary>Transaction type A for Intrastat</summary>
Public Property [IntraStatTransactionA] As String
'''<summary>Transaction type B for Intrastat</summary>
Public Property [IntraStatTransactionB] As String
'''<summary>Transport method for Intrastat</summary>
Public Property [IntraStatTransportMethod] As String
'''<summary>ID of account to be invoiced instead of this account</summary>
Public Property [InvoiceAccount] As Guid?
'''<summary>Code of InvoiceAccount</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvoiceAccountCode] As String
'''<summary>Name of InvoiceAccount</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvoiceAccountName] As String
'''<summary>Indicates which attachment types should be sent when a sales invoice is printed. Only values in related table with Invoice=1 are allowed</summary>
Public Property [InvoiceAttachmentType] As Int32?
'''<summary>Method of sending for sales invoices. Values: 1: Paper, 2: EMail, 4: Mailbox (electronic exchange)</summary>
Public Property [InvoicingMethod] As Int32?
'''<summary>Indicates whether the account is an accountant. Values: 0 = No accountant, 1 = True, but accountant doesn't want his name to be published in the list of accountants, 2 = True, and accountant is published in the list of accountants</summary>
Public Property [IsAccountant] As Byte
'''<summary>Indicates whether the accounti is an agency</summary>
Public Property [IsAgency] As Byte
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsBank] As Boolean?
'''<summary>Indicates whether the account is a competitor</summary>
Public Property [IsCompetitor] As Byte
'''<summary>Indicates whether a customer is eligible for extra duty</summary>
Public Property [IsExtraDuty] As Boolean?
'''<summary>Indicates if the account is excluded from mailing marketing information</summary>
Public Property [IsMailing] As Byte
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsMember] As Boolean?
'''<summary>Indicates whether the account is a pilot account</summary>
Public Property [IsPilot] As Boolean?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsPurchase] As Boolean?
'''<summary>Indicates whether the account is a reseller</summary>
Public Property [IsReseller] As Boolean?
'''<summary>Indicates whether the account is allowed for sales</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsSales] As Boolean?
'''<summary>Indicates whether the account is a supplier</summary>
Public Property [IsSupplier] As Boolean?
'''<summary>Language code</summary>
Public Property [Language] As String
'''<summary>Language description</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [LanguageDescription] As String
'''<summary>Latitude (used by Google maps)</summary>
Public Property [Latitude] As Double?
'''<summary>Reference to Lead source of an account</summary>
Public Property [LeadSource] As Guid?
'''<summary>Bytes of the logo image</summary>
Public Property [Logo] As Byte()
'''<summary>The file name (without path, but with extension) of the image</summary>
Public Property [LogoFileName] As String
'''<summary>Thumbnail url of the logo</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [LogoThumbnailUrl] As String
'''<summary>Url to retrieve the logo</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [LogoUrl] As String
'''<summary>Longitude (used by Google maps)</summary>
Public Property [Longitude] As Double?
'''<summary>Reference to main contact person</summary>
Public Property [MainContact] As Guid?
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Account name</summary>
Public Property [Name] As String
'''<summary>ID of the parent account</summary>
Public Property [Parent] As Guid?
'''<summary>Indicates the loan repayment plan for UK legislation</summary>
Public Property [PayAsYouEarn] As String
'''<summary>Code of default payment condition for purchase</summary>
Public Property [PaymentConditionPurchase] As String
'''<summary>Description of PaymentConditionPurchase</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PaymentConditionPurchaseDescription] As String
'''<summary>Code of default payment condition for sales</summary>
Public Property [PaymentConditionSales] As String
'''<summary>Description of PaymentConditionSales</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PaymentConditionSalesDescription] As String
'''<summary>Phone number</summary>
Public Property [Phone] As String
'''<summary>Phone number extention</summary>
Public Property [PhoneExtension] As String
'''<summary>Visit address postcode</summary>
Public Property [Postcode] As String
'''<summary>Default sales price list for account</summary>
Public Property [PriceList] As Guid?
'''<summary>Currency of purchase</summary>
Public Property [PurchaseCurrency] As String
'''<summary>Description of PurchaseCurrency</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PurchaseCurrencyDescription] As String
'''<summary>Indicates number of days required to receive a purchase. Acts as a default</summary>
Public Property [PurchaseLeadDays] As Int32?
'''<summary>Default VAT code used for purchase entries</summary>
Public Property [PurchaseVATCode] As String
'''<summary>Description of PurchaseVATCode</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PurchaseVATCodeDescription] As String
'''<summary>Define the relation that should be taken in the official document of the rewarding fiscal fiches Belcotax</summary>
Public Property [RecepientOfCommissions] As Boolean?
'''<summary>Remarks</summary>
Public Property [Remarks] As String
'''<summary>ID of the reseller account. Conditions: the target account must have the property IsReseller turned on</summary>
Public Property [Reseller] As Guid?
'''<summary>Code of Reseller</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ResellerCode] As String
'''<summary>Name of Reseller</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ResellerName] As String
'''<summary>Fiscal number for NL legislation</summary>
Public Property [RSIN] As String
'''<summary>Currency of Sales used for Time & Billing</summary>
Public Property [SalesCurrency] As String
'''<summary>Description of SalesCurrency</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesCurrencyDescription] As String
'''<summary>Obsolete</summary>
Public Property [SalesTaxSchedule] As Guid?
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesTaxScheduleCode] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesTaxScheduleDescription] As String
'''<summary>Default VAT code for a sales entry</summary>
Public Property [SalesVATCode] As String
'''<summary>Description of SalesVATCode</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesVATCodeDescription] As String
'''<summary>Search code</summary>
Public Property [SearchCode] As String
'''<summary>Security level (0 - 100)</summary>
Public Property [SecurityLevel] As Int32?
'''<summary>Separate invoice per project (Time & Billing)</summary>
Public Property [SeparateInvPerProject] As Byte
'''<summary>Indicates how invoices are generated from subscriptions. 0 = subscriptions belonging to the same customer are combined in a single invoice. 1 = each subscription results in one invoice. In both cases, each individual subscription line results in one invoice line</summary>
Public Property [SeparateInvPerSubscription] As Byte
'''<summary>Indicates the number of days it takes to send goods to the customer. Acts as a default</summary>
Public Property [ShippingLeadDays] As Int32?
'''<summary>Default shipping method</summary>
Public Property [ShippingMethod] As Guid?
'''<summary>Indicates in combination with the end date if the account is active</summary>
Public Property [StartDate] As DateTime?
'''<summary>State/Province/County code When changing the Country and the State is filled, the State must be assigned with a valid value from the selected country or set to empty</summary>
Public Property [State] As String
'''<summary>Name of State</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [StateName] As String
'''<summary>If the status field is filled this means the account is a customer. The value indicates the customer status. Possible values: A=None, S=Suspect, P=Prospect, C=Customer</summary>
Public Property [Status] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [StatusSince] As DateTime?
'''<summary>Trade name can be registered and shown with the client (for all legislations)</summary>
Public Property [TradeName] As String
'''<summary>Account type: Values: A = Relation, D = Division</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Type] As String
'''<summary>Unique taxpayer reference for UK legislation</summary>
Public Property [UniqueTaxpayerReference] As String
'''<summary>Indicates the VAT status of an account to be able to identify the relation that should be selected in the VAT debtor listing in Belgium</summary>
Public Property [VATLiability] As String
'''<summary>The number under which the account is known at the Value Added Tax collection agency</summary>
Public Property [VATNumber] As String
'''<summary>Website of the account</summary>
Public Property [Website] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [AccountClass]
'''<summary>Classification code</summary>
Public Property [Code] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Default credit management scenario to be used for new payment terms</summary>
Public Property [CreditManagementScenario] As Guid?
'''<summary>Description</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [AccountClassification]
'''<summary>Reference to Account classification name</summary>
Public Property [AccountClassificationName] As Guid?
'''<summary>Description of AccountClassificationName</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountClassificationNameDescription] As String
'''<summary>Account classification code</summary>
Public Property [Code] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Description</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [AccountClassificationName]
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Description</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Sequence number</summary>
Public Property [SequenceNumber] As Int32
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [Address]
'''<summary>Account linked to the address</summary>
Public Property [Account] As Guid?
'''<summary>Indicates if the account is a supplier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountIsSupplier] As Boolean?
'''<summary>Name of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountName] As String
'''<summary>First address line</summary>
Public Property [AddressLine1] As String
'''<summary>Second address line</summary>
Public Property [AddressLine2] As String
'''<summary>Third address line</summary>
Public Property [AddressLine3] As String
'''<summary>City</summary>
Public Property [City] As String
'''<summary>Contact linked to Address</summary>
Public Property [Contact] As Guid?
'''<summary>Contact name</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ContactName] As String
'''<summary>Country code</summary>
Public Property [Country] As String
'''<summary>Country name</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CountryName] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Fax number</summary>
Public Property [Fax] As String
'''<summary>Free boolean field 1</summary>
Public Property [FreeBoolField_01] As Boolean?
'''<summary>Free boolean field 2</summary>
Public Property [FreeBoolField_02] As Boolean?
'''<summary>Free boolean field 3</summary>
Public Property [FreeBoolField_03] As Boolean?
'''<summary>Free boolean field 4</summary>
Public Property [FreeBoolField_04] As Boolean?
'''<summary>Free boolean field 5</summary>
Public Property [FreeBoolField_05] As Boolean?
'''<summary>Free date field 1</summary>
Public Property [FreeDateField_01] As DateTime?
'''<summary>Free date field 2</summary>
Public Property [FreeDateField_02] As DateTime?
'''<summary>Free date field 3</summary>
Public Property [FreeDateField_03] As DateTime?
'''<summary>Free date field 4</summary>
Public Property [FreeDateField_04] As DateTime?
'''<summary>Free date field 5</summary>
Public Property [FreeDateField_05] As DateTime?
'''<summary>Free number field 1</summary>
Public Property [FreeNumberField_01] As Double?
'''<summary>Free number field 2</summary>
Public Property [FreeNumberField_02] As Double?
'''<summary>Free number field 3</summary>
Public Property [FreeNumberField_03] As Double?
'''<summary>Free number field 4</summary>
Public Property [FreeNumberField_04] As Double?
'''<summary>Free number field 5</summary>
Public Property [FreeNumberField_05] As Double?
'''<summary>Free text field 1</summary>
Public Property [FreeTextField_01] As String
'''<summary>Free text field 2</summary>
Public Property [FreeTextField_02] As String
'''<summary>Free text field 3</summary>
Public Property [FreeTextField_03] As String
'''<summary>Free text field 4</summary>
Public Property [FreeTextField_04] As String
'''<summary>Free text field 5</summary>
Public Property [FreeTextField_05] As String
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Mailbox</summary>
Public Property [Mailbox] As String
'''<summary>Indicates if the address is the main address for this type</summary>
Public Property [Main] As Boolean?
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Last 5 digits of SIRET number which is an intern sequential number of 4 digits representing the identification of the localization of the office</summary>
Public Property [NicNumber] As String
'''<summary>Notes for an address</summary>
Public Property [Notes] As String
'''<summary>Phone number</summary>
Public Property [Phone] As String
'''<summary>Phone extension</summary>
Public Property [PhoneExtension] As String
'''<summary>Postcode</summary>
Public Property [Postcode] As String
'''<summary>State</summary>
Public Property [State] As String
'''<summary>Name of the State</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [StateDescription] As String
'''<summary>The type of address. Visit=1, Postal=2, Invoice=3, Delivery=4</summary>
Public Property [Type] As Int16?
'''<summary>The warehouse linked to the address, if a warehouse is linked the account will be empty. Can only be filled for type=Delivery</summary>
Public Property [Warehouse] As Guid?
'''<summary>Code of the warehoude</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [WarehouseCode] As String
'''<summary>Description of the warehouse</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [WarehouseDescription] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [AddressState]
'''<summary>Country code</summary>
Public Property [Country] As String
'''<summary>Description of state prefixed with the code</summary>
Public Property [DisplayValue] As String
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Latitude</summary>
Public Property [Latitude] As Double?
'''<summary>Longitude</summary>
Public Property [Longitude] As Double?
'''<summary>State name</summary>
Public Property [Name] As String
'''<summary>State code</summary>
Public Property [State] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [BankAccount]
'''<summary>Account (customer, supplier) to which the bank account belongs</summary>
Public Property [Account] As Guid?
'''<summary>The name of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountName] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Bank] As Guid?
'''<summary>The bank account number</summary>
Public Property [BankAccount] As String
'''<summary>Name of the holder of the bank account, as known by the bank</summary>
Public Property [BankAccountHolderName] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [BankDescription] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [BankName] As String
'''<summary>BIC code of the bank where the bank account is held</summary>
Public Property [BICCode] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Description of the bank account</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Format that belongs to the bank account number</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Format] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IBAN] As String
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Indicates if the bank account is the main bank account</summary>
Public Property [Main] As Boolean?
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>ID of the Payment service account. Used when Type is 'P' (Payment service)</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PaymentServiceAccount] As Guid?
'''<summary>The type indicates what entity the bank account is used for. A = Account (default), E = Employee, K = Cash, P = Payment service, R = Bank, S = Student, U = Unknown. Currently it's only possible to create 'Account' type bank accounts.</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Type] As String
'''<summary>Description of the Type</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [TypeDescription] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [Contact]
'''<summary>The account to which the contact belongs</summary>
Public Property [Account] As Guid?
'''<summary>Indicates if account is a customer</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountIsCustomer] As Boolean
'''<summary>Indicates if account is a supplier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountIsSupplier] As Boolean?
'''<summary>Reference to the main contact of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountMainContact] As Guid?
'''<summary>Name of the account</summary>
Public Property [AccountName] As String
'''<summary>Second address line</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressLine2] As String
'''<summary>Street name of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreet] As String
'''<summary>Street number of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreetNumber] As String
'''<summary>Street number suffix of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreetNumberSuffix] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AllowMailing] As Int32?
'''<summary>Birth date</summary>
Public Property [BirthDate] As DateTime?
'''<summary>Obsolete. Please don't use this field anymore as it may overwrite LastName.</summary>
Public Property [BirthName] As String
'''<summary>Obsolete. Please don't use this field anymore as it may overwrite MiddleName.</summary>
Public Property [BirthNamePrefix] As String
'''<summary>Birth place</summary>
Public Property [BirthPlace] As String
'''<summary>Email address of the contact</summary>
Public Property [BusinessEmail] As String
'''<summary>Fax of the contact</summary>
Public Property [BusinessFax] As String
'''<summary>Mobile of the contact</summary>
Public Property [BusinessMobile] As String
'''<summary>Phone of the contact</summary>
Public Property [BusinessPhone] As String
'''<summary>Phone extension of the contact</summary>
Public Property [BusinessPhoneExtension] As String
'''<summary>City</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [City] As String
'''<summary>Code of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Code] As String
'''<summary>Country code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Country] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Email address of the contact</summary>
Public Property [Email] As String
'''<summary>End date</summary>
Public Property [EndDate] As DateTime?
'''<summary>First name. Provide at least first name or last name to create a new contact</summary>
Public Property [FirstName] As String
'''<summary>Full name (First name Middle name Last name)</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [FullName] As String
'''<summary>Gender</summary>
Public Property [Gender] As String
'''<summary>Contact ID</summary>
Public Property [HID] As Int32?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Identification date</summary>
Public Property [IdentificationDate] As DateTime?
'''<summary>Reference to the identification document of the contact</summary>
Public Property [IdentificationDocument] As Guid?
'''<summary>Reference to the user responsible for identification</summary>
Public Property [IdentificationUser] As Guid?
'''<summary>Initials</summary>
Public Property [Initials] As String
'''<summary>Indicates whether contacts are excluded from the marketing list</summary>
Public Property [IsMailingExcluded] As Boolean?
'''<summary>Indicates if this is the main contact of the linked account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsMainContact] As Boolean?
'''<summary>Jobtitle of the contact</summary>
Public Property [JobTitleDescription] As String
'''<summary>Language code</summary>
Public Property [Language] As String
'''<summary>Last name. Provide at least first name or last name to create a new contact</summary>
Public Property [LastName] As String
'''<summary>The user should be able to do a full text search on these notes to gather contacts for a marketing campaign</summary>
Public Property [MarketingNotes] As String
'''<summary>Middle name</summary>
Public Property [MiddleName] As String
'''<summary>Business phone of the contact</summary>
Public Property [Mobile] As String
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of the last modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Nationality</summary>
Public Property [Nationality] As String
'''<summary>Extra remarks</summary>
Public Property [Notes] As String
'''<summary>Last name of partner</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PartnerName] As String
'''<summary>Middlename of partner</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PartnerNamePrefix] As String
'''<summary>Reference to the personal information of this contact such as name, gender, address etc.</summary>
Public Property [Person] As Guid?
'''<summary>Phone of the contact</summary>
Public Property [Phone] As String
'''<summary>Phone extension of the contact</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PhoneExtension] As String
'''<summary>This field is write-only. The picture can be downloaded through PictureUrl and PictureThumbnailUrl.</summary>
Public Property [Picture] As Byte()
'''<summary>Filename of the picture</summary>
Public Property [PictureName] As String
'''<summary>Url to retrieve the picture thumbnail</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PictureThumbnailUrl] As String
'''<summary>Url to retrieve the picture</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PictureUrl] As String
'''<summary>Postcode</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Postcode] As String
'''<summary>Social security number</summary>
Public Property [SocialSecurityNumber] As String
'''<summary>Start date</summary>
Public Property [StartDate] As DateTime?
'''<summary>State</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [State] As String
'''<summary>Title</summary>
Public Property [Title] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [Document]
'''<summary>ID of the related account of this document</summary>
Public Property [Account] As Guid?
'''<summary>Attachments linked to the document. Binaries are not sent in the response.</summary>
Public Property [Attachments] As IEnumerable(Of Models.CRM.DocumentsAttachment)
'''<summary>Body of this document</summary>
Public Property [Body] As String
'''<summary>Creation date</summary>
Public Property [Created] As DateTime
'''<summary>User ID of creator</summary>
Public Property [Creator] As Guid?
'''<summary>Name of creator</summary>
Public Property [CreatorFullName] As String
'''<summary>Division code</summary>
Public Property [Division] As Int32
'''<summary>Entry date of the incoming document</summary>
Public Property [DocumentDate] As DateTime?
'''<summary>Id of document folder</summary>
Public Property [DocumentFolder] As Guid?
'''<summary>Url to view the document</summary>
Public Property [DocumentViewUrl] As String
'''<summary>Indicates that the document body is empty</summary>
Public Property [HasEmptyBody] As Boolean
'''<summary>Human-readable ID, formatted as xx.xxx.xxx. Unique. May not be equal to zero</summary>
Public Property [HID] As Int32
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Last modified date</summary>
Public Property [Modified] As DateTime
'''<summary>User ID of modifier</summary>
Public Property [Modifier] As Guid?
'''<summary>The opportunity linked to the document</summary>
Public Property [Opportunity] As Guid?
'''<summary>Purchase invoice number.</summary>
Public Property [PurchaseInvoiceNumber] As Int32?
'''<summary>Purchase order number.</summary>
Public Property [PurchaseOrderNumber] As Int32?
'''<summary>'Our reference' of the transaction that belongs to this document</summary>
Public Property [SalesInvoiceNumber] As Int32?
'''<summary>Number of the sales order</summary>
Public Property [SalesOrderNumber] As Int32?
'''<summary>Send Method</summary>
Public Property [SendMethod] As Int32?
Public Property [Share] As Int32
'''<summary>Subject of this document</summary>
Public Property [Subject] As String
'''<summary>The document type</summary>
Public Property [Type] As Int32
'''<summary>Translated description of the document type. $filter and $orderby are not supported for this property.</summary>
Public Property [TypeDescription] As String
'''<summary>Translation id of the document type description</summary>
Public Property [TypeDescriptionTermId] As Int32
'''<summary>English description of the document type</summary>
Public Property [UntermedTypeDescription] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [DocumentsAttachment]
'''<summary>Filename of the attachment</summary>
Public Property [AttachmentFileName] As String
'''<summary>File size of the attachment</summary>
Public Property [AttachmentFileSize] As Double
'''<summary>Url for downloading the attachment. To get the file in its original format (xml, jpg, pdf, etc.) append <b>&Download=1</b> to the url.</summary>
Public Property [AttachmentUrl] As String
Public Property [CanShowInWebView] As Boolean
'''<summary>Primary key</summary>
Public Property [ID] As Guid
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [Opportunity]
'''<summary>Lead to which the opportunity applies</summary>
Public Property [Account] As Guid?
'''<summary>Accountant linked to the opportunity</summary>
Public Property [Accountant] As Guid?
'''<summary>Code of the Accountant</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountantCode] As String
'''<summary>Name of the Accountant</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountantName] As String
'''<summary>Code of Account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountCode] As String
'''<summary>Name of Account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountName] As String
'''<summary>Indicates the date before/on the NextAction is supposed to be done</summary>
Public Property [ActionDate] As DateTime?
'''<summary>Amount in the default currency of the company. AmountDC = AmountFC * RateFC</summary>
Public Property [AmountDC] As Double?
'''<summary>Amount in the currency of the transaction</summary>
Public Property [AmountFC] As Double?
'''<summary>Reference to the campaign opportunity is related to</summary>
Public Property [Campaign] As Guid?
'''<summary>Description of Campaign</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CampaignDescription] As String
'''<summary>Reference to the channel opportunity is related to</summary>
Public Property [Channel] As Int16?
'''<summary>Description of Channel</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ChannelDescription] As String
'''<summary>The date when the opportunity is expected to be closed</summary>
Public Property [CloseDate] As DateTime?
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Currency code</summary>
Public Property [Currency] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>The source of the lead/opportunity</summary>
Public Property [LeadSource] As Guid?
'''<summary>Description of LeadSource</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [LeadSourceDescription] As String
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of the last modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Name of the opportunity</summary>
Public Property [Name] As String
'''<summary>Indicates what follow up action is to be undertaken to move the opportunity towards a deal. Is used in combination with ActionDate</summary>
Public Property [NextAction] As String
'''<summary>Notes of the opportunity</summary>
Public Property [Notes] As String
'''<summary>The stage of the opportunity. This is a list defined by the user</summary>
Public Property [OpportunityStage] As Guid?
'''<summary>Description of OpportunityStage</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OpportunityStageDescription] As String
'''<summary>Status: 1=Open, 2=Closed won, 3=Closed lost</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OpportunityStatus] As Int32?
'''<summary>Code of Opportunity Type</summary>
Public Property [OpportunityType] As Int16?
'''<summary>Description of Opportunity Type</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OpportunityTypeDescription] As String
'''<summary>The resource who owns the opportunity and is responsible to close the opportunity (either won or lost)</summary>
Public Property [Owner] As Guid?
'''<summary>Name of Owner</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OwnerFullName] As String
'''<summary>The chance that the opportunity will be closed and won. The default for the probability depends on the default from the opportunity stage</summary>
Public Property [Probability] As Double?
'''<summary>Reference to project</summary>
Public Property [Project] As Guid?
'''<summary>Code of Project</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ProjectCode] As String
'''<summary>Description of Project</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ProjectDescription] As String
'''<summary>Exchange rate from original to division currency</summary>
Public Property [RateFC] As Double?
'''<summary>Indicates the reason why the opportunity was lost.</summary>
Public Property [ReasonCode] As Guid?
'''<summary>Description of ReasonCode</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ReasonCodeDescription] As String
'''<summary>Reseller linked to the opportunity</summary>
Public Property [Reseller] As Guid?
'''<summary>Code of the Reseller</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ResellerCode] As String
'''<summary>Name of the Reseller</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ResellerName] As String
'''<summary>Reference to Sales type</summary>
Public Property [SalesType] As Guid?
'''<summary>Description of SalesType</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesTypeDescription] As String
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [OpportunityContact]
'''<summary>The account to which the contact belongs</summary>
Public Property [Account] As Guid?
'''<summary>Indicates if account is a customer</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountIsCustomer] As Boolean
'''<summary>Indicates if account is a supplier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountIsSupplier] As Boolean?
'''<summary>Reference to the main contact of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AccountMainContact] As Guid?
'''<summary>Name of the account</summary>
Public Property [AccountName] As String
'''<summary>Second address line</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressLine2] As String
'''<summary>Street name of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreet] As String
'''<summary>Street number of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreetNumber] As String
'''<summary>Street number suffix of the address</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AddressStreetNumberSuffix] As String
'''<summary>Obsolete</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AllowMailing] As Int32?
'''<summary>Birth date</summary>
Public Property [BirthDate] As DateTime?
'''<summary>Obsolete. Please don't use this field anymore as it may overwrite LastName.</summary>
Public Property [BirthName] As String
'''<summary>Obsolete. Please don't use this field anymore as it may overwrite MiddleName.</summary>
Public Property [BirthNamePrefix] As String
'''<summary>Birth place</summary>
Public Property [BirthPlace] As String
'''<summary>Email address of the contact</summary>
Public Property [BusinessEmail] As String
'''<summary>Fax of the contact</summary>
Public Property [BusinessFax] As String
'''<summary>Mobile of the contact</summary>
Public Property [BusinessMobile] As String
'''<summary>Phone of the contact</summary>
Public Property [BusinessPhone] As String
'''<summary>Phone extension of the contact</summary>
Public Property [BusinessPhoneExtension] As String
'''<summary>City</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [City] As String
'''<summary>Code of the account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Code] As String
'''<summary>Contact person that is linked to the opportunity</summary>
Public Property [Contact] As Guid?
'''<summary>Country code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Country] As String
'''<summary>Creation date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime?
'''<summary>User ID of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32?
'''<summary>Email address of the contact</summary>
Public Property [Email] As String
'''<summary>End date</summary>
Public Property [EndDate] As DateTime?
'''<summary>First name. Provide at least first name or last name to create a new contact</summary>
Public Property [FirstName] As String
'''<summary>Full name (First name Middle name Last name)</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [FullName] As String
'''<summary>Gender</summary>
Public Property [Gender] As String
'''<summary>Contact ID</summary>
Public Property [HID] As Int32?
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Identification date</summary>
Public Property [IdentificationDate] As DateTime?
'''<summary>Reference to the identification document of the contact</summary>
Public Property [IdentificationDocument] As Guid?
'''<summary>Reference to the user responsible for identification</summary>
Public Property [IdentificationUser] As Guid?
'''<summary>Initials</summary>
Public Property [Initials] As String
'''<summary>Indicates whether contacts are excluded from the marketing list</summary>
Public Property [IsMailingExcluded] As Boolean?
'''<summary>Indicates if this is the main contact of the linked account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [IsMainContact] As Boolean?
'''<summary>Jobtitle of the contact</summary>
Public Property [JobTitleDescription] As String
'''<summary>Language code</summary>
Public Property [Language] As String
'''<summary>Last name. Provide at least first name or last name to create a new contact</summary>
Public Property [LastName] As String
'''<summary>The user should be able to do a full text search on these notes to gather contacts for a marketing campaign</summary>
Public Property [MarketingNotes] As String
'''<summary>Middle name</summary>
Public Property [MiddleName] As String
'''<summary>Business phone of the contact</summary>
Public Property [Mobile] As String
'''<summary>Last modified date</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of the last modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Nationality</summary>
Public Property [Nationality] As String
'''<summary>Extra remarks</summary>
Public Property [Notes] As String
'''<summary>Opportunity that is linked to the contact person</summary>
Public Property [Opportunity] As Guid?
'''<summary>Last name of partner</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PartnerName] As String
'''<summary>Middlename of partner</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PartnerNamePrefix] As String
'''<summary>Reference to the personal information of this contact such as name, gender, address etc.</summary>
Public Property [Person] As Guid?
'''<summary>Phone of the contact</summary>
Public Property [Phone] As String
'''<summary>Phone extension of the contact</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PhoneExtension] As String
'''<summary>This field is write-only. The picture can be downloaded through PictureUrl and PictureThumbnailUrl.</summary>
Public Property [Picture] As Byte()
'''<summary>Filename of the picture</summary>
Public Property [PictureName] As String
'''<summary>Url to retrieve the picture thumbnail</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PictureThumbnailUrl] As String
'''<summary>Url to retrieve the picture</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [PictureUrl] As String
'''<summary>Postcode</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Postcode] As String
'''<summary>Social security number</summary>
Public Property [SocialSecurityNumber] As String
'''<summary>Start date</summary>
Public Property [StartDate] As DateTime?
'''<summary>State</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [State] As String
'''<summary>Title</summary>
Public Property [Title] As String
End Class
<SupportedActionsSDK(True, False, False, False)>
<DataServiceKey("QuotationID")>
Public Class [PrintQuotation]
'''<summary>Division code</summary>
Public Property [Division] As Int32
'''<summary>Contains the id of the document that was created</summary>
Public Property [Document] As Guid?
'''<summary>Contains the error message if an error occurred during the creation of the document</summary>
Public Property [DocumentCreationError] As String
'''<summary>Contains information if a document was successfully created</summary>
Public Property [DocumentCreationSuccess] As String
'''<summary>Based on this layout a PDF is created and attached to an Exact Online document and an email. In case it is not specified, the default layout is used.</summary>
Public Property [DocumentLayout] As Guid?
'''<summary>Contains the error message if an error occurred during the creation of the Email</summary>
Public Property [EmailCreationError] As String
'''<summary>Based on this layout the email text is produced. In case it is not specified, the default layout is used.</summary>
Public Property [EmailLayout] As Guid?
'''<summary>Extra text that can be added to the printed document and email</summary>
Public Property [ExtraText] As String
'''<summary>Date of the quotation printed</summary>
Public Property [QuotationDate] As DateTime
'''<summary>Identifier of the quotation</summary>
Public Property [QuotationID] As Guid
'''<summary>Set to True if an email containing the quotation should be sent to the customer</summary>
Public Property [SendEmailToCustomer] As Boolean
'''<summary>Email address from which the email will be sent. If not specified, the company email address will be used.</summary>
Public Property [SenderEmailAddress] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("QuotationID")>
Public Class [Quotation]
'''<summary>Amount in the default currency of the company</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AmountDC] As Double
'''<summary>Amount in the currency of the transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AmountFC] As Double
'''<summary>Date on which the customer accepted or rejected the quotation version</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CloseDate] As DateTime?
'''<summary>Date on which you expect to close/win the deal</summary>
Public Property [ClosingDate] As DateTime?
'''<summary>Date and time on which the quotation was created</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Created] As DateTime
'''<summary>User ID of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of the creator</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [CreatorFullName] As String
'''<summary>The currency of the quotation</summary>
Public Property [Currency] As String
'''<summary>The account where the items should delivered</summary>
Public Property [DeliveryAccount] As Guid?
'''<summary>The code of the delivery account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [DeliveryAccountCode] As String
'''<summary>The contact person of the delivery account</summary>
Public Property [DeliveryAccountContact] As Guid?
'''<summary>Full name of the delivery account contact person</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [DeliveryAccountContactFullName] As String
'''<summary>The name of the delivery account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [DeliveryAccountName] As String
'''<summary>The id of the delivery address</summary>
Public Property [DeliveryAddress] As Guid?
'''<summary>The description of the quotation</summary>
Public Property [Description] As String
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32
'''<summary>Document linked to the quotation</summary>
Public Property [Document] As Guid?
'''<summary>The subject of the document</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [DocumentSubject] As String
'''<summary>Date after which the quotation is no longer valid</summary>
Public Property [DueDate] As DateTime?
'''<summary>The account to which the invoice is sent</summary>
Public Property [InvoiceAccount] As Guid?
'''<summary>The code of the invoice account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvoiceAccountCode] As String
'''<summary>The contact person of the invoice account</summary>
Public Property [InvoiceAccountContact] As Guid?
'''<summary>Full name of the invoice account contact person</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvoiceAccountContactFullName] As String
'''<summary>The name of the invoice account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [InvoiceAccountName] As String
'''<summary>Date and time on which the quotation was last modified</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modified] As DateTime
'''<summary>User ID of the modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Modifier] As Guid?
'''<summary>Name of the modifier</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ModifierFullName] As String
'''<summary>Opportunity linked to the quotation</summary>
Public Property [Opportunity] As Guid?
'''<summary>The name of the opportunity</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OpportunityName] As String
'''<summary>The account that requested the quotation</summary>
Public Property [OrderAccount] As Guid?
'''<summary>The code of the order account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OrderAccountCode] As String
'''<summary>The contact person of the order account</summary>
Public Property [OrderAccountContact] As Guid?
'''<summary>Full name of the order account contact person</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OrderAccountContactFullName] As String
'''<summary>The name of the order account</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [OrderAccountName] As String
'''<summary>The project linked to the quotation</summary>
Public Property [Project] As Guid?
'''<summary>The code of the project</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ProjectCode] As String
'''<summary>The description of the project</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ProjectDescription] As String
'''<summary>Date on which the quotation version is entered or printed. Both during entering and printing this date can be adjusted</summary>
Public Property [QuotationDate] As DateTime?
'''<summary>Identifier of the quotation</summary>
Public Property [QuotationID] As Guid
'''<summary>The collection of quotation lines</summary>
Public Property [QuotationLines] As IEnumerable(Of Models.CRM.QuotationLine)
'''<summary>Unique number to indentify the quotation. By default this number is based on the setting for first available number</summary>
Public Property [QuotationNumber] As Int32
'''<summary>Extra text that can be added to the quotation</summary>
Public Property [Remarks] As String
'''<summary>The user that is responsible for the quotation version</summary>
Public Property [SalesPerson] As Guid?
'''<summary>Full name of the sales person</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [SalesPersonFullName] As String
'''<summary>The status of the quotation version. 5 = Rejected, 6 = Reviewed and closed, 10 = Recovery, 20 = Draft, 25 = Open, 35 = Processing... , 40 = Printed, 50 = Accepted</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Status] As Int16?
'''<summary>The description of the status</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [StatusDescription] As String
'''<summary>Total VAT amount in the currency of the transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VATAmountFC] As Double?
'''<summary>Number indicating the different reviews which are made for the quotation</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VersionNumber] As Int32
'''<summary>The number by which this quotation is identified by the order account</summary>
Public Property [YourRef] As String
End Class
<SupportedActionsSDK(True, True, True, True)>
<DataServiceKey("ID")>
Public Class [QuotationLine]
'''<summary>Amount in the default currency of the company</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AmountDC] As Double
'''<summary>Amount in the currency of the transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [AmountFC] As Double
'''<summary>By default this contains the item description</summary>
Public Property [Description] As String
'''<summary>Discount given on the default price. This is stored as a fraction. ie 5.5% is stored as .055</summary>
Public Property [Discount] As Double?
'''<summary>Division code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Division] As Int32
'''<summary>Primary key</summary>
Public Property [ID] As Guid
'''<summary>Reference to the item that is sold in this quotation line</summary>
Public Property [Item] As Guid?
'''<summary>Description of the item</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [ItemDescription] As String
'''<summary>Indicates the sequence of the lines within one quotation</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [LineNumber] As Int32
'''<summary>Net price of the quotation line</summary>
Public Property [NetPrice] As Double?
'''<summary>Extra notes</summary>
Public Property [Notes] As String
'''<summary>The number of items sold in default units. The quantity shown in the entry screen is Quantity * UnitFactor</summary>
Public Property [Quantity] As Double?
'''<summary>Identifies the quotation. All the lines of a quotation have the same QuotationID</summary>
Public Property [QuotationID] As Guid
'''<summary>Unique number to indentify the quotation. By default this number is based on the setting for first available number</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [QuotationNumber] As Int32
'''<summary>Code of the item unit</summary>
Public Property [UnitCode] As String
'''<summary>Description of the item unit</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [UnitDescription] As String
'''<summary>Price per item unit</summary>
Public Property [UnitPrice] As Double?
'''<summary>VAT amount of the line in the currency of the transaction</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VATAmountFC] As Double?
'''<summary>The VAT code that is used when the quotation is invoiced</summary>
Public Property [VATCode] As String
'''<summary>Description of the VAT code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VATDescription] As String
'''<summary>The VAT percentage of the VAT code</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VATPercentage] As Double?
'''<summary>Number indicating the different reviews which are made for the quotation</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [VersionNumber] As Int32
End Class
<SupportedActionsSDK(False, True, False, False)>
<DataServiceKey("ID")>
Public Class [ReasonCode]
'''<summary>Indicates if the reason code is active.</summary>
Public Property [Active] As Byte?
'''<summary>Code of the reason.</summary>
Public Property [Code] As String
'''<summary>Creation date.</summary>
Public Property [Created] As DateTime?
'''<summary>User ID of creator.</summary>
<SDKFieldType(FieldType.ReadOnly)>
Public Property [Creator] As Guid?
'''<summary>Name of creator.</summary>
Public Property [CreatorFullName] As String
'''<summary>Description of the reason code.</summary>
Public Property [Description] As String
'''<summary>Division code.</summary>
Public Property [Division] As Int32?
'''<summary>Primary key.</summary>
Public Property [ID] As Guid
'''<summary>Last modified date.</summary>
Public Property [Modified] As DateTime?
'''<summary>User ID of modifier.</summary>
Public Property [Modifier] As Guid?
'''<summary>Name of modifier.</summary>
Public Property [ModifierFullName] As String
'''<summary>Extra notes.</summary>
Public Property [Notes] As String
'''<summary>Type of the reason code.</summary>
Public Property [Type] As Int16?
'''<summary>Description of the type of the reason code.</summary>
Public Property [TypeDescription] As String
End Class
<SupportedActionsSDK(True, False, False, False)>
<DataServiceKey("QuotationID")>
Public Class [RejectQuotation]
'''<summary>Division code.</summary>
Public Property [Division] As Int32
'''<summary>Contains the error message if an error occurred during the rejection of the quotation.</summary>
Public Property [ErrorMessage] As String
'''<summary>Identifier of the quotation.</summary>
Public Property [QuotationID] As Guid
'''<summary>Reason why the quotation was rejected.</summary>
Public Property [ReasonCode] As Guid?
'''<summary>Contains information if the quotation was successfully rejected.</summary>
Public Property [SuccessMessage] As String
End Class
<SupportedActionsSDK(True, False, False, False)>
<DataServiceKey("QuotationID")>
Public Class [ReopenQuotation]
'''<summary>Division code.</summary>
Public Property [Division] As Int32
'''<summary>Contains the error message if an error occurred during the reopening of the quotation.</summary>
Public Property [ErrorMessage] As String
'''<summary>Identifier of the quotation.</summary>
Public Property [QuotationID] As Guid
'''<summary>Contains information if the quotation was successfully reopened.</summary>
Public Property [SuccessMessage] As String
End Class
<SupportedActionsSDK(True, False, False, False)>
<DataServiceKey("QuotationID")>
Public Class [ReviewQuotation]
'''<summary>Indicates if the item prices should be copied from the original quotation or the default item prices should be used.</summary>
Public Property [CopyItemPrices] As Boolean?
'''<summary>The description of the new quotation.</summary>
Public Property [Description] As String
'''<summary>Division code.</summary>
Public Property [Division] As Int32
'''<summary>The document linked to the new quotation.</summary>
Public Property [Document] As Guid?
'''<summary>Contains the error message if an error occurred during the reviewing of the quotation.</summary>
Public Property [ErrorMessage] As String
'''<summary>Identifier of the newly created quotation.</summary>
Public Property [NewQuotationID] As Guid?
'''<summary>The account who made the order.</summary>
Public Property [OrderAccount] As Guid?
'''<summary>The contact person of the account who made the order.</summary>
Public Property [OrderAccountContact] As Guid?
'''<summary>The paymentcondition linked to the new quotation.</summary>
Public Property [PaymentCondition] As String
'''<summary>The date of the new quotation.</summary>
Public Property [QuotationDate] As DateTime?
'''<summary>Identifier of the quotation.</summary>
Public Property [QuotationID] As Guid
'''<summary>Contains information if the quotation was successfully reviewed.</summary>
Public Property [SuccessMessage] As String
End Class
End Namespace
|
shtrip/exactonline-api-dotnet-client
|
src/ExactOnline.Client.Models/CRM.vb
|
Visual Basic
|
mit
| 73,840
|
Imports System
Imports System.Net
Imports System.Collections.Generic
Imports Independentsoft.Exchange
Namespace Sample
Class Module1
Shared Sub Main(ByVal args As String())
Dim credential As New NetworkCredential("username", "password")
Dim service As New Service("https://myserver/ews/Exchange.asmx", credential)
service.RequestServerVersion = RequestServerVersion.Exchange2010SP1
Try
Dim timeZone As TimeZoneDefinition = GetTimeZone(service, "Berlin") ''find time zone based on name
''Dim timeZone As TimeZoneDefinition = GetTimeZone(service, "UTC-08:00") ''find time zone based on offset
'Montly recurrence. Last friday in every month.
Dim days As New List(Of Independentsoft.Exchange.DayOfWeek)()
days.Add(Independentsoft.Exchange.DayOfWeek.Friday)
Dim recurrence As New Recurrence()
recurrence.Pattern = New RelativeMonthlyRecurrencePattern(1, days, DayOfWeekIndex.Last)
recurrence.Range = New NoEndRecurrenceRange(DateTime.Today)
Dim appointment As New Appointment()
appointment.Subject = "Last friday"
appointment.Body = New Body("Body text")
appointment.StartTime = DateTime.Today.AddHours(15)
appointment.EndTime = DateTime.Today.AddHours(16)
appointment.Recurrence = recurrence
appointment.StartTimeZone = timeZone
appointment.EndTimeZone = timeZone
Dim itemId As ItemId = service.CreateItem(appointment)
Catch ex As ServiceRequestException
Console.WriteLine("Error: " + ex.Message)
Console.WriteLine("Error: " + ex.XmlMessage)
Console.Read()
Catch ex As WebException
Console.WriteLine("Error: " + ex.Message)
Console.Read()
End Try
End Sub
Private Shared Function GetTimeZone(ByVal service As Service, ByVal name As String) As TimeZoneDefinition
Dim Response As GetServerTimeZonesResponse = service.GetServerTimeZones()
For Each timeZone As TimeZoneDefinition In Response.TimeZoneDefinitions
If timeZone.Name.IndexOf(name) > 0 Then
Return timeZone
End If
Next
Return Nothing
End Function
End Class
End Namespace
|
age-killer/Electronic-invoice-document-processing
|
MailSort_CSHARP/packages/Independentsoft.Exchange.3.0.400/Tutorial/VBCreateRecurringAppointment3/Module1.vb
|
Visual Basic
|
mit
| 2,516
|
Partial Class RepNota4
'NOTE: The following procedure is required by the telerik Reporting Designer
'It can be modified using the telerik Reporting Designer.
'Do not modify it using the code editor.
Private Sub InitializeComponent()
Dim ReportParameter1 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim ReportParameter2 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim ReportParameter3 As Telerik.Reporting.ReportParameter = New Telerik.Reporting.ReportParameter()
Dim StyleRule1 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule2 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule3 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Dim StyleRule4 As Telerik.Reporting.Drawing.StyleRule = New Telerik.Reporting.Drawing.StyleRule()
Me.SDSRepNota4 = New Telerik.Reporting.SqlDataSource()
Me.labelsGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.fECHADOCUMENTOCaptionTextBox = New Telerik.Reporting.TextBox()
Me.rucCaptionTextBox = New Telerik.Reporting.TextBox()
Me.razonSocialCaptionTextBox = New Telerik.Reporting.TextBox()
Me.registroCaptionTextBox = New Telerik.Reporting.TextBox()
Me.montoCaptionTextBox = New Telerik.Reporting.TextBox()
Me.labelsGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.labelsGroup = New Telerik.Reporting.Group()
Me.cuentaGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.cuentaDataTextBox = New Telerik.Reporting.TextBox()
Me.cuentaGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.TextBox2 = New Telerik.Reporting.TextBox()
Me.montoSumFunctionTextBox = New Telerik.Reporting.TextBox()
Me.cuentaGroup = New Telerik.Reporting.Group()
Me.proyectoGroupHeader = New Telerik.Reporting.GroupHeaderSection()
Me.proyectoDataTextBox = New Telerik.Reporting.TextBox()
Me.proyectoGroupFooter = New Telerik.Reporting.GroupFooterSection()
Me.montoSumFunctionTextBox1 = New Telerik.Reporting.TextBox()
Me.TextBox3 = New Telerik.Reporting.TextBox()
Me.proyectoGroup = New Telerik.Reporting.Group()
Me.reportFooter = New Telerik.Reporting.ReportFooterSection()
Me.TextBox1 = New Telerik.Reporting.TextBox()
Me.montoSumFunctionTextBox2 = New Telerik.Reporting.TextBox()
Me.pageHeader = New Telerik.Reporting.PageHeaderSection()
Me.pageFooter = New Telerik.Reporting.PageFooterSection()
Me.reportHeader = New Telerik.Reporting.ReportHeaderSection()
Me.TextBox4 = New Telerik.Reporting.TextBox()
Me.detail = New Telerik.Reporting.DetailSection()
Me.fECHADOCUMENTODataTextBox = New Telerik.Reporting.TextBox()
Me.rucDataTextBox = New Telerik.Reporting.TextBox()
Me.razonSocialDataTextBox = New Telerik.Reporting.TextBox()
Me.registroDataTextBox = New Telerik.Reporting.TextBox()
Me.montoDataTextBox = New Telerik.Reporting.TextBox()
CType(Me, System.ComponentModel.ISupportInitialize).BeginInit()
'
'SDSRepNota4
'
Me.SDSRepNota4.ConnectionString = "cnx"
Me.SDSRepNota4.Name = "SDSRepNota4"
Me.SDSRepNota4.Parameters.AddRange(New Telerik.Reporting.SqlDataSourceParameter() {New Telerik.Reporting.SqlDataSourceParameter("@fechaFin", System.Data.DbType.DateTime, "=Parameters.fechaFin.Value"), New Telerik.Reporting.SqlDataSourceParameter("@idProyecto", System.Data.DbType.Int32, "=Parameters.idProyecto.Value"), New Telerik.Reporting.SqlDataSourceParameter("@tipo", System.Data.DbType.AnsiStringFixedLength, "=Parameters.tipo.Value")})
Me.SDSRepNota4.SelectCommand = "dbo.RepNota4"
Me.SDSRepNota4.SelectCommandType = Telerik.Reporting.SqlDataSourceCommandType.StoredProcedure
'
'labelsGroupHeader
'
Me.labelsGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.fECHADOCUMENTOCaptionTextBox, Me.rucCaptionTextBox, Me.razonSocialCaptionTextBox, Me.registroCaptionTextBox, Me.montoCaptionTextBox})
Me.labelsGroupHeader.Name = "labelsGroupHeader"
Me.labelsGroupHeader.PrintOnEveryPage = True
'
'fECHADOCUMENTOCaptionTextBox
'
Me.fECHADOCUMENTOCaptionTextBox.CanGrow = True
Me.fECHADOCUMENTOCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.000099921220680698752R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fECHADOCUMENTOCaptionTextBox.Name = "fECHADOCUMENTOCaptionTextBox"
Me.fECHADOCUMENTOCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fECHADOCUMENTOCaptionTextBox.Style.Font.Name = "Arial"
Me.fECHADOCUMENTOCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.fECHADOCUMENTOCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.fECHADOCUMENTOCaptionTextBox.StyleName = "Caption"
Me.fECHADOCUMENTOCaptionTextBox.Value = "FECHA DOC."
'
'rucCaptionTextBox
'
Me.rucCaptionTextBox.CanGrow = True
Me.rucCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0002000331878662R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucCaptionTextBox.Name = "rucCaptionTextBox"
Me.rucCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucCaptionTextBox.Style.Font.Name = "Arial"
Me.rucCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.rucCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.rucCaptionTextBox.StyleName = "Caption"
Me.rucCaptionTextBox.Value = "RUC"
'
'razonSocialCaptionTextBox
'
Me.razonSocialCaptionTextBox.CanGrow = True
Me.razonSocialCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(4.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.000099921220680698752R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialCaptionTextBox.Name = "razonSocialCaptionTextBox"
Me.razonSocialCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(9.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialCaptionTextBox.Style.Font.Name = "Arial"
Me.razonSocialCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.razonSocialCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.razonSocialCaptionTextBox.StyleName = "Caption"
Me.razonSocialCaptionTextBox.Value = "RAZON SOCIAL"
'
'registroCaptionTextBox
'
Me.registroCaptionTextBox.CanGrow = True
Me.registroCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(13.000000953674316R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroCaptionTextBox.Name = "registroCaptionTextBox"
Me.registroCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroCaptionTextBox.Style.Font.Name = "Arial"
Me.registroCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.registroCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.registroCaptionTextBox.StyleName = "Caption"
Me.registroCaptionTextBox.Value = "DOCUMENTO"
'
'montoCaptionTextBox
'
Me.montoCaptionTextBox.CanGrow = True
Me.montoCaptionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoCaptionTextBox.Name = "montoCaptionTextBox"
Me.montoCaptionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoCaptionTextBox.Style.Font.Name = "Arial"
Me.montoCaptionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoCaptionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.montoCaptionTextBox.StyleName = "Caption"
Me.montoCaptionTextBox.Value = "IMPORTE"
'
'labelsGroupFooter
'
Me.labelsGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.labelsGroupFooter.Name = "labelsGroupFooter"
Me.labelsGroupFooter.Style.Visible = False
'
'labelsGroup
'
Me.labelsGroup.GroupFooter = Me.labelsGroupFooter
Me.labelsGroup.GroupHeader = Me.labelsGroupHeader
Me.labelsGroup.Name = "labelsGroup"
'
'cuentaGroupHeader
'
Me.cuentaGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.cuentaGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.cuentaDataTextBox})
Me.cuentaGroupHeader.Name = "cuentaGroupHeader"
'
'cuentaDataTextBox
'
Me.cuentaDataTextBox.CanGrow = True
Me.cuentaDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Name = "cuentaDataTextBox"
Me.cuentaDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(17.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.cuentaDataTextBox.Style.Font.Bold = True
Me.cuentaDataTextBox.Style.Font.Name = "Arial"
Me.cuentaDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.cuentaDataTextBox.StyleName = "Data"
Me.cuentaDataTextBox.Value = "=Fields.Cuenta"
'
'cuentaGroupFooter
'
Me.cuentaGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.cuentaGroupFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox2, Me.montoSumFunctionTextBox})
Me.cuentaGroupFooter.Name = "cuentaGroupFooter"
'
'TextBox2
'
Me.TextBox2.CanGrow = True
Me.TextBox2.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Name = "TextBox2"
Me.TextBox2.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox2.Style.Font.Name = "Arial"
Me.TextBox2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox2.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox2.StyleName = "Caption"
Me.TextBox2.Value = "TOTAL CUENTA:"
'
'montoSumFunctionTextBox
'
Me.montoSumFunctionTextBox.CanGrow = True
Me.montoSumFunctionTextBox.Format = "{0:N2}"
Me.montoSumFunctionTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(14.999899864196777R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox.Name = "montoSumFunctionTextBox"
Me.montoSumFunctionTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox.Style.Font.Name = "Arial"
Me.montoSumFunctionTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoSumFunctionTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoSumFunctionTextBox.StyleName = "Data"
Me.montoSumFunctionTextBox.Value = "=Sum(Fields.Monto)"
'
'cuentaGroup
'
Me.cuentaGroup.GroupFooter = Me.cuentaGroupFooter
Me.cuentaGroup.GroupHeader = Me.cuentaGroupHeader
Me.cuentaGroup.Groupings.AddRange(New Telerik.Reporting.Grouping() {New Telerik.Reporting.Grouping("=Fields.Cuenta")})
Me.cuentaGroup.Name = "cuentaGroup"
'
'proyectoGroupHeader
'
Me.proyectoGroupHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.proyectoGroupHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.proyectoDataTextBox})
Me.proyectoGroupHeader.Name = "proyectoGroupHeader"
'
'proyectoDataTextBox
'
Me.proyectoDataTextBox.CanGrow = True
Me.proyectoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.proyectoDataTextBox.Name = "proyectoDataTextBox"
Me.proyectoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(17.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.proyectoDataTextBox.Style.Font.Name = "Arial"
Me.proyectoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.proyectoDataTextBox.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.30000001192092896R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.proyectoDataTextBox.StyleName = "Data"
Me.proyectoDataTextBox.Value = "=Fields.Proyecto"
'
'proyectoGroupFooter
'
Me.proyectoGroupFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.proyectoGroupFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.montoSumFunctionTextBox1, Me.TextBox3})
Me.proyectoGroupFooter.Name = "proyectoGroupFooter"
'
'montoSumFunctionTextBox1
'
Me.montoSumFunctionTextBox1.CanGrow = True
Me.montoSumFunctionTextBox1.Format = "{0:N2}"
Me.montoSumFunctionTextBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(14.999899864196777R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox1.Name = "montoSumFunctionTextBox1"
Me.montoSumFunctionTextBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox1.Style.Font.Name = "Arial"
Me.montoSumFunctionTextBox1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoSumFunctionTextBox1.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoSumFunctionTextBox1.StyleName = "Data"
Me.montoSumFunctionTextBox1.Value = "=Sum(Fields.Monto)"
'
'TextBox3
'
Me.TextBox3.CanGrow = True
Me.TextBox3.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Name = "TextBox3"
Me.TextBox3.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(14.999699592590332R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox3.Style.Font.Name = "Arial"
Me.TextBox3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox3.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox3.StyleName = "Caption"
Me.TextBox3.Value = "TOTAL PROYECTO:"
'
'proyectoGroup
'
Me.proyectoGroup.GroupFooter = Me.proyectoGroupFooter
Me.proyectoGroup.GroupHeader = Me.proyectoGroupHeader
Me.proyectoGroup.Groupings.AddRange(New Telerik.Reporting.Grouping() {New Telerik.Reporting.Grouping("=Fields.Proyecto")})
Me.proyectoGroup.Name = "proyectoGroup"
'
'reportFooter
'
Me.reportFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportFooter.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox1, Me.montoSumFunctionTextBox2})
Me.reportFooter.Name = "reportFooter"
Me.reportFooter.Style.Visible = True
'
'TextBox1
'
Me.TextBox1.CanGrow = True
Me.TextBox1.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(15.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox1.Style.Font.Name = "Arial"
Me.TextBox1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox1.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.TextBox1.StyleName = "Caption"
Me.TextBox1.Value = "TOTAL GENERAL:"
'
'montoSumFunctionTextBox2
'
Me.montoSumFunctionTextBox2.CanGrow = True
Me.montoSumFunctionTextBox2.Format = "{0:N2}"
Me.montoSumFunctionTextBox2.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(14.999899864196777R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox2.Name = "montoSumFunctionTextBox2"
Me.montoSumFunctionTextBox2.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoSumFunctionTextBox2.Style.BorderStyle.Bottom = Telerik.Reporting.Drawing.BorderType.[Double]
Me.montoSumFunctionTextBox2.Style.BorderStyle.Top = Telerik.Reporting.Drawing.BorderType.Solid
Me.montoSumFunctionTextBox2.Style.Font.Name = "Arial"
Me.montoSumFunctionTextBox2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoSumFunctionTextBox2.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoSumFunctionTextBox2.StyleName = "Data"
Me.montoSumFunctionTextBox2.Value = "=Sum(Fields.Monto)"
'
'pageHeader
'
Me.pageHeader.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageHeader.Name = "pageHeader"
Me.pageHeader.Style.Visible = False
'
'pageFooter
'
Me.pageFooter.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.pageFooter.Name = "pageFooter"
Me.pageFooter.Style.Visible = False
'
'reportHeader
'
Me.reportHeader.Height = New Telerik.Reporting.Drawing.Unit(0.99990016222000122R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.reportHeader.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.TextBox4})
Me.reportHeader.Name = "reportHeader"
'
'TextBox4
'
Me.TextBox4.CanGrow = True
Me.TextBox4.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.00010012308484874666R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.000099921220680698752R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Name = "TextBox4"
Me.TextBox4.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(16.999900817871094R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.TextBox4.Style.Font.Bold = True
Me.TextBox4.Style.Font.Name = "Arial"
Me.TextBox4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(8.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.TextBox4.StyleName = "Caption"
Me.TextBox4.Value = "NOTA 04: CUENTAS POR COBRAR COMERCIALES"
'
'detail
'
Me.detail.Height = New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.detail.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.fECHADOCUMENTODataTextBox, Me.rucDataTextBox, Me.razonSocialDataTextBox, Me.registroDataTextBox, Me.montoDataTextBox})
Me.detail.Name = "detail"
'
'fECHADOCUMENTODataTextBox
'
Me.fECHADOCUMENTODataTextBox.CanGrow = True
Me.fECHADOCUMENTODataTextBox.Format = "{0:d}"
Me.fECHADOCUMENTODataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fECHADOCUMENTODataTextBox.Name = "fECHADOCUMENTODataTextBox"
Me.fECHADOCUMENTODataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.fECHADOCUMENTODataTextBox.Style.Font.Name = "Arial"
Me.fECHADOCUMENTODataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.fECHADOCUMENTODataTextBox.Style.Padding.Left = New Telerik.Reporting.Drawing.Unit(0.30000001192092896R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.fECHADOCUMENTODataTextBox.StyleName = "Data"
Me.fECHADOCUMENTODataTextBox.Value = "=Fields.FECHADOCUMENTO"
'
'rucDataTextBox
'
Me.rucDataTextBox.CanGrow = True
Me.rucDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(2.0001997947692871R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucDataTextBox.Name = "rucDataTextBox"
Me.rucDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.rucDataTextBox.Style.Font.Name = "Arial"
Me.rucDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.rucDataTextBox.StyleName = "Data"
Me.rucDataTextBox.Value = "=Fields.Ruc"
'
'razonSocialDataTextBox
'
Me.razonSocialDataTextBox.CanGrow = True
Me.razonSocialDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(4.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialDataTextBox.Name = "razonSocialDataTextBox"
Me.razonSocialDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(9.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.razonSocialDataTextBox.Style.Font.Name = "Arial"
Me.razonSocialDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.razonSocialDataTextBox.StyleName = "Data"
Me.razonSocialDataTextBox.Value = "=Fields.RazonSocial"
'
'registroDataTextBox
'
Me.registroDataTextBox.CanGrow = True
Me.registroDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(13.000000953674316R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroDataTextBox.Name = "registroDataTextBox"
Me.registroDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.registroDataTextBox.Style.Font.Name = "Arial"
Me.registroDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.registroDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Center
Me.registroDataTextBox.StyleName = "Data"
Me.registroDataTextBox.Value = "=Fields.Registro"
'
'montoDataTextBox
'
Me.montoDataTextBox.CanGrow = True
Me.montoDataTextBox.Format = "{0:N2}"
Me.montoDataTextBox.Location = New Telerik.Reporting.Drawing.PointU(New Telerik.Reporting.Drawing.Unit(14.999899864196777R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.0R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoDataTextBox.Name = "montoDataTextBox"
Me.montoDataTextBox.Size = New Telerik.Reporting.Drawing.SizeU(New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm), New Telerik.Reporting.Drawing.Unit(0.5R, Telerik.Reporting.Drawing.UnitType.Cm))
Me.montoDataTextBox.Style.Font.Name = "Arial"
Me.montoDataTextBox.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(6.0R, Telerik.Reporting.Drawing.UnitType.Point)
Me.montoDataTextBox.Style.TextAlign = Telerik.Reporting.Drawing.HorizontalAlign.Right
Me.montoDataTextBox.StyleName = "Data"
Me.montoDataTextBox.Value = "=Fields.Monto"
'
'RepNota4
'
Me.DataSource = Me.SDSRepNota4
Me.Groups.AddRange(New Telerik.Reporting.Group() {Me.labelsGroup, Me.cuentaGroup, Me.proyectoGroup})
Me.Items.AddRange(New Telerik.Reporting.ReportItemBase() {Me.labelsGroupHeader, Me.labelsGroupFooter, Me.cuentaGroupHeader, Me.cuentaGroupFooter, Me.proyectoGroupHeader, Me.proyectoGroupFooter, Me.reportFooter, Me.pageHeader, Me.pageFooter, Me.reportHeader, Me.detail})
Me.PageSettings.Landscape = False
Me.PageSettings.Margins.Bottom = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Left = New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Right = New Telerik.Reporting.Drawing.Unit(2.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.Margins.Top = New Telerik.Reporting.Drawing.Unit(1.0R, Telerik.Reporting.Drawing.UnitType.Cm)
Me.PageSettings.PaperKind = System.Drawing.Printing.PaperKind.A4
ReportParameter1.Name = "fechaFin"
ReportParameter1.Text = "fechaFin"
ReportParameter1.Type = Telerik.Reporting.ReportParameterType.DateTime
ReportParameter1.Visible = True
ReportParameter2.Name = "idProyecto"
ReportParameter2.Text = "idProyecto"
ReportParameter2.Type = Telerik.Reporting.ReportParameterType.[Integer]
ReportParameter2.Visible = True
ReportParameter3.Name = "tipo"
ReportParameter3.Text = "tipo"
ReportParameter3.Visible = True
Me.ReportParameters.Add(ReportParameter1)
Me.ReportParameters.Add(ReportParameter2)
Me.ReportParameters.Add(ReportParameter3)
Me.Style.BackgroundColor = System.Drawing.Color.White
StyleRule1.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Title")})
StyleRule1.Style.Color = System.Drawing.Color.Black
StyleRule1.Style.Font.Bold = True
StyleRule1.Style.Font.Italic = False
StyleRule1.Style.Font.Name = "Tahoma"
StyleRule1.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(20.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule1.Style.Font.Strikeout = False
StyleRule1.Style.Font.Underline = False
StyleRule2.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Caption")})
StyleRule2.Style.Color = System.Drawing.Color.Black
StyleRule2.Style.Font.Name = "Tahoma"
StyleRule2.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule2.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule3.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("Data")})
StyleRule3.Style.Font.Name = "Tahoma"
StyleRule3.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule3.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
StyleRule4.Selectors.AddRange(New Telerik.Reporting.Drawing.ISelector() {New Telerik.Reporting.Drawing.StyleSelector("PageInfo")})
StyleRule4.Style.Font.Name = "Tahoma"
StyleRule4.Style.Font.Size = New Telerik.Reporting.Drawing.Unit(11.0R, Telerik.Reporting.Drawing.UnitType.Point)
StyleRule4.Style.VerticalAlign = Telerik.Reporting.Drawing.VerticalAlign.Middle
Me.StyleSheet.AddRange(New Telerik.Reporting.Drawing.StyleRule() {StyleRule1, StyleRule2, StyleRule3, StyleRule4})
Me.Width = New Telerik.Reporting.Drawing.Unit(17.0R, Telerik.Reporting.Drawing.UnitType.Cm)
CType(Me, System.ComponentModel.ISupportInitialize).EndInit()
End Sub
Friend WithEvents SDSRepNota4 As Telerik.Reporting.SqlDataSource
Friend WithEvents labelsGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents fECHADOCUMENTOCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents rucCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents razonSocialCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents registroCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents montoCaptionTextBox As Telerik.Reporting.TextBox
Friend WithEvents labelsGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents labelsGroup As Telerik.Reporting.Group
Friend WithEvents cuentaGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents cuentaDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents cuentaGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents TextBox2 As Telerik.Reporting.TextBox
Friend WithEvents montoSumFunctionTextBox As Telerik.Reporting.TextBox
Friend WithEvents cuentaGroup As Telerik.Reporting.Group
Friend WithEvents proyectoGroupHeader As Telerik.Reporting.GroupHeaderSection
Friend WithEvents proyectoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents proyectoGroupFooter As Telerik.Reporting.GroupFooterSection
Friend WithEvents TextBox3 As Telerik.Reporting.TextBox
Friend WithEvents montoSumFunctionTextBox1 As Telerik.Reporting.TextBox
Friend WithEvents proyectoGroup As Telerik.Reporting.Group
Friend WithEvents reportFooter As Telerik.Reporting.ReportFooterSection
Friend WithEvents TextBox1 As Telerik.Reporting.TextBox
Friend WithEvents montoSumFunctionTextBox2 As Telerik.Reporting.TextBox
Friend WithEvents pageHeader As Telerik.Reporting.PageHeaderSection
Friend WithEvents pageFooter As Telerik.Reporting.PageFooterSection
Friend WithEvents reportHeader As Telerik.Reporting.ReportHeaderSection
Friend WithEvents detail As Telerik.Reporting.DetailSection
Friend WithEvents fECHADOCUMENTODataTextBox As Telerik.Reporting.TextBox
Friend WithEvents rucDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents razonSocialDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents registroDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents montoDataTextBox As Telerik.Reporting.TextBox
Friend WithEvents TextBox4 As Telerik.Reporting.TextBox
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.Report/RepNota4.Designer.vb
|
Visual Basic
|
mit
| 34,792
|
' 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.CodeAnalysis.Editor.Host
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.TextStructureNavigation
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Operations
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.TextStructureNavigation
Public Class TextStructureNavigatorTests
<Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestEmpty() As Task
Await AssertExtentAsync(
String.Empty,
pos:=0,
isSignificant:=False,
start:=0, length:=0)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestWhitespace() As Task
Await AssertExtentAsync(
" ",
pos:=0,
isSignificant:=False,
start:=0, length:=3)
Await AssertExtentAsync(
" ",
pos:=1,
isSignificant:=False,
start:=0, length:=3)
Await AssertExtentAsync(
" ",
pos:=3,
isSignificant:=False,
start:=0, length:=3)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestEndOfFile() As Task
Await AssertExtentAsync(
"Imports System",
pos:=14,
isSignificant:=True,
start:=8, length:=6)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestNewLine() As Task
Await AssertExtentAsync(
"Module Module1" & vbCrLf & vbCrLf & "End Module",
pos:=14,
isSignificant:=False,
start:=14, length:=2)
Await AssertExtentAsync(
"Module Module1" & vbCrLf & vbCrLf & "End Module",
pos:=15,
isSignificant:=False,
start:=14, length:=2)
Await AssertExtentAsync(
"Module Module1" & vbCrLf & vbCrLf & "End Module",
pos:=16,
isSignificant:=False,
start:=16, length:=2)
Await AssertExtentAsync(
"Module Module1" & vbCrLf & vbCrLf & "End Module",
pos:=17,
isSignificant:=False,
start:=16, length:=2)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestComment() As Task
Await AssertExtentAsync(
" ' Comment ",
pos:=1,
isSignificant:=True,
start:=1, length:=11)
Await AssertExtentAsync(
" ' Comment ",
pos:=5,
isSignificant:=True,
start:=3, length:=7)
Await AssertExtentAsync(
" ' () test",
pos:=4,
isSignificant:=True,
start:=3, length:=2)
Await AssertExtentAsync(
" REM () test",
pos:=1,
isSignificant:=True,
start:=1, length:=11)
Await AssertExtentAsync(
" rem () test",
pos:=6,
isSignificant:=True,
start:=5, length:=2)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestKeyword() As Task
For i = 7 To 12
Await AssertExtentAsync(
"Public Module Module1",
pos:=i,
isSignificant:=True,
start:=7, length:=6)
Next
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestIdentifier() As Task
For i = 13 To 13 + 8
Await AssertExtentAsync(
"Public Class SomeClass : Inherits Object",
pos:=i,
isSignificant:=True,
start:=13, length:=9)
Next
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestEscapedIdentifier() As Task
For i = 12 To 12 + 7
Await AssertExtentAsync(
"Friend Enum [Module] As Long",
pos:=i,
isSignificant:=True,
start:=12, length:=8)
Next
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestNumber() As Task
For i = 37 To 37 + 12
Await AssertExtentAsync(
"Class Test : Dim number As Double = -1.234678E-120 : End Class",
pos:=i,
isSignificant:=True,
start:=37, length:=13)
Next
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestString() As Task
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=33,
isSignificant:=True,
start:=33, length:=1)
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=34,
isSignificant:=False,
start:=34, length:=1)
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=35,
isSignificant:=True,
start:=35, length:=2)
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=43,
isSignificant:=False,
start:=42, length:=2)
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=44,
isSignificant:=True,
start:=44, length:=1)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.TextStructureNavigator)>
Public Async Function TestInterpolatedString() As Task
Await AssertExtentAsync(
"Class Test : Dim str As String = $"" () test "" : End Class",
pos:=33,
isSignificant:=True,
start:=33, length:=2)
Await AssertExtentAsync(
"Class Test : Dim str As String = $"" () test "" : End Class",
pos:=35,
isSignificant:=False,
start:=35, length:=1)
Await AssertExtentAsync(
"Class Test : Dim str As String = $"" () test "" : End Class",
pos:=36,
isSignificant:=True,
start:=36, length:=2)
Await AssertExtentAsync(
"Class Test : Dim str As String = $"" () test "" : End Class",
pos:=44,
isSignificant:=False,
start:=43, length:=2)
Await AssertExtentAsync(
"Class Test : Dim str As String = "" () test "" : End Class",
pos:=45,
isSignificant:=False,
start:=45, length:=1)
End Function
Private Shared Async Function AssertExtentAsync(
code As String,
pos As Integer,
isSignificant As Boolean,
start As Integer,
length As Integer) As Task
Using workspace = Await VisualBasicWorkspaceFactory.CreateWorkspaceFromLinesAsync(code)
Dim buffer = workspace.Documents.First().GetTextBuffer()
Dim provider = New TextStructureNavigatorProvider(
workspace.GetService(Of ITextStructureNavigatorSelectorService),
workspace.GetService(Of IContentTypeRegistryService),
workspace.GetService(Of IWaitIndicator))
Dim navigator = provider.CreateTextStructureNavigator(buffer)
Dim extent = navigator.GetExtentOfWord(New SnapshotPoint(buffer.CurrentSnapshot, pos))
Assert.Equal(isSignificant, extent.IsSignificant)
Dim expectedSpan As New SnapshotSpan(buffer.CurrentSnapshot, start, length)
Assert.Equal(expectedSpan, extent.Span)
End Using
End Function
End Class
End Namespace
|
HellBrick/roslyn
|
src/EditorFeatures/VisualBasicTest/TextStructureNavigation/TextStructureNavigatorTests.vb
|
Visual Basic
|
apache-2.0
| 9,272
|
Namespace API
''' <summary>
''' kintoneアカウント情報を格納するためのクラス。
''' コンストラクタが読み込むapp.configの設定に対して優先使用されます。
''' </summary>
''' <remarks></remarks>
Public Class kintoneAccount
''' <summary>
''' アプリケーションのドメイン
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Domain As String = ""
''' <summary>
''' Basic認証のためのID
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property AccessId As String = ""
''' <summary>
''' Basic認証のためのパスワード
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property AccessPassword As String = ""
''' <summary>
''' kintoneのログインを行うためのID
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property LoginId As String = ""
''' <summary>
''' kintoneのログインを行うためのパスワード
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property LoginPassword As String = ""
''' <summary>
''' kintoneのアプリごとに生成するAPIトークン。
''' 設定されている場合、ログインID/パスワードより優先される。
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ApiToken As String = ""
''' <summary>
''' Proxyを経由する場合のアドレス
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Proxy As String = ""
''' <summary>
''' 認証が必要なプロキシの場合のユーザー名
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ProxyUser As String = ""
''' <summary>
''' 認証が必要なプロキシの場合のパスワード
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property ProxyPassword As String = ""
''' <summary>
''' kintoneアカウント情報を格納するためのクラス。
''' コンストラクタが読み込むapp.configの設定に対して優先使用されます。
''' </summary>
''' <param name="domain">アプリケーションのドメイン</param>
''' <param name="accessId">Basic認証のためのID</param>
''' <param name="accessPassword">Basic認証のためのパスワード</param>
''' <param name="loginId">kintoneのログインを行うためのID</param>
''' <param name="loginPassword">kintoneのログインを行うためのパスワード</param>
''' <param name="apiToken">kintoneのアプリごとに生成するAPIトークン。
''' 設定されている場合、ログインID/パスワードより優先される。</param>
''' <param name="proxy">Proxyを経由する場合のアドレス</param>
''' <param name="proxyUser">認証が必要なプロキシの場合のユーザー名</param>
''' <param name="proxyPassword">認証が必要なプロキシの場合のパスワード</param>
''' <remarks></remarks>
Public Sub New(Optional ByVal domain As String = "",
Optional ByVal accessId As String = "",
Optional ByVal accessPassword As String = "",
Optional ByVal loginId As String = "",
Optional ByVal loginPassword As String = "",
Optional ByVal apiToken As String = "",
Optional ByVal proxy As String = "",
Optional ByVal proxyUser As String = "",
Optional ByVal proxyPassword As String = "")
For Each config As String In ConfigurationManager.AppSettings.AllKeys
Dim value As String = ConfigurationManager.AppSettings(config)
Select Case config
Case "ktDomain"
_Domain = If(Not String.IsNullOrEmpty(domain), domain, value)
Case "ktAccessId"
_AccessId = If(Not String.IsNullOrEmpty(accessId), accessId, value)
Case "ktAccessPassword"
_AccessPassword = If(Not String.IsNullOrEmpty(accessPassword), accessPassword, value)
Case "ktLoginId"
_LoginId = If(Not String.IsNullOrEmpty(loginId), loginId, value)
Case "ktLoginPassword"
_LoginPassword = If(Not String.IsNullOrEmpty(loginPassword), loginPassword, value)
Case "ktApiToken"
_ApiToken = If(Not String.IsNullOrEmpty(apiToken), apiToken, value)
Case "proxy"
_Proxy = If(Not String.IsNullOrEmpty(proxy), proxy, value)
Case "proxyUser"
_ProxyUser = If(Not String.IsNullOrEmpty(proxyUser), proxyUser, value)
Case "proxyPassword"
_ProxyPassword = If(Not String.IsNullOrEmpty(proxyPassword), proxyPassword, value)
End Select
Next
End Sub
End Class
End Namespace
|
icoxfog417/kintoneDotNET
|
kintoneDotNET/kintoneAccount.vb
|
Visual Basic
|
apache-2.0
| 5,854
|
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'
' Importando librerias
'-------------------------------------------------------------------------------------------'
Imports System.Data
'-------------------------------------------------------------------------------------------'
' Inicio de clase "rTablas"
'-------------------------------------------------------------------------------------------'
Partial Class rTablas
Inherits vis2Formularios.frmReporte
Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
Dim loComandoSeleccionar As New StringBuilder()
'Creando Tabla Temporal
loComandoSeleccionar.AppendLine(" CREATE TABLE #tblRESULTADOS")
loComandoSeleccionar.AppendLine(" (")
loComandoSeleccionar.AppendLine(" [name] nvarchar(100),")
loComandoSeleccionar.AppendLine(" [rows] int,")
loComandoSeleccionar.AppendLine(" [reserved] varchar(50),")
loComandoSeleccionar.AppendLine(" [data] varchar(50),")
loComandoSeleccionar.AppendLine(" [index_size] varchar(50),")
loComandoSeleccionar.AppendLine(" [unused] varchar(50),")
loComandoSeleccionar.AppendLine(" )")
'Llenando la Tabbla Temporal
loComandoSeleccionar.AppendLine(" EXEC sp_MSforeachtable @command1=")
loComandoSeleccionar.AppendLine(" 'INSERT INTO #tblRESULTADOS")
loComandoSeleccionar.AppendLine(" ([name],[rows],[reserved],[data],[index_size],[unused])")
loComandoSeleccionar.AppendLine(" EXEC sp_spaceused ''?'''")
loComandoSeleccionar.AppendLine(" SELECT")
loComandoSeleccionar.AppendLine(" name AS Tabla,")
loComandoSeleccionar.AppendLine(" rows As Filas,")
loComandoSeleccionar.AppendLine(" CAST(left(reserved, LEN(reserved)-3) AS INT) AS Espacio_Reservado,")
loComandoSeleccionar.AppendLine(" CAST(left(data, LEN(data)-3) AS INT) AS Espacio_Usado_Dato,")
loComandoSeleccionar.AppendLine(" CAST(left(index_size, LEN(index_size)-3) AS INT) AS Espacio_Usado_Indice,")
loComandoSeleccionar.AppendLine(" CAST(left(unused, LEN(unused)-3) AS INT) AS Espacio_No_Utilizado")
loComandoSeleccionar.AppendLine(" FROM #tblRESULTADOS")
loComandoSeleccionar.AppendLine(" WHERE ")
loComandoSeleccionar.AppendLine(" name BETWEEN " & lcParametro0Desde)
loComandoSeleccionar.AppendLine(" AND " & lcParametro0Hasta)
loComandoSeleccionar.AppendLine(" ORDER BY " & lcOrdenamiento)
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("rTablas", laDatosReporte)
Me.mTraducirReporte(loObjetoReporte)
Me.mFormatearCamposReporte(loObjetoReporte)
Me.crvrTablas.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: 19/08/09: Programacion inicial
'-------------------------------------------------------------------------------------------'
' MAT: 09/08/11: Ajuste de la vista de diseño
'-------------------------------------------------------------------------------------------'
|
kodeitsolutions/ef-reports
|
rTablas.aspx.vb
|
Visual Basic
|
mit
| 5,680
|
Imports TextAdventures.Utility
Public Class Main
Private m_currentFile As String
Private m_playingEditorGame As Boolean = False
Private m_cmdLineLaunch As String = Nothing
Private m_fromEditor As Boolean
Private m_editorSimpleMode As Boolean
Public Sub New()
' This call is required by the Windows Form Designer.
InitializeComponent()
AddHandler System.Windows.Threading.Dispatcher.CurrentDispatcher.UnhandledException, AddressOf CurrentDispatcher_UnhandledException
' Add any initialization after the InitializeComponent() call.
ctlLauncher.QuestVersion = My.Application.Info.Version
ctlLauncher.MaxASLVersion = Constants.MaxASLVersion
ctlLauncher.DownloadFolder = Options.Instance.GetStringValue(OptionNames.GamesFolder)
ctlLauncher.ShowSandpit = Options.Instance.GetBooleanValue(OptionNames.ShowSandpit)
ctlLauncher.ShowAdult = Options.Instance.GetBooleanValue(OptionNames.ShowAdult)
ctlPlayer.Visible = False
InitialiseMenuHandlers()
Dim helper As New TextAdventures.Utility.WindowHelper(Me, "Quest", "Main")
Dim args As New List(Of String)(Environment.GetCommandLineArgs())
If args.Count > 1 Then
CmdLineLaunch(args(1))
End If
AddHandler Options.Instance.OptionChanged, AddressOf OptionsChanged
AddHandler ctlLauncher.BrowseForGame, AddressOf ctlLauncher_BrowseForGame
AddHandler ctlLauncher.BrowseForGameEdit, AddressOf ctlLauncher_BrowseForGameEdit
AddHandler ctlLauncher.CreateNewGame, AddressOf ctlLauncher_CreateNewGame
AddHandler ctlLauncher.EditGame, AddressOf ctlLauncher_EditGame
AddHandler ctlLauncher.LaunchGame, AddressOf ctlLauncher_LaunchGame
AddHandler ctlLauncher.Tutorial, AddressOf ctlLauncher_Tutorial
End Sub
Private Sub CurrentDispatcher_UnhandledException(sender As Object, e As System.Windows.Threading.DispatcherUnhandledExceptionEventArgs)
ErrorHandler.ShowError(e.Exception.ToString())
e.Handled = True
End Sub
Private Sub InitialiseMenuHandlers()
ctlMenu.AddMenuClickHandler("open", AddressOf Browse)
ctlMenu.AddMenuClickHandler("about", AddressOf AboutMenuClick)
ctlMenu.AddMenuClickHandler("exit", AddressOf ExitMenuClick)
ctlMenu.AddMenuClickHandler("openedit", AddressOf OpenEditMenuClick)
ctlMenu.AddMenuClickHandler("restart", AddressOf RestartMenuClick)
ctlMenu.AddMenuClickHandler("createnew", AddressOf CreateNewMenuClick)
ctlMenu.AddMenuClickHandler("viewhelp", AddressOf Help)
ctlMenu.AddMenuClickHandler("forums", AddressOf Forums)
ctlMenu.AddMenuClickHandler("logbug", AddressOf LogBug)
ctlMenu.AddMenuClickHandler("fullscreen", AddressOf GoFullScreen)
ctlMenu.AddMenuClickHandler("options", AddressOf ShowOptions)
End Sub
Private Sub ctlPlayer_AddToRecent(filename As String, name As String) Handles ctlPlayer.AddToRecent
ctlLauncher.AddToRecent(filename, name)
End Sub
Private Sub ctlPlayer_Quit() Handles ctlPlayer.Quit
If Not ctlPlayer.Visible Then Return
FullScreen = False
If m_playingEditorGame Then
ctlPlayer.Visible = False
ctlPlayer.ResetAfterGameFinished()
ctlMenu.Mode = Quest.Controls.Menu.MenuMode.Editor
ctlEditor.Visible = True
m_playingEditorGame = False
ctlEditor.SetWindowTitle()
ctlEditor.SetMenu(ctlMenu)
ctlEditor.Redisplay()
Else
ctlMenu.Mode = Quest.Controls.Menu.MenuMode.GameBrowser
ctlLauncher.RefreshLists()
ctlPlayer.Visible = False
ctlPlayer.ResetAfterGameFinished()
ctlLauncherHost.Visible = True
SetWindowTitle()
End If
End Sub
Private Sub ctlLauncher_BrowseForGame()
Browse()
End Sub
Private Sub ctlLauncher_BrowseForGameEdit()
BrowseEdit()
End Sub
Private Sub ctlLauncher_CreateNewGame()
CreateNewMenuClick()
End Sub
Private Sub ctlLauncher_EditGame(filename As String)
LaunchEdit(filename)
End Sub
Private Sub ctlLauncher_LaunchGame(filename As String)
Launch(filename)
End Sub
Private Sub ctlLauncher_Tutorial()
Tutorial()
End Sub
Private Sub Browse()
Dim startFolder As String = DirectCast(Registry.GetSetting("Quest", "Settings", "StartFolder", _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), String)
dlgOpenFile.InitialDirectory = startFolder
dlgOpenFile.Multiselect = False
dlgOpenFile.Filter = "Quest Games|*.quest;*.quest-save;*.aslx;*.asl;*.cas;*.qsg|All files|*.*"
dlgOpenFile.FileName = ""
dlgOpenFile.ShowDialog()
If dlgOpenFile.FileName.Length > 0 Then
Registry.SaveSetting("Quest", "Settings", "StartFolder", System.IO.Path.GetDirectoryName(dlgOpenFile.FileName))
Launch(dlgOpenFile.FileName)
End If
End Sub
Private Sub Launch(filename As String, Optional fromEditor As Boolean = False, Optional editorSimpleMode As Boolean = False)
Dim game As IASL
If System.IO.Path.GetExtension(filename) = ".aslx" Then fromEditor = True
m_fromEditor = fromEditor
m_editorSimpleMode = editorSimpleMode
Try
m_currentFile = filename
ctlPlayer.Reset()
game = GameLauncher.GetGame(filename, String.Empty)
If game Is Nothing Then
MsgBox("Unrecognised file type. This game cannot be loaded in Quest.", MsgBoxStyle.Critical)
Else
Me.SuspendLayout()
ctlMenu.Mode = Quest.Controls.Menu.MenuMode.Player
ctlLauncherHost.Visible = False
ctlEditor.Visible = False
ctlPlayer.Visible = True
ctlPlayer.SetMenu(ctlMenu)
Me.ResumeLayout()
Application.DoEvents()
ctlPlayer.UseGameColours = Options.Instance.GetBooleanValue(OptionNames.UseGameColours)
ctlPlayer.SetPlayerOverrideColours(
Options.Instance.GetColourValue(OptionNames.BackgroundColour),
Options.Instance.GetColourValue(OptionNames.ForegroundColour),
Options.Instance.GetColourValue(OptionNames.LinkColour))
ctlPlayer.UseGameFont = Options.Instance.GetBooleanValue(OptionNames.UseGameFont)
ctlPlayer.SetPlayerOverrideFont(
Options.Instance.GetStringValue(OptionNames.FontFamily),
Options.Instance.GetSingleValue(OptionNames.FontSize),
DirectCast(Options.Instance.GetIntValue(OptionNames.FontStyle), FontStyle))
ctlPlayer.PlaySounds = Options.Instance.GetBooleanValue(OptionNames.PlaySounds)
ctlPlayer.UseSAPI = Options.Instance.GetBooleanValue(OptionNames.UseSAPI)
ctlPlayer.Initialise(game, fromEditor, editorSimpleMode)
ctlPlayer.Focus()
End If
Catch ex As Exception
MsgBox("Error launching game: " & ex.Message)
End Try
End Sub
Private Sub LaunchEdit(filename As String)
Dim ext As String
Try
Me.Cursor = Cursors.WaitCursor
ext = System.IO.Path.GetExtension(filename)
Select Case ext
Case ".aslx"
Me.SuspendLayout()
ctlMenu.Mode = Quest.Controls.Menu.MenuMode.Editor
ctlLauncherHost.Visible = False
ctlPlayer.Visible = False
ctlEditor.Visible = True
ctlEditor.SetMenu(ctlMenu)
Me.ResumeLayout()
Application.DoEvents()
ctlEditor.Initialise(filename)
ctlEditor.Focus()
Case Else
MsgBox(String.Format("Unrecognised file type '{0}'", ext))
End Select
Catch ex As Exception
MsgBox("Error loading game: " + Environment.NewLine + Environment.NewLine + ex.Message, MsgBoxStyle.Critical)
Me.Cursor = Cursors.Default
End Try
End Sub
Private Sub ctlEditor_InitialiseFinished(success As Boolean) Handles ctlEditor.InitialiseFinished
Me.Cursor = Cursors.Default
ctlMenu.Visible = True
If Not success Then
CloseEditor()
End If
End Sub
Private Sub AboutMenuClick()
Dim frmAbout As New About
frmAbout.ShowDialog()
End Sub
Private Sub ctlPlayer_GameNameSet(name As String) Handles ctlPlayer.GameNameSet
SetWindowTitle(name)
End Sub
Private Sub SetWindowTitle(Optional gameName As String = "")
Dim caption As String
caption = "Quest"
If Not String.IsNullOrEmpty(gameName) Then caption += " - " + gameName
Me.Text = caption
End Sub
Private Sub ExitMenuClick()
Me.Close()
End Sub
Private Sub RestartMenuClick()
Launch(m_currentFile, m_fromEditor, m_editorSimpleMode)
End Sub
Private Sub OpenEditMenuClick()
If Not ctlEditor.CheckGameIsSaved("Do you wish to save your changes before opening a new game?") Then Return
BrowseEdit()
End Sub
Private Sub CreateNewMenuClick()
If Not ctlEditor.CheckGameIsSaved("Do you wish to save your changes before creating a new game?") Then Return
Dim newFile = ctlEditor.CreateNewGame()
If String.IsNullOrEmpty(newFile) Then Return
LaunchEdit(newFile)
End Sub
Private Sub BrowseEdit()
Dim startFolder As String = DirectCast(Registry.GetSetting("Quest", "Settings", "StartFolder", _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)), String)
dlgOpenFile.InitialDirectory = startFolder
dlgOpenFile.Multiselect = False
dlgOpenFile.Filter = "Quest Games (*.aslx)|*.aslx|All files|*.*"
dlgOpenFile.FileName = ""
dlgOpenFile.ShowDialog()
If dlgOpenFile.FileName.Length > 0 Then
Registry.SaveSetting("Quest", "Settings", "StartFolder", System.IO.Path.GetDirectoryName(dlgOpenFile.FileName))
LaunchEdit(dlgOpenFile.FileName)
End If
End Sub
Private Sub ctlEditor_AddToRecent(filename As String, name As String) Handles ctlEditor.AddToRecent
ctlLauncher.AddToEditorRecent(filename, name)
End Sub
Private Sub Main_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
ctlPlayer.WindowClosing()
If Not ctlEditor.CloseEditor(False, True) Then
e.Cancel = True
ElseIf Not ctlLauncher.CloseLauncher() Then
e.Cancel = True
End If
End Sub
Private Sub Main_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
'If e.KeyCode = Keys.F11 Then
' Dim frmError As New ErrorHandler
' frmError.ErrorText = "Test error"
' frmError.ShowDialog()
'End If
If e.KeyCode = Keys.Escape AndAlso FullScreen Then
FullScreen = False
End If
If e.KeyCode = Keys.Enter Then
ctlPlayer.KeyPressed()
End If
If e.KeyCode = Keys.Escape Then
ctlPlayer.EscPressed()
End If
End Sub
Private Sub Main_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
e.Handled = ctlPlayer.KeyPressed()
End Sub
Private Sub ctlEditor_Close() Handles ctlEditor.Close
CloseEditor()
End Sub
Private Sub CloseEditor()
ctlMenu.Mode = Quest.Controls.Menu.MenuMode.GameBrowser
ctlLauncher.RefreshLists()
ctlEditor.Visible = False
ctlEditor.CancelUnsavedChanges()
ctlLauncherHost.Visible = True
SetWindowTitle()
End Sub
Private Sub ctlEditor_Loaded(name As String) Handles ctlEditor.Loaded
SetWindowTitle(name)
End Sub
Private Sub ctlEditor_NewGame() Handles ctlEditor.NewGame
CreateNewMenuClick()
End Sub
Private Sub ctlEditor_OpenGame() Handles ctlEditor.OpenGame
OpenEditMenuClick()
End Sub
Private Sub ctlEditor_Play(filename As String) Handles ctlEditor.Play
m_playingEditorGame = True
Launch(filename, True, ctlEditor.SimpleMode)
End Sub
Private Sub ctlEditor_PlayWalkthrough(filename As String, walkthrough As String, record As Boolean) Handles ctlEditor.PlayWalkthrough
m_playingEditorGame = True
ctlPlayer.PreLaunchAction = Sub() ctlPlayer.InitWalkthrough(walkthrough)
ctlPlayer.PostLaunchAction = Sub() ctlPlayer.StartWalkthrough()
If record Then
ctlPlayer.RecordWalkthrough = walkthrough
End If
Launch(filename, True, ctlEditor.SimpleMode)
End Sub
Private Sub Main_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
ctlLauncher.MainWindowShown()
If m_cmdLineLaunch IsNot Nothing Then
If (System.IO.Path.GetExtension(m_cmdLineLaunch) = ".aslx") Then
LaunchEdit(m_cmdLineLaunch)
Else
Launch(m_cmdLineLaunch)
End If
End If
End Sub
Private Sub ctlPlayer_ShortcutKeyPressed(keys As System.Windows.Forms.Keys) Handles ctlPlayer.ShortcutKeyPressed
ctlMenu.ShortcutKeyPressed(keys)
End Sub
Private Sub CmdLineLaunch(filename As String)
ctlLauncherHost.Visible = False
m_cmdLineLaunch = filename
End Sub
Private Sub LogBug()
LaunchURL("https://github.com/textadventures/quest/issues")
End Sub
Private Sub Forums()
LaunchURL("http://forum.textadventures.co.uk/")
End Sub
Private Sub Help()
LaunchURL("http://docs.textadventures.co.uk/quest/")
End Sub
Private Sub Tutorial()
LaunchURL("http://docs.textadventures.co.uk/quest/tutorial/")
End Sub
Private Sub LaunchURL(url As String)
Try
System.Diagnostics.Process.Start(url)
Catch ex As Exception
MsgBox(String.Format("Error launching {0}{1}{2}", url, Environment.NewLine + Environment.NewLine, ex.Message), MsgBoxStyle.Critical, "Quest")
End Try
End Sub
Private Sub GoFullScreen()
FullScreen = True
ctlPlayer.ShowExitFullScreenButton()
End Sub
Private m_fullScreen As Boolean
Public Property FullScreen As Boolean
Get
Return m_fullScreen
End Get
Set(value As Boolean)
If m_fullScreen <> value Then
m_fullScreen = value
Me.FormBorderStyle = If(m_fullScreen, Windows.Forms.FormBorderStyle.None, Windows.Forms.FormBorderStyle.Sizable)
Me.WindowState = If(m_fullScreen, FormWindowState.Maximized, FormWindowState.Normal)
ctlMenu.Visible = Not m_fullScreen
End If
End Set
End Property
Private Sub ctlPlayer_ExitFullScreen() Handles ctlPlayer.ExitFullScreen
BeginInvoke(Sub() FullScreen = False)
End Sub
Private Sub ctlPlayer_RecordedWalkthrough(name As String, steps As System.Collections.Generic.List(Of String)) Handles ctlPlayer.RecordedWalkthrough
ctlEditor.SetRecordedWalkthrough(name, steps)
End Sub
Private Sub ShowOptions()
Dim optionsForm As New OptionsDialog
optionsForm.ShowDialog()
End Sub
Private Sub OptionsChanged(optionName As OptionNames)
Select Case optionName
Case OptionNames.BackgroundColour, OptionNames.ForegroundColour, OptionNames.LinkColour
ctlPlayer.SetPlayerOverrideColours(
Options.Instance.GetColourValue(OptionNames.BackgroundColour),
Options.Instance.GetColourValue(OptionNames.ForegroundColour),
Options.Instance.GetColourValue(OptionNames.LinkColour))
Case OptionNames.UseGameColours
ctlPlayer.UseGameColours = Options.Instance.GetBooleanValue(OptionNames.UseGameColours)
Case OptionNames.FontFamily, OptionNames.FontSize, OptionNames.FontStyle
ctlPlayer.SetPlayerOverrideFont(
Options.Instance.GetStringValue(OptionNames.FontFamily),
Options.Instance.GetSingleValue(OptionNames.FontSize),
DirectCast(Options.Instance.GetIntValue(OptionNames.FontStyle), FontStyle))
Case OptionNames.UseGameFont
ctlPlayer.UseGameFont = Options.Instance.GetBooleanValue(OptionNames.UseGameFont)
Case OptionNames.GamesFolder
ctlLauncher.DownloadFolder = Options.Instance.GetStringValue(OptionNames.GamesFolder)
Case OptionNames.ShowSandpit
ctlLauncher.ShowSandpit = Options.Instance.GetBooleanValue(OptionNames.ShowSandpit)
Case OptionNames.ShowAdult
ctlLauncher.ShowAdult = Options.Instance.GetBooleanValue(OptionNames.ShowAdult)
Case OptionNames.PlaySounds
ctlPlayer.PlaySounds = Options.Instance.GetBooleanValue(OptionNames.PlaySounds)
Case OptionNames.UseSAPI
ctlPlayer.UseSAPI = Options.Instance.GetBooleanValue(OptionNames.UseSAPI)
End Select
End Sub
End Class
|
siege918/quest
|
Quest/Main.vb
|
Visual Basic
|
mit
| 18,053
|
' 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_89
''' <summary>
''' Indicates whether the specified object is a high surrogate.
''' </summary>
''' <param name="c">The Unicode character to evaluate.</param>
''' <returns>
''' true if the numeric value of the parameter ranges from U+D800 through U+DBFF; otherwise, false.
''' </returns>
<System.Runtime.CompilerServices.Extension> _
Public Function IsHighSurrogate(c As [Char]) As [Boolean]
Return [Char].IsHighSurrogate(c)
End Function
End Module
|
zzzprojects/Z.ExtensionMethods
|
src (VB.NET)/Z.ExtensionMethods.VB/Z.Core/System.Char/System.Char/Char.IsHighSurrogate.vb
|
Visual Basic
|
mit
| 880
|
' 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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.RemoveUnusedVariable
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.RemoveUnusedVariableTest
Partial Public Class RemoveUnusedVariableTest
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (Nothing,
New RemoveUnusedVariableCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)>
Public Async Function RemoveUnusedVariable() As Task
Dim markup =
<File>
Module M
Sub Main()
Dim [|x as String|]
End Sub
End Module
</File>
Dim expected =
<File>
Module M
Sub Main()
End Sub
End Module
</File>
Await TestAsync(markup, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)>
Public Async Function RemoveUnusedVariable1() As Task
Dim markup =
<File>
Module M
Sub Main()
Dim [|x|], c as String
End Sub
End Module
</File>
Dim expected =
<File>
Module M
Sub Main()
Dim c as String
End Sub
End Module
</File>
Await TestAsync(markup, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnusedVariable)>
Public Async Function RemoveUnusedVariableFixAll() As Task
Dim markup =
<File>
Module M
Sub Main()
Dim x, c as String
Dim {|FixAllInDocument:a as String|}
End Sub
End Module
</File>
Dim expected =
<File>
Module M
Sub Main()
End Sub
End Module
</File>
Await TestAsync(markup, expected)
End Function
End Class
End Namespace
|
weltkante/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/RemoveUnusedVariable/RemoveUnusedVariableTest.vb
|
Visual Basic
|
apache-2.0
| 2,165
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.UnitTests
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.Composition
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Preview
Imports Microsoft.VisualStudio.Text.Editor
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Preview
Public Class PreviewChangesTests
Private _exportProvider As ExportProvider = MinimalTestExportProvider.CreateExportProvider(
TestExportProvider.MinimumCatalogWithCSharpAndVisualBasic.WithPart(GetType(StubVsEditorAdaptersFactoryService)))
<WpfFact>
Public Async Function TestListStructure() As Task
Using workspace = Await TestWorkspace.CreateCSharpAsync(<text>
Class C
{
void Foo()
{
$$
}
}</text>.Value, exportProvider:=_exportProvider)
Dim expectedItems = New List(Of Tuple(Of String, Integer)) From
{
Tuple.Create("topLevelItemName", 0),
Tuple.Create("test1.cs", 1),
Tuple.Create("insertion!", 2)
}
Dim documentId = workspace.Documents.First().Id
Dim document = workspace.CurrentSolution.GetDocument(documentId)
Dim text = document.GetTextAsync().Result
Dim textChange = New TextChange(New TextSpan(workspace.Documents.First().CursorPosition.Value, 0), "insertion!")
Dim forkedDocument = document.WithText(text.WithChanges(textChange))
Dim componentModel = New MockComponentModel(workspace.ExportProvider)
Dim previewEngine = New PreviewEngine(
"Title", "helpString", "description", "topLevelItemName", CodeAnalysis.Glyph.Assembly,
forkedDocument.Project.Solution,
workspace.CurrentSolution,
componentModel)
Dim outChangeList As Object = Nothing
previewEngine.GetRootChangesList(outChangeList)
Dim topLevelList = DirectCast(outChangeList, ChangeList)
AssertTreeStructure(expectedItems, topLevelList)
End Using
End Function
<WpfFact, WorkItem(1036455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036455")>
Public Async Function TestListStructure_AddedDeletedDocuments() As Task
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document FilePath="test1.cs">
Class C
{
void Foo()
{
$$
}
}
</Document>
<Document FilePath="test2.cs">// This file will be deleted!</Document>
</Project>
</Workspace>
Using workspace = Await TestWorkspace.CreateAsync(workspaceXml, exportProvider:=_exportProvider)
Dim expectedItems = New List(Of Tuple(Of String, Integer)) From
{
Tuple.Create("topLevelItemName", 0),
Tuple.Create("test1.cs", 1),
Tuple.Create("insertion!", 2),
Tuple.Create(ServicesVSResources.PreviewChangesAddedPrefix + "test3.cs", 1),
Tuple.Create("// This file will be added!", 2),
Tuple.Create(ServicesVSResources.PreviewChangesDeletedPrefix + "test2.cs", 1),
Tuple.Create("// This file will be deleted!", 2)
}
Dim docId = workspace.Documents.First().Id
Dim document = workspace.CurrentSolution.GetDocument(docId)
Dim text = document.GetTextAsync().Result
Dim textChange = New TextChange(New TextSpan(workspace.Documents.First().CursorPosition.Value, 0), "insertion!")
Dim forkedDocument = document.WithText(text.WithChanges(textChange))
Dim newSolution = forkedDocument.Project.Solution
Dim removedDocumentId = workspace.Documents.Last().Id
newSolution = newSolution.RemoveDocument(removedDocumentId)
Dim addedDocumentId = DocumentId.CreateNewId(docId.ProjectId)
newSolution = newSolution.AddDocument(addedDocumentId, "test3.cs", "// This file will be added!")
Dim componentModel = New MockComponentModel(workspace.ExportProvider)
Dim previewEngine = New PreviewEngine(
"Title", "helpString", "description", "topLevelItemName", CodeAnalysis.Glyph.Assembly,
newSolution,
workspace.CurrentSolution,
componentModel)
Dim outChangeList As Object = Nothing
previewEngine.GetRootChangesList(outChangeList)
Dim topLevelList = DirectCast(outChangeList, ChangeList)
AssertTreeStructure(expectedItems, topLevelList)
End Using
End Function
<WpfFact>
Public Async Function TestCheckedItems() As Task
Using workspace = Await TestWorkspace.CreateCSharpAsync(<text>
Class C
{
void Foo()
{
$$
}
}</text>.Value, exportProvider:=_exportProvider)
Dim expectedItems = New List(Of String) From {"topLevelItemName", "*test1.cs", "**insertion!"}
Dim documentId = workspace.Documents.First().Id
Dim document = workspace.CurrentSolution.GetDocument(documentId)
Dim text = document.GetTextAsync().Result
Dim textChange = New TextChange(New TextSpan(workspace.Documents.First().CursorPosition.Value, 0), "insertion!")
Dim forkedDocument = document.WithText(text.WithChanges(textChange))
Dim componentModel = New MockComponentModel(workspace.ExportProvider)
Dim previewEngine = New PreviewEngine(
"Title", "helpString", "description", "topLevelItemName", CodeAnalysis.Glyph.Assembly,
forkedDocument.Project.Solution,
workspace.CurrentSolution,
componentModel)
WpfTestCase.RequireWpfFact("Test explicitly creates an IWpfTextView")
Dim textEditorFactory = componentModel.GetService(Of ITextEditorFactoryService)
Using disposableView As DisposableTextView = textEditorFactory.CreateDisposableTextView()
previewEngine.SetTextView(disposableView.TextView)
Dim outChangeList As Object = Nothing
previewEngine.GetRootChangesList(outChangeList)
Dim topLevelList = DirectCast(outChangeList, ChangeList)
SetCheckedChildren(New List(Of String)(), topLevelList)
previewEngine.ApplyChanges()
Dim finalText = previewEngine.FinalSolution.GetDocument(documentId).GetTextAsync().Result.ToString()
Assert.Equal(document.GetTextAsync().Result.ToString(), finalText)
End Using
End Using
End Function
<WpfFact, WorkItem(1036455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036455")>
Public Async Function TestCheckedItems_AddedDeletedDocuments() As Task
Dim workspaceXml =
<Workspace>
<Project Language=<%= LanguageNames.CSharp %> CommonReferences="true">
<Document FilePath="test1.cs">
Class C
{
void Foo()
{
$$
}
}
</Document>
<Document FilePath="test2.cs">// This file will be deleted!</Document>
<Document FilePath="test3.cs">// This file will just escape deletion!</Document>
</Project>
</Workspace>
Using workspace = Await TestWorkspace.CreateAsync(workspaceXml, exportProvider:=_exportProvider)
Dim docId = workspace.Documents.First().Id
Dim document = workspace.CurrentSolution.GetDocument(docId)
Dim text = document.GetTextAsync().Result
Dim textChange = New TextChange(New TextSpan(workspace.Documents.First().CursorPosition.Value, 0), "insertion!")
Dim forkedDocument = document.WithText(text.WithChanges(textChange))
Dim newSolution = forkedDocument.Project.Solution
Dim componentModel = New MockComponentModel(workspace.ExportProvider)
Dim removedDocumentId1 = workspace.Documents.ElementAt(1).Id
Dim removedDocumentId2 = workspace.Documents.ElementAt(2).Id
newSolution = newSolution.RemoveDocument(removedDocumentId1)
newSolution = newSolution.RemoveDocument(removedDocumentId2)
Dim addedDocumentId1 = DocumentId.CreateNewId(docId.ProjectId)
Dim addedDocumentId2 = DocumentId.CreateNewId(docId.ProjectId)
Dim addedDocumentText = "// This file will be added!"
newSolution = newSolution.AddDocument(addedDocumentId1, "test4.cs", addedDocumentText)
newSolution = newSolution.AddDocument(addedDocumentId2, "test5.cs", "// This file will be unchecked and not added!")
Dim previewEngine = New PreviewEngine(
"Title", "helpString", "description", "topLevelItemName", CodeAnalysis.Glyph.Assembly,
newSolution,
workspace.CurrentSolution,
componentModel)
WpfTestCase.RequireWpfFact("Test explicitly creates an IWpfTextView")
Dim textEditorFactory = componentModel.GetService(Of ITextEditorFactoryService)
Using disposableView As DisposableTextView = textEditorFactory.CreateDisposableTextView()
previewEngine.SetTextView(disposableView.TextView)
Dim outChangeList As Object = Nothing
previewEngine.GetRootChangesList(outChangeList)
Dim topLevelList = DirectCast(outChangeList, ChangeList)
Dim checkedItems = New List(Of String) From
{
"test1.cs",
ServicesVSResources.PreviewChangesAddedPrefix + "test4.cs",
ServicesVSResources.PreviewChangesDeletedPrefix + "test2.cs"
}
SetCheckedChildren(checkedItems, topLevelList)
previewEngine.ApplyChanges()
Dim finalSolution = previewEngine.FinalSolution
Dim finalDocuments = finalSolution.Projects.First().Documents
Assert.Equal(3, finalDocuments.Count)
Dim changedDocText = finalSolution.GetDocument(docId).GetTextAsync().Result.ToString()
Assert.Equal(forkedDocument.GetTextAsync().Result.ToString(), changedDocText)
Dim finalAddedDocText = finalSolution.GetDocument(addedDocumentId1).GetTextAsync().Result.ToString()
Assert.Equal(addedDocumentText, finalAddedDocText)
Dim finalNotRemovedDocText = finalSolution.GetDocument(removedDocumentId2).GetTextAsync().Result.ToString()
Assert.Equal("// This file will just escape deletion!", finalNotRemovedDocText)
End Using
End Using
End Function
<WpfFact>
Public Async Function TestLinkedFileChangesMergedAndDeduplicated() As Task
Dim workspaceXml = <Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj1">
<Document FilePath="C.vb"><![CDATA[
Class C
Sub M()
End Sub
Sub X()
End Sub()
End Class
]]>
</Document>
</Project>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj2">
<Document IsLinkFile="true" LinkAssemblyName="VBProj1" LinkFilePath="C.vb"/>
</Project>
</Workspace>
Using workspace = Await TestWorkspace.CreateAsync(workspaceXml, , exportProvider:=_exportProvider)
Dim documentId1 = workspace.Documents.Where(Function(d) d.Project.Name = "VBProj1").Single().Id
Dim document1 = workspace.CurrentSolution.GetDocument(documentId1)
Dim documentId2 = workspace.Documents.Where(Function(d) d.Project.Name = "VBProj2").Single().Id
Dim document2 = workspace.CurrentSolution.GetDocument(documentId2)
Dim text1 = document1.GetTextAsync().Result
Dim textChange1 = New TextChange(New TextSpan(19, 1), "N")
Dim text2 = document2.GetTextAsync().Result
Dim textChange2 = New TextChange(New TextSpan(47, 1), "Y")
Dim updatedSolution = document1.Project.Solution _
.WithDocumentText(documentId1, text1.WithChanges(textChange1)) _
.WithDocumentText(documentId2, text2.WithChanges(textChange2))
Dim componentModel = New MockComponentModel(workspace.ExportProvider)
Dim previewEngine = New PreviewEngine(
"Title", "helpString", "description", "topLevelItemName", CodeAnalysis.Glyph.Assembly,
updatedSolution,
workspace.CurrentSolution,
componentModel)
Dim outChangeList As Object = Nothing
previewEngine.GetRootChangesList(outChangeList)
Dim topLevelList = DirectCast(outChangeList, ChangeList)
Dim expectedItems = New List(Of Tuple(Of String, Integer)) From
{
Tuple.Create("topLevelItemName", 0),
Tuple.Create("C.vb", 1),
Tuple.Create("Sub N()", 2),
Tuple.Create("Sub Y()", 2)
}
AssertTreeStructure(expectedItems, topLevelList)
End Using
End Function
Private Sub AssertTreeStructure(expectedItems As List(Of Tuple(Of String, Integer)), topLevelList As ChangeList)
Dim outChangeList As Object = Nothing
Dim outCanRecurse As Integer = Nothing
Dim outTreeList As Shell.Interop.IVsLiteTreeList = Nothing
Dim flatteningResult = New List(Of Tuple(Of String, Integer))()
FlattenTree(topLevelList, flatteningResult, 0)
Assert.Equal(expectedItems.Count, flatteningResult.Count)
For x As Integer = 0 To flatteningResult.Count - 1
Assert.Equal(flatteningResult(x), expectedItems(x))
Next
End Sub
Private Sub FlattenTree(list As ChangeList, result As List(Of Tuple(Of String, Integer)), depth As Integer)
For Each change In list.Changes
Dim text As String = Nothing
change.GetText(Nothing, text)
result.Add(Tuple.Create(text, depth))
If change.Children.Changes.Any Then
FlattenTree(change.Children, result, depth + 1)
End If
Next
End Sub
' Check each of the most-nested children whose names appear in checkItems.
' Uncheck the rest
Private Sub SetCheckedChildren(checkedItems As List(Of String), topLevelList As ChangeList)
For Each change In topLevelList.Changes
Dim text As String = Nothing
change.GetText(Nothing, text)
Dim isChecked = change.CheckState = Shell.Interop.__PREVIEWCHANGESITEMCHECKSTATE.PCCS_Checked
If checkedItems.Contains(text) Then
If Not isChecked Then
change.Toggle()
End If
Continue For
ElseIf isChecked Then
change.Toggle()
End If
If change.Children.Changes.Any() Then
SetCheckedChildren(checkedItems, change.Children)
End If
Next
End Sub
Private Sub AssertChildCount(list As ChangeList, count As UInteger)
Dim actualCount As UInteger = Nothing
list.GetItemCount(actualCount)
Assert.Equal(count, actualCount)
End Sub
Private Sub AssertChildText(list As ChangeList, index As UInteger, text As String)
Dim actualText As String = Nothing
list.GetText(index, Nothing, actualText)
Assert.Equal(text, actualText)
End Sub
Private Sub AssertSomeChild(list As ChangeList, text As String)
Dim count As UInteger = Nothing
list.GetItemCount(count)
For i As UInteger = 0 To count
Dim actualText As String = Nothing
list.GetText(i, Nothing, actualText)
If actualText = text Then
Return
End If
Next
Assert.True(False, "Didn't find child with name '" + text + "'")
End Sub
End Class
End Namespace
|
ericfe-ms/roslyn
|
src/VisualStudio/Core/Test/Preview/PreviewChangesTests.vb
|
Visual Basic
|
apache-2.0
| 17,844
|
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Option Strict Off
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.GenerateConstructor
Imports Microsoft.CodeAnalysis.VisualBasic.Diagnostics
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.GenerateConstructor
Public Class GenerateConstructorTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(Nothing, New GenerateConstructorCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateIntoContainingType()
Test(
NewLines("Class C \n Sub Main() \n Dim f = New C([|4|], 5, 6) \n End Sub \n End Class"),
NewLines("Class C \n Private v1 As Integer \n Private v2 As Integer \n Private v3 As Integer \n Public Sub New(v1 As Integer, v2 As Integer, v3 As Integer) \n Me.v1 = v1 \n Me.v2 = v2 \n Me.v3 = v3 \n End Sub \n Sub Main() \n Dim f = New C(4, 5, 6) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestInvokingFromInsideAnotherConstructor()
Test(
NewLines("Class A \n Private v As B \n Public Sub New() \n Me.v = New B([|5|]) \n End Sub \n End Class \n Friend Class B \n End Class"),
NewLines("Class A \n Private v As B \n Public Sub New() \n Me.v = New B(5) \n End Sub \n End Class \n Friend Class B \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMissingGenerateDefaultConstructor()
TestMissing(
NewLines("Class Test \n Sub Main() \n Dim a = New [|A|]() \n End Sub \n End Class \n Class A \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMissingGenerateDefaultConstructorInStructure()
TestMissing(
NewLines("Class Test \n Sub Main() \n Dim a = New [|A|]() \n End Sub \n End Class \n Structure A \n End Structure"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOfferDefaultConstructorWhenOverloadExists()
Test(
NewLines("Class Test \n Sub Main() \n Dim a = [|New A()|] \n End Sub \n End Class \n Class A \n Sub New(x As Integer) \n End Sub \n End Class"),
NewLines("Class Test \n Sub Main() \n Dim a = New A() \n End Sub \n End Class \n Class A \n Public Sub New() \n End Sub \n Sub New(x As Integer) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestParameterizedConstructorOffered1()
Test(
NewLines("Class Test \n Sub Main() \n Dim a = New A([|1|]) \n End Sub \n End Class \n Class A \n End Class"),
NewLines("Class Test \n Sub Main() \n Dim a = New A(1) \n End Sub \n End Class \n Class A \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestParameterizedConstructorOffered2()
Test(
NewLines("Class Test \n Sub Main() \n Dim a = New A([|1|]) \n End Sub \n End Class \n Class A \n Public Sub New() \n End Sub \n End Class"),
NewLines("Class Test \n Sub Main() \n Dim a = New A(1) \n End Sub \n End Class \n Class A \n Private v As Integer \n Public Sub New() \n End Sub \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<WorkItem(527627), WorkItem(539735), WorkItem(539735)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestInAsNewExpression()
Test(
NewLines("Class Test \n Sub Main() \n Dim a As New A([|1|]) \n End Sub \n End Class \n Class A \n Public Sub New() \n End Sub \n End Class"),
NewLines("Class Test \n Sub Main() \n Dim a As New A(1) \n End Sub \n End Class \n Class A \n Private v As Integer \n Public Sub New() \n End Sub \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateInPartialClass1()
Test(
NewLines("Public Partial Class Test \n Public Sub S1() \n End Sub \n End Class \n Public Class Test \n Public Sub S2() \n End Sub \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test([|5|]) \n End Sub \n End Class"),
NewLines("Public Partial Class Test \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Public Sub S1() \n End Sub \n End Class \n Public Class Test \n Public Sub S2() \n End Sub \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test(5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateInPartialClassWhenArityDoesntMatch()
Test(
NewLines("Public Partial Class Test \n Public Sub S1() \n End Sub \n End Class \n Public Class Test(Of T) \n Public Sub S2() \n End Sub \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test([|5|]) \n End Sub \n End Class"),
NewLines("Public Partial Class Test \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Public Sub S1() \n End Sub \n End Class \n Public Class Test(Of T) \n Public Sub S2() \n End Sub \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test(5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateInPartialClassWithConflicts()
Test(
NewLines("Public Partial Class Test2 \n End Class \n Private Partial Class Test2 \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test2([|5|]) \n End Sub \n End Class"),
NewLines("Public Partial Class Test2 \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n Private Partial Class Test2 \n End Class \n Public Class A \n Sub Main() \n Dim s = New Test2(5) \n End Sub \n End Class"))
End Sub
<WorkItem(528257)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateIntoInaccessibleType()
TestMissing(
NewLines("Class Foo \n Private Class Bar \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Foo.Bar([|5|]) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnNestedTypes()
Test(
NewLines("Class Foo \n Class Bar \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Foo.Bar([|5|]) \n End Sub \n End Class"),
NewLines("Class Foo \n Class Bar \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Foo.Bar(5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnNestedPartialTypes()
Test(
NewLines("Public Partial Class Test \n Public Partial Class NestedTest \n Public Sub S1() \n End Sub \n End Class \n End Class \n Public Partial Class Test \n Public Partial Class NestedTest \n Public Sub S2() \n End Sub \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Test.NestedTest([|5|]) \n End Sub \n End Class"),
NewLines("Public Partial Class Test \n Public Partial Class NestedTest \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Public Sub S1() \n End Sub \n End Class \n End Class \n Public Partial Class Test \n Public Partial Class NestedTest \n Public Sub S2() \n End Sub \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Test.NestedTest(5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnNestedGenericType()
Test(
NewLines("Class Outer(Of T) \n Public Class Inner \n End Class \n Public i = New Inner([|5|]) \n End Class"),
NewLines("Class Outer(Of T) \n Public Class Inner \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n Public i = New Inner(5) \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnGenericTypes1()
Test(
NewLines("Class Base(Of T, V) \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)([|5|], 5) \n End Sub \n End Class"),
NewLines("Class Base(Of T, V) \n Private v1 As Integer \n Private v2 As Integer \n Public Sub New(v1 As Integer, v2 As Integer) \n Me.v1 = v1 \n Me.v2 = v2 \n End Sub \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)(5, 5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnGenericTypes2()
Test(
NewLines("Class Base(Of T, V) \n End Class \n Class Derived(Of V) \n Inherits Base(Of Integer, V) \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)(5, 5) \n Dim b = New Derived(Of Integer)([|5|]) \n End Sub \n End Class"),
NewLines("Class Base(Of T, V) \n End Class \n Class Derived(Of V) \n Inherits Base(Of Integer, V) \n Private v1 As Integer \n Public Sub New(v1 As Integer) \n Me.v1 = v1 \n End Sub \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)(5, 5) \n Dim b = New Derived(Of Integer)(5) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOnGenericTypes3()
Test(
NewLines("Class Base(Of T, V) \n End Class \n Class Derived(Of V) \n Inherits Base(Of Integer, V) \n End Class \n Class MoreDerived \n Inherits Derived(Of Double) \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)(5, 5) \n Dim b = New Derived(Of Integer)(5) \n Dim c = New MoreDerived([|5.5|]) \n End Sub \n End Class"),
NewLines("Class Base(Of T, V) \n End Class \n Class Derived(Of V) \n Inherits Base(Of Integer, V) \n End Class \n Class MoreDerived \n Inherits Derived(Of Double) \n Private v As Double \n Public Sub New(v As Double) \n Me.v = v \n End Sub \n End Class \n Class Test \n Sub Foo() \n Dim a = New Base(Of Integer, Integer)(5, 5) \n Dim b = New Derived(Of Integer)(5) \n Dim c = New MoreDerived(5.5) \n End Sub \n End Class"))
End Sub
<WorkItem(528244)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestDateTypeForInference()
Test(
NewLines("Class Foo \n End Class \n Class A \n Sub Main() \n Dim s = New Foo([|Date.Now|]) \n End Sub \n End Class"),
NewLines("Class Foo \n Private now As Date \n Public Sub New(now As Date) \n Me.now = now \n End Sub \n End Class \n Class A \n Sub Main() \n Dim s = New Foo(Date.Now) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestBaseConstructor()
Test(
NewLines("Class Base \n End Class \n Class Derived \n Inherits Base \n Private x As Integer \n Public Sub New(x As Integer) \n MyBase.New([|x|]) \n Me.x = x \n End Sub \n End Class"),
NewLines("Class Base \n Private x As Integer \n Public Sub New(x As Integer) \n Me.x = x \n End Sub \n End Class \n Class Derived \n Inherits Base \n Private x As Integer \n Public Sub New(x As Integer) \n MyBase.New(x) \n Me.x = x \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMustInheritBase()
Test(
NewLines("MustInherit Class Base \n End Class \n Class Derived \n Inherits Base \n Shared x As Integer \n Public Sub New(x As Integer) \n MyBase.New([|x|]) 'This should generate a protected ctor in Base \n Derived.x = x \n End Sub \n Sub Test1() \n Dim a As New Derived(1) \n End Sub \n End Class"),
NewLines("MustInherit Class Base \n Private x As Integer \n Public Sub New(x As Integer) \n Me.x = x \n End Sub \n End Class \n Class Derived \n Inherits Base \n Shared x As Integer \n Public Sub New(x As Integer) \n MyBase.New(x) 'This should generate a protected ctor in Base \n Derived.x = x \n End Sub \n Sub Test1() \n Dim a As New Derived(1) \n End Sub \n End Class"))
End Sub
<WorkItem(540586)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMissingOnNoCloseParen()
TestMissing(
NewLines("Imports System \n Imports System.Collections.Generic \n Imports System.Linq \n Module Program \n Sub Main(args As String()) \n Dim c = New [|foo|]( \n End Sub \n End Module \n Class foo \n End Class"))
End Sub
<WorkItem(540545)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestConversionError()
Test(
NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n Dim i As Char \n Dim cObject As C = New C([|i|]) \n Console.WriteLine(cObject.v1) \n End Sub \n End Module \n Class C \n Public v1 As Integer \n Public Sub New(v1 As Integer) \n Me.v1 = v1 \n End Sub \n End Class"),
NewLines("Imports System \n Module Program \n Sub Main(args As String()) \n Dim i As Char \n Dim cObject As C = New C(i) \n Console.WriteLine(cObject.v1) \n End Sub \n End Module \n Class C \n Public v1 As Integer \n Private i As Char \n Public Sub New(i As Char) \n Me.i = i \n End Sub Public Sub New(v1 As Integer) \n Me.v1 = v1 \n End Sub \n \n End Class"))
End Sub
<WorkItem(540642)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestNotOnNestedConstructor()
Test(
NewLines("Module Program \n Sub Main(args As String()) \n Dim x As C = New C([|New C()|]) \n End Sub \n End Module \n Friend Class C \n End Class"),
NewLines("Module Program \n Sub Main(args As String()) \n Dim x As C = New C(New C()) \n End Sub \n End Module \n Friend Class C \n Private c As C \n Public Sub New(c As C) \n Me.c = c \n End Sub \n End Class"))
End Sub
<WorkItem(540607)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestUnavailableTypeParameters()
Test(
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test = New Test([|x|], y) \n End Sub \n End Class \n Friend Class Test \n End Class"),
NewLines("Class C(Of T1, T2) \n Sub M(x As T1, y As T2) \n Dim a As Test = New Test(x, y) \n End Sub \n End Class \n Friend Class Test \n Private x As Object \n Private y As Object \n Public Sub New(x As Object, y As Object) \n Me.x = x \n Me.y = y \n End Sub \n End Class"))
End Sub
<WorkItem(540748)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestKeywordArgument1()
Test(
NewLines("Class Test \n Private [Class] As Integer = 5 \n Sub Main() \n Dim a = New A([|[Class]|]) \n End Sub \n End Class \n Class A \n End Class"),
NewLines("Class Test \n Private [Class] As Integer = 5 \n Sub Main() \n Dim a = New A([Class]) \n End Sub \n End Class \n Class A \n Private [class] As Integer \n Public Sub New([class] As Integer) \n Me.class = [class] \n End Sub \n End Class"))
End Sub
<WorkItem(540747)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestKeywordArgument2()
Test(
NewLines("Class Test \n Sub Main() \n Dim a = New A([|Class|]) \n End Sub \n End Class \n Class A \n End Class"),
NewLines("Class Test \n Sub Main() \n Dim a = New A(Class) \n End Sub \n End Class \n Class A \n Private p As Object \n Public Sub New(p As Object) \n Me.p = p \n End Sub \n End Class"))
End Sub
<WorkItem(540746)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestConflictWithTypeParameterName()
Test(
NewLines("Class Test \n Sub Foo() \n Dim a = New Bar(Of Integer)([|5|]) \n End Sub \n End Class \n Class Bar(Of V) \n End Class"),
NewLines("Class Test \n Sub Foo() \n Dim a = New Bar(Of Integer)(5) \n End Sub \n End Class \n Class Bar(Of V) \n Private v1 As Integer \n Public Sub New(v1 As Integer) \n Me.v1 = v1 \n End Sub \n End Class"))
End Sub
<WorkItem(541174)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingReadonlyField()
Test(
NewLines("Class C \n ReadOnly x As Integer \n Sub Test() \n Dim x As Integer = 1 \n Dim obj As New C([|x|]) \n End Sub \n End Class"),
NewLines("Class C \n ReadOnly x As Integer \n Public Sub New(x As Integer) \n Me.x = x \n End Sub \n Sub Test() \n Dim x As Integer = 1 \n Dim obj As New C(x) \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingProperty()
Test(
NewLines("Class Program \n Sub Test() \n Dim x = New A([|P|]:=5) \n End Sub \n End Class \n Class A \n Public Property P As Integer \n End Class"),
NewLines("Class Program \n Sub Test() \n Dim x = New A(P:=5) \n End Sub \n End Class \n Class A \n Public Sub New(P As Integer) \n Me.P = P \n End Sub \n Public Property P As Integer \n End Class"))
End Sub
<WorkItem(542055)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingMethod()
Test(
NewLines("Class A \n Sub Test() \n Dim t As New C([|u|]:=5) \n End Sub \n End Class \n Class C \n Public Sub u() \n End Sub \n End Class"),
NewLines("Class A \n Sub Test() \n Dim t As New C(u:=5) \n End Sub \n End Class \n Class C \n Private u1 As Integer \n Public Sub New(u As Integer) \n Me.u1 = u \n End Sub \n Public Sub u() \n End Sub \n End Class"))
End Sub
<WorkItem(542055)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestDetectAssignmentToSharedFieldFromInstanceConstructor()
Test(
NewLines("Class Program \n Sub Test() \n Dim x = New A([|P|]:=5) \n End Sub \n End Class \n Class A \n Shared Property P As Integer \n End Class"),
NewLines("Class Program \n Sub Test() \n Dim x = New A(P:=5) \n End Sub \n End Class \n Class A \n Private P1 As Integer \n Public Sub New(P As Integer) \n Me.P1 = P \n End Sub \n Shared Property P As Integer \n End Class"))
End Sub
<WorkItem(542055)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingFieldWithSameNameButIncompatibleType()
Test(
NewLines("Class A \n Sub Test() \n Dim t As New B([|x|]:=5) \n End Sub \n End Class \n Class B \n Private x As String \n End Class"),
NewLines("Class A \n Sub Test() \n Dim t As New B(x:=5) \n End Sub \n End Class \n Class B \n Private x As String \n Private x1 As Integer \n Public Sub New(x As Integer) \n Me.x1 = x \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingFieldFromBaseClass()
Test(
NewLines("Class A \n Sub Test() \n Dim t As New C([|u|]:=5) \n End Sub \n End Class \n Class C \n Inherits B \n Private x As String \n End Class \n Class B \n Protected u As Integer \n End Class"),
NewLines("Class A \n Sub Test() \n Dim t As New C(u:=5) \n End Sub \n End Class \n Class C \n Inherits B \n Private x As String \n Public Sub New(u As Integer) \n Me.u = u \n End Sub \n End Class \n Class B \n Protected u As Integer \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMeConstructorInitializer()
Test(
NewLines("Class C \n Sub New \n Me.New([|1|]) \n End Sub \n End Class"),
NewLines("Class C \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Sub New \n Me.New(1) \n End Sub \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingMeConstructorInitializer()
TestMissing(
NewLines("Class C \n Private v As Integer \n Sub New \n Me.[|New|](1) \n End Sub \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMyBaseConstructorInitializer()
Test(
NewLines("Class C \n Sub New \n MyClass.New([|1|]) \n End Sub \n End Class"),
NewLines("Class C \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Sub New \n MyClass.New(1) \n End Sub \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingMyBaseConstructorInitializer()
TestMissing(
NewLines("Class C \n Private v As Integer \n Sub New \n MyClass.[|New|](1) \n End Sub \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMyClassConstructorInitializer()
Test(
NewLines("Class C \n Inherits B \n Sub New \n MyBase.New([|1|]) \n End Sub \n End Class \n Class B \n End Class"),
NewLines("Class C \n Inherits B \n Sub New \n MyBase.New(1) \n End Sub \n End Class \n Class B \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
<WorkItem(542098)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestExistingMyClassConstructorInitializer()
TestMissing(
NewLines("Class C \n Inherits B \n Sub New \n MyBase.New([|1|]) \n End Sub \n End Class \n Class B \n Protected Sub New(v As Integer) \n End Sub \n End Class"))
End Sub
<WorkItem(542056)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestConflictingFieldNameInSubclass()
Test(
NewLines("Class A \n Sub Test() \n Dim t As New C([|u|]:=5) \n End Sub \n End Class \n Class C \n Inherits B \n Private x As String \n End Class \n Class B \n Protected u As String \n End Class"),
NewLines("Class A \n Sub Test() \n Dim t As New C(u:=5) \n End Sub \n End Class \n Class C \n Inherits B \n Private u1 As Integer \n Private x As String \n Public Sub New(u As Integer) \n Me.u1 = u \n End Sub \n End Class \n Class B \n Protected u As String \n End Class"))
End Sub
<WorkItem(542442)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestNothingArgument()
TestMissing(
NewLines("Class C1 \n Public Sub New(ByVal accountKey As Integer) \n Me.new() \n Me.[|new|](accountKey, Nothing) \n End Sub \n Public Sub New(ByVal accountKey As Integer, ByVal accountName As String) \n Me.New(accountKey, accountName, Nothing) \n End Sub \n Public Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String) \n End Sub \n End Class"))
End Sub
<WorkItem(540641)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestMissingOnExistingConstructor()
TestMissing(
NewLines("Module Program \n Sub M() \n Dim x As C = New [|C|](P) \n End Sub \n End Module \n Class C \n Private v As Object \n Public Sub New(v As Object) \n Me.v = v \n End Sub \n End Class"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerationIntoVisibleType()
Test(
NewLines("#ExternalSource (""Default.aspx"", 1) \n Class C \n Sub Foo() \n Dim x As New D([|5|]) \n End Sub \n End Class \n Class D \n End Class \n #End ExternalSource"),
NewLines("#ExternalSource (""Default.aspx"", 1) \n Class C \n Sub Foo() \n Dim x As New D(5) \n End Sub \n End Class \n Class D \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n #End ExternalSource"))
End Sub
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestNoGenerationIntoEntirelyHiddenType()
TestMissing(
<Text>#ExternalSource (""Default.aspx"", 1)
Class C
Sub Foo()
Dim x As New D([|5|])
End Sub
End Class
#End ExternalSource
Class D
End Class
</Text>.Value)
End Sub
<WorkItem(546030)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestConflictingDelegatedParameterNameAndNamedArgumentName1()
Test(
NewLines("Module Program \n Sub Main(args As String()) \n Dim objc As New C(1, [|prop|]:=""Property"") \n End Sub \n End Module \n \n Class C \n Private prop As String \n \n Public Sub New(prop As String) \n Me.prop = prop \n End Sub \n End Class"),
NewLines("Module Program \n Sub Main(args As String()) \n Dim objc As New C(1, prop:=""Property"") \n End Sub \n End Module \n \n Class C \n Private prop As String \n Private v As Integer \n Public Sub New(prop As String) \n Me.prop = prop \n End Sub \n Public Sub New(v As Integer, prop As String) \n Me.v = v \n Me.prop = prop \n End Sub \n End Class"))
End Sub
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestFormattingInGenerateConstructor()
Test(
<Text>Class C
Sub New()
MyClass.New([|1|])
End Sub
End Class</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Class C
Private v As Integer
Sub New()
MyClass.New(1)
End Sub
Public Sub New(v As Integer)
Me.v = v
End Sub
End Class</Text>.Value.Replace(vbLf, vbCrLf),
compareTokens:=False)
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithArgument()
Test(
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n End Class \n [|<MyAttribute(123)>|] \n Public Class D \n End Class"),
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n <MyAttribute(123)> \n Public Class D \n End Class"))
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithMultipleArguments()
Test(
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n End Class \n [|<MyAttribute(true, 1, ""hello"")>|] \n Public Class D \n End Class"),
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private v1 As Boolean \n Private v2 As Integer \n Private v3 As String \n Public Sub New(v1 As Boolean, v2 As Integer, v3 As String) \n Me.v1 = v1 \n Me.v2 = v2 \n Me.v3 = v3 \n End Sub \n End Class \n <MyAttribute(true, 1, ""hello"")> \n Public Class D \n End Class"))
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithNamedArguments()
Test(
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n End Class \n [|<MyAttribute(true, 1, Topic:= ""hello"")>|] \n Public Class D \n End Class"),
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private Topic As String \n Private v1 As Boolean \n Private v2 As Integer \n Public Sub New(v1 As Boolean, v2 As Integer, Topic As String) \n Me.v1 = v1 \n Me.v2 = v2 \n Me.Topic = Topic \n End Sub \n End Class \n <MyAttribute(true, 1, Topic:= ""hello"")> \n Public Class D \n End Class"))
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithAdditionalConstructors()
Test(
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n [|<MyAttribute(True, 2)>|] \n Public Class D \n End Class"),
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private v As Integer \n Private v1 As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n Public Sub New(v As Integer, v1 As Integer) \n Me.New(v) \n Me.v1 = v1 \n End Sub \n End Class \n <MyAttribute(True, 2)> \n Public Class D \n End Class"))
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithAllValidArguments()
Test(
NewLines("Enum A \n A1 \n End Enum \n <AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n End Class \n [|<MyAttribute(New Short(1) {1, 2, 3}, A.A1, True, 1, ""Z""c, 5S, 1I, 5L, 6.0R, 2.1F, ""abc"")>|] \n Public Class D End Class"),
NewLines("Enum A \n A1 \n End Enum \n <AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute \n Private a1 As A \n Private v1 As Short() \n Private v10 As String \n Private v2 As Boolean \n Private v3 As Integer \n Private v4 As Char \n Private v5 As Short \n Private v6 As Integer \n Private v7 As Long \n Private v8 As Double \n Private v9 As Single \n Public Sub New(v1() As Short, a1 As A, v2 As Boolean, v3 As Integer, v4 As Char, v5 As Short, v6 As Integer, v7 As Long, v8 As Double, v9 As Single, v10 As String) \n Me.v1 = v1 \n Me.a1 = a1 \n Me.v2 = v2 \n Me.v3 = v3 \n Me.v4 = v4 \n Me.v5 = v5 \n Me.v6 = v6 \n Me.v7 = v7 \n Me.v8 = v8 \n Me.v9 = v9 \n Me.v10 = v10 \n End Sub \n End Class \n <MyAttribute(New Short(1) {1, 2, 3}, A.A1, True, 1, ""Z""c, 5S, 1I, 5L, 6.0R, 2.1F, ""abc"")> \n Public Class D \n End Class "))
End Sub
<WorkItem(530003)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestAttributesWithLambda()
TestMissing(
NewLines("<AttributeUsage(AttributeTargets.Class)> \n Public Class MyAttribute \n Inherits System.Attribute End Class \n [|<MyAttribute(Function(x) x+1)>|] \n Public Class D \n End Class"))
End Sub
<WorkItem(889349)>
<Fact(), Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestConstructorGenerationForDifferentNamedParameter()
Test(
<Text>Class Program
Sub Main(args As String())
Dim a = New Program([|y:=4|])
End Sub
Sub New(x As Integer)
End Sub
End Class</Text>.Value.Replace(vbLf, vbCrLf),
<Text>Class Program
Private y As Integer
Sub Main(args As String())
Dim a = New Program(y:=4)
End Sub
Sub New(x As Integer)
End Sub
Public Sub New(y As Integer)
Me.y = y
End Sub
End Class</Text>.Value.Replace(vbLf, vbCrLf),
compareTokens:=False)
End Sub
<WorkItem(897355)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestOptionStrictOn()
Test(
NewLines("Option Strict On \n Module Module1 \n Sub Main() \n Dim int As Integer = 3 \n Dim obj As Object = New Object() \n Dim c1 As Classic = New Classic(int) \n Dim c2 As Classic = [|New Classic(obj)|] \n End Sub \n Class Classic \n Private int As Integer \n Public Sub New(int As Integer) \n Me.int = int \n End Sub \n End Class \n End Module"),
NewLines("Option Strict On \n Module Module1 \n Sub Main() \n Dim int As Integer = 3 \n Dim obj As Object = New Object() \n Dim c1 As Classic = New Classic(int) \n Dim c2 As Classic = New Classic(obj) \n End Sub \n Class Classic \n Private int As Integer \n Private obj As Object \n Public Sub New(obj As Object) \n Me.obj = obj \n End Sub \n Public Sub New(int As Integer) \n Me.int = int \n End Sub \n End Class \n End Module "))
End Sub
<WorkItem(528257)>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateInInaccessibleType()
Test(
NewLines("Class Foo \n Private Class Bar \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New [|Foo.Bar(5)|] \n End Sub \n End Class"),
NewLines("Class Foo \n Private Class Bar \n Private v As Integer \n Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class \n End Class \n Class A \n Sub Main() \n Dim s = New Foo.Bar(5) \n End Sub \n End Class"))
End Sub
Public Class GenerateConstructorTestsWithFindMissingIdentifiersAnalyzer
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, CodeFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, CodeFixProvider)(New VisualBasicUnboundIdentifiersDiagnosticAnalyzer(), New GenerateConstructorCodeFixProvider())
End Function
<WorkItem(1241, "https://github.com/dotnet/roslyn/issues/1241")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateConstructor)>
Public Sub TestGenerateConstructorInIncompleteLambda()
Test(
NewLines("Imports System.Linq \n Class C \n Sub New() \n Dim s As Action = Sub() \n Dim a = New [|C|](0)"),
NewLines("Imports System.Linq \n Class C \n Private v As Integer \n Sub New() \n Dim s As Action = Sub() \n Dim a = New C(0)Public Sub New(v As Integer) \n Me.v = v \n End Sub \n End Class"))
End Sub
End Class
End Class
End Namespace
|
droyad/roslyn
|
src/EditorFeatures/VisualBasicTest/Diagnostics/GenerateConstructor/GenerateConstructorTests.vb
|
Visual Basic
|
apache-2.0
| 35,255
|
Imports System.Globalization
Imports Microsoft.Win32
Public Class ApplicationOptions
#Region "Option Constants"
Public Const OPT_FOLDER_LEVEL_1 As String = "FolderLevel1"
Public Const OPT_FOLDER_LEVEL_2 As String = "FolderLevel2"
Public Const OPT_FOLDER_LEVEL_3 As String = "FolderLevel3"
Public Const OPT_FOLDER_LEVEL_4 As String = "FolderLevel4"
Public Const OPT_IGNORE_DOT_FILES As String = "IgnoreDotFiles"
Public Const OPT_USE_DATE_TAKEN As String = "UseDateTaken"
Public Const OPT_DUPLICATE_ACTION As String = "DuplicateFileAction"
Public Const OPT_MOVE_FILES As String = "MoveFiles"
Public Const OPT_FOLDER_SOURCE As String = "FolderSource"
Public Const OPT_FOLDER_DEST As String = "FolderDest"
Public Const FOLDER_LEVEL_YEAR As String = "Year"
Public Const FOLDER_LEVEL_MONTH As String = "Month"
Public Const FOLDER_LEVEL_EVENT As String = "Event Name"
Public Const FOLDER_LEVEL_DAY As String = "Day"
Public Const FOLDER_LEVEL_NONE As String = "(None)"
Public Const DUPLICATE_ACTION_COPY_ANYWAYS = "0"
Public Const DUPLICATE_ACTION_COPY_TO_DUP_FOLDER = "1"
Public Const DUPLICATE_ACTION_SKIP = "2"
#End Region
Private OptionList As Dictionary(Of String, String)
Private AllLists As Dictionary(Of String, List(Of String))
#Region "Singleton Implementation"
Private Shared _Instance As ApplicationOptions
Private Shared ReadOnly _InstanceLock As Object = New Object()
Public Shared ReadOnly Property Instance() As ApplicationOptions
Get
SyncLock _InstanceLock
If (_Instance Is Nothing) Then
_Instance = New ApplicationOptions()
End If
End SyncLock
Return _Instance
End Get
End Property
#End Region
Private Sub New()
OptionList = New Dictionary(Of String, String)
AllLists = New Dictionary(Of String, List(Of String))
setDefaultValues()
EnsureExistsRegKey("SOFTWARE", Application.ProductName)
EnsureExistsRegKey("SOFTWARE\" & Application.ProductName, "Lists")
loadFromReg()
loadAllListsFromReg()
End Sub
Private Sub setDefaultValues()
OptionList(OPT_USE_DATE_TAKEN) = "true"
OptionList(OPT_IGNORE_DOT_FILES) = "true"
OptionList(OPT_MOVE_FILES) = "true"
OptionList(OPT_DUPLICATE_ACTION) = DUPLICATE_ACTION_COPY_TO_DUP_FOLDER
OptionList(OPT_FOLDER_LEVEL_1) = FOLDER_LEVEL_YEAR
OptionList(OPT_FOLDER_LEVEL_2) = FOLDER_LEVEL_MONTH
OptionList(OPT_FOLDER_LEVEL_3) = FOLDER_LEVEL_EVENT
OptionList(OPT_FOLDER_LEVEL_4) = FOLDER_LEVEL_NONE
End Sub
Public Sub setOption(strOptionName As String, strOptionValue As String)
OptionList(strOptionName) = strOptionValue
saveOptionReg(strOptionName, strOptionValue)
End Sub
Public Function getOption(strOptionName As String) As String
If hasOption(strOptionName) Then
Return OptionList(strOptionName)
Else
Return ""
End If
End Function
Public Function hasOption(strOptionName As String) As Boolean
If OptionList.ContainsKey(strOptionName) Then
Return True
Else
Return False
End If
End Function
Public Sub setOptionInt(strOptionName As String, intOptionValue As Integer)
setOption(strOptionName, intOptionValue.ToString())
End Sub
Public Function getOptionInt(strOptionName As String) As Integer
Dim intReturn As Integer
Try
intReturn = Integer.Parse(getOption(strOptionName))
Catch ex As Exception
intReturn = 0
End Try
Return intReturn
End Function
Public Function hasOptionInt(strOptionName As String) As Boolean
Dim blnRet As Boolean
Dim intVal As Integer
Try
blnRet = hasOption(strOptionName)
If blnRet Then
intVal = Integer.Parse(getOption(strOptionName))
End If
Catch ex As Exception
blnRet = False
End Try
Return blnRet
End Function
Public Function getOptionDate(strOptionName As String) As DateTime
Dim ciProvider As CultureInfo = CultureInfo.InvariantCulture
Dim dteReturnDate As DateTime
Try
If hasOptionDate(strOptionName) Then
dteReturnDate = DateTime.ParseExact(getOption(strOptionName), "yyyy-MM-dd HH:mm:ss", ciProvider)
Else
dteReturnDate = DateTime.ParseExact("1900-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss", ciProvider)
End If
Catch ex As Exception
dteReturnDate = DateTime.ParseExact("1900-01-01 12:00:00", "yyyy-MM-dd HH:mm:ss", ciProvider)
End Try
Return (dteReturnDate)
End Function
Public Sub setOptionDate(strOptionName As String, dteDateValue As DateTime)
Dim strFormatValue As String
strFormatValue = dteDateValue.ToString("yyyy-MM-dd HH:mm:ss")
setOption(strOptionName, strFormatValue)
End Sub
Public Function hasOptionDate(strOptionName As String) As Boolean
Dim blnRet As Boolean
Dim ciProvider As CultureInfo = CultureInfo.InvariantCulture
Dim dteReturnDate As DateTime
Try
blnRet = hasOption(strOptionName)
If blnRet Then
dteReturnDate = DateTime.ParseExact(getOption(strOptionName), "yyyy-MM-dd HH:mm:ss", ciProvider)
End If
Catch ex As Exception
blnRet = False
End Try
Return blnRet
End Function
Public Function getOptionBoolean(strOptionName As String) As Boolean
Dim blnRet As Boolean
Dim strValue As String
strValue = getOption(strOptionName)
If strValue = "true" Then
blnRet = True
Else
blnRet = False
End If
Return blnRet
End Function
Public Sub setOptionBoolean(strOptionName As String, blnValue As Boolean)
If blnValue Then
setOption(strOptionName, "true")
Else
setOption(strOptionName, "false")
End If
End Sub
Public Function getDuplicateFolder() As String
Dim strRet As String
strRet = getOption(OPT_FOLDER_DEST)
strRet = strRet & "\Duplicates"
Return strRet
End Function
Private Sub EnsureExistsRegKey(strKeyParent As String, strCheckKey As String)
Dim reg As RegistryKey
Dim strKeys As String()
Dim blnHasKey As Boolean
blnHasKey = False
reg = Registry.CurrentUser.OpenSubKey(strKeyParent, True)
strKeys = reg.GetSubKeyNames
For Each strKeyName As String In strKeys
If strKeyName = strCheckKey Then
blnHasKey = True
End If
Next
If blnHasKey = False Then
reg.CreateSubKey(strCheckKey)
End If
reg.Close()
reg.Dispose()
End Sub
Private Sub loadFromReg()
Dim reg As RegistryKey
Dim strValueNames As String()
Dim strValue As String
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName, True)
strValueNames = reg.GetValueNames()
For Each strValueName As String In strValueNames
strValue = reg.GetValue(strValueName)
setOption(strValueName, strValue)
Next
reg.Close()
reg.Dispose()
End Sub
Private Sub loadAllListsFromReg()
Dim reg As RegistryKey
Dim strSubKeys As String()
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName & "\Lists", True)
strSubKeys = reg.GetSubKeyNames()
For Each strKey As String In strSubKeys
loadListFromReg(strKey)
Next
reg.Close()
reg.Dispose()
End Sub
Private Sub loadListFromReg(strListName As String)
Dim reg As RegistryKey
Dim intEntryCount As Integer
Dim intEntryNum As Integer
Dim lstList As List(Of String)
Dim strEntry As String
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName & "\Lists\" & strListName, True)
intEntryCount = reg.GetValue("EntryCount")
intEntryNum = 1
lstList = New List(Of String)()
While intEntryNum <= intEntryCount
strEntry = reg.GetValue("Entry_" & intEntryNum)
lstList.Add(strEntry)
intEntryNum += 1
End While
setList(strListName, lstList)
reg.Close()
reg.Dispose()
End Sub
Private Sub saveOptionReg(strName As String, strValue As String)
Dim reg As RegistryKey
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName, True)
reg.SetValue(strName, strValue)
reg.Close()
reg.Dispose()
End Sub
Public Function getLevelDepth()
Dim intRet As Integer
Dim i As Integer
intRet = 0
i = 1
While i <= 4
If getOption(getLevelOptionName(i)) = ApplicationOptions.FOLDER_LEVEL_NONE Then
intRet = i - 1
i = 5
End If
i += 1
End While
If intRet = 0 Then
intRet = 4
End If
Return intRet
End Function
Public Function getLevelOptionName(intLevelNum As Integer) As String
Dim strReturn As String
Select Case intLevelNum
Case 1
strReturn = ApplicationOptions.OPT_FOLDER_LEVEL_1
Case 2
strReturn = ApplicationOptions.OPT_FOLDER_LEVEL_2
Case 3
strReturn = ApplicationOptions.OPT_FOLDER_LEVEL_3
Case 4
strReturn = ApplicationOptions.OPT_FOLDER_LEVEL_4
Case Else
Throw New PFException("Invalid folder level specified for option name", "INVALID_FOLDER_LEVEL", PFException.eType.InternalError)
End Select
Return strReturn
End Function
Private Function hasList(strListName As String) As Boolean
Dim blnRet As Boolean
If AllLists.ContainsKey(strListName) Then
blnRet = True
Else
blnRet = False
End If
Return blnRet
End Function
Private Sub createList(strListName As String)
Dim reg As RegistryKey
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName & "\Lists", True)
reg.CreateSubKey(strListName)
AllLists.Add(strListName, New List(Of String))
End Sub
Public Sub addListEntry(strListName As String, strNewEntry As String)
Dim lstList As List(Of String)
If hasList(strListName) = False Then
createList(strListName)
End If
lstList = getList(strListName)
lstList.Add(strNewEntry)
End Sub
Public Sub addMRUListEntry(strListName As String, strNewEntry As String, intMaxSize As Integer)
Dim lstList As List(Of String)
Dim lstNewList As List(Of String)
If hasList(strListName) = False Then
createList(strListName)
End If
' Get the existing list and add
lstList = getList(strListName)
lstNewList = New List(Of String)
' Add this entry at the start of the list
lstNewList.Add(strNewEntry)
' Loop through the previous list and add all items which aren't equal to the one already added
' and limit the size to "Max Size"
For Each strEntry As String In lstList
If strEntry <> strNewEntry Then
If lstNewList.Count < intMaxSize Then
lstNewList.Add(strEntry)
End If
End If
Next
' Save the new list
setList(strListName, lstNewList)
End Sub
Public Sub saveListToReg(strListName As String)
Dim lstSave As List(Of String)
Dim reg As RegistryKey
Dim intEntryNum As Integer
If hasList(strListName) Then
lstSave = getList(strListName)
Else
lstSave = New List(Of String)
End If
reg = Registry.CurrentUser.OpenSubKey("SOFTWARE\" & Application.ProductName & "\Lists\" & strListName, True)
reg.SetValue("EntryCount", lstSave.Count)
intEntryNum = 1
For Each strEntry As String In lstSave
reg.SetValue("Entry_" & intEntryNum, strEntry)
intEntryNum += 1
Next
reg.Close()
End Sub
Public Sub setList(strListName As String, lstSet As List(Of String))
AllLists.Item(strListName) = lstSet
saveListToReg(strListName)
End Sub
Public Function getList(strListName As String) As List(Of String)
Dim lstRet As List(Of String)
If hasList(strListName) Then
lstRet = AllLists.Item(strListName)
Else
lstRet = New List(Of String)
End If
Return lstRet
End Function
End Class
|
acrojax-open/photos2folders
|
Photos2Folders/ApplicationOptions.vb
|
Visual Basic
|
mit
| 13,131
|
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
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)
Dim sweptProtrusions = model.SweptProtrusions
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.Model.SweptProtrusions.vb
|
Visual Basic
|
mit
| 1,374
|
'------------------------------------------------------------------------------
' <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("TextEditor.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property
'''<summary>
''' Overrides the current thread's CurrentUICulture property for all
''' resource lookups using this strongly typed resource class.
'''</summary>
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
Friend Property Culture() As Global.System.Globalization.CultureInfo
Get
Return resourceCulture
End Get
Set(ByVal value As Global.System.Globalization.CultureInfo)
resourceCulture = value
End Set
End Property
End Module
End Namespace
|
Shadorunce/MiniProjects
|
Text Editor/TextEditor/My Project/Resources.Designer.vb
|
Visual Basic
|
mit
| 2,781
|
'------------------------------------------------------------------------------
' <generado automáticamente>
' Este código fue generado por una herramienta.
'
' Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
' se vuelve a generar el código.
' </generado automáticamente>
'------------------------------------------------------------------------------
Option Strict On
Option Explicit On
Partial Public Class ExcelExistencias
'''<summary>
'''Control Head1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents Head1 As Global.System.Web.UI.HtmlControls.HtmlHead
'''<summary>
'''Control form1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents form1 As Global.System.Web.UI.HtmlControls.HtmlForm
'''<summary>
'''Control GridView1.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents GridView1 As Global.System.Web.UI.WebControls.GridView
'''<summary>
'''Control SqlDatos.
'''</summary>
'''<remarks>
'''Campo generado automáticamente.
'''Para modificarlo, mueva la declaración del campo del archivo del diseñador al archivo de código subyacente.
'''</remarks>
Protected WithEvents SqlDatos As Global.System.Web.UI.WebControls.SqlDataSource
End Class
|
crackper/SistFoncreagro
|
SistFoncreagro.WebSite/Monitoreo/Formularios/ExcelExistencias.aspx.designer.vb
|
Visual Basic
|
mit
| 1,831
|
'////////////////////////////////////////////////////////////////////////
' Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
'
' This file is part of Aspose.Words. The source code in this file
' is only intended as a supplement to the documentation, and is provided
' "as is", without warranty of any kind, either expressed or implied.
'////////////////////////////////////////////////////////////////////////
Imports Microsoft.VisualBasic
Imports System.IO
Imports Aspose.Words
Public Class HelloWorld
Public Shared Sub Run()
' The path to the documents directory.
Dim dataDir As String = RunExamples.GetDataDir_QuickStart()
' Create a blank document.
Dim doc As New Document()
' DocumentBuilder provides members to easily add content to a document.
Dim builder As New DocumentBuilder(doc)
' Write a new paragraph in the document with the text "Hello World!"
builder.Writeln("Hello World!")
' Save the document in DOCX format. The format to save as is inferred from the extension of the file name.
' Aspose.Words supports saving any document in many more formats.
doc.Save(dataDir & "HelloWorld Out.docx")
Console.WriteLine(vbNewLine + "New document created successfully." + vbNewLine + "File saved at " + dataDir + "HelloWorld Out.docx")
End Sub
End Class
|
dtscal/Aspose_Words_NET
|
Examples/VisualBasic/Quick-Start/HelloWorld.vb
|
Visual Basic
|
mit
| 1,381
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class frmpregivercctr
Inherits WeifenLuo.WinFormsUI.Docking.DockContent
'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.pnHeader = New System.Windows.Forms.Panel
Me.cmdSave = New PlanningS.NPIButton
Me.cmdImport = New PlanningS.NPIButton
Me.NpiLabel2 = New PlanningS.NPILabel
Me.NpiLabel1 = New PlanningS.NPILabel
Me.txtVersion = New PlanningS.NPIText
Me.txtOrder = New PlanningS.NPIText
Me.Splitter1 = New System.Windows.Forms.Splitter
Me.dtgItem = New System.Windows.Forms.DataGridView
Me.pnHeader.SuspendLayout()
CType(Me.dtgItem, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'pnHeader
'
Me.pnHeader.BackColor = System.Drawing.Color.FromArgb(CType(CType(255, Byte), Integer), CType(CType(255, Byte), Integer), CType(CType(192, Byte), Integer))
Me.pnHeader.Controls.Add(Me.cmdSave)
Me.pnHeader.Controls.Add(Me.cmdImport)
Me.pnHeader.Controls.Add(Me.NpiLabel2)
Me.pnHeader.Controls.Add(Me.NpiLabel1)
Me.pnHeader.Controls.Add(Me.txtVersion)
Me.pnHeader.Controls.Add(Me.txtOrder)
Me.pnHeader.Dock = System.Windows.Forms.DockStyle.Top
Me.pnHeader.Location = New System.Drawing.Point(0, 0)
Me.pnHeader.Name = "pnHeader"
Me.pnHeader.Size = New System.Drawing.Size(888, 60)
Me.pnHeader.TabIndex = 0
'
'cmdSave
'
Me.cmdSave.BackColor = System.Drawing.SystemColors.Control
Me.cmdSave.Cursor = System.Windows.Forms.Cursors.Hand
Me.cmdSave.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Bold)
Me.cmdSave.ForeColor = System.Drawing.Color.Blue
Me.cmdSave.Location = New System.Drawing.Point(524, 18)
Me.cmdSave.Name = "cmdSave"
Me.cmdSave.Size = New System.Drawing.Size(75, 23)
Me.cmdSave.TabIndex = 5
Me.cmdSave.Text = "Save"
Me.cmdSave.UseVisualStyleBackColor = True
'
'cmdImport
'
Me.cmdImport.BackColor = System.Drawing.SystemColors.Control
Me.cmdImport.Cursor = System.Windows.Forms.Cursors.Hand
Me.cmdImport.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Bold)
Me.cmdImport.ForeColor = System.Drawing.Color.Blue
Me.cmdImport.Location = New System.Drawing.Point(404, 18)
Me.cmdImport.Name = "cmdImport"
Me.cmdImport.Size = New System.Drawing.Size(104, 23)
Me.cmdImport.TabIndex = 4
Me.cmdImport.Text = "Import Excel"
Me.cmdImport.UseVisualStyleBackColor = True
'
'NpiLabel2
'
Me.NpiLabel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.NpiLabel2.Cursor = System.Windows.Forms.Cursors.Hand
Me.NpiLabel2.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Bold)
Me.NpiLabel2.ImageAlign = System.Drawing.ContentAlignment.MiddleRight
Me.NpiLabel2.Location = New System.Drawing.Point(244, 18)
Me.NpiLabel2.Name = "NpiLabel2"
Me.NpiLabel2.Size = New System.Drawing.Size(89, 23)
Me.NpiLabel2.TabIndex = 3
Me.NpiLabel2.Text = "Version :"
Me.NpiLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'NpiLabel1
'
Me.NpiLabel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle
Me.NpiLabel1.Cursor = System.Windows.Forms.Cursors.Hand
Me.NpiLabel1.Font = New System.Drawing.Font("Tahoma", 12.0!, System.Drawing.FontStyle.Bold)
Me.NpiLabel1.ImageAlign = System.Drawing.ContentAlignment.MiddleRight
Me.NpiLabel1.Location = New System.Drawing.Point(28, 18)
Me.NpiLabel1.Name = "NpiLabel1"
Me.NpiLabel1.Size = New System.Drawing.Size(100, 23)
Me.NpiLabel1.TabIndex = 2
Me.NpiLabel1.Text = "Order No: "
Me.NpiLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'txtVersion
'
Me.txtVersion.Font = New System.Drawing.Font("Tahoma", 9.0!)
Me.txtVersion.Location = New System.Drawing.Point(336, 18)
Me.txtVersion.MaxLength = 2
Me.txtVersion.Name = "txtVersion"
Me.txtVersion.Showcomma = False
Me.txtVersion.Size = New System.Drawing.Size(33, 22)
Me.txtVersion.TabIndex = 1
'
'txtOrder
'
Me.txtOrder.Font = New System.Drawing.Font("Tahoma", 9.0!)
Me.txtOrder.Location = New System.Drawing.Point(134, 18)
Me.txtOrder.MaxLength = 7
Me.txtOrder.Name = "txtOrder"
Me.txtOrder.Size = New System.Drawing.Size(90, 22)
Me.txtOrder.TabIndex = 0
'
'Splitter1
'
Me.Splitter1.Dock = System.Windows.Forms.DockStyle.Top
Me.Splitter1.Location = New System.Drawing.Point(0, 60)
Me.Splitter1.Name = "Splitter1"
Me.Splitter1.Size = New System.Drawing.Size(888, 3)
Me.Splitter1.TabIndex = 1
Me.Splitter1.TabStop = False
'
'dtgItem
'
Me.dtgItem.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.dtgItem.Dock = System.Windows.Forms.DockStyle.Fill
Me.dtgItem.Location = New System.Drawing.Point(0, 63)
Me.dtgItem.Name = "dtgItem"
Me.dtgItem.Size = New System.Drawing.Size(888, 416)
Me.dtgItem.TabIndex = 2
Me.dtgItem.TabStop = False
'
'FrmPreGI
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(888, 479)
Me.Controls.Add(Me.dtgItem)
Me.Controls.Add(Me.Splitter1)
Me.Controls.Add(Me.pnHeader)
Me.Name = "FrmPreGI"
Me.TabText = "เตรียมใบเบิก"
Me.Text = "เตรียมใบเบิก"
Me.pnHeader.ResumeLayout(False)
Me.pnHeader.PerformLayout()
CType(Me.dtgItem, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents pnHeader As System.Windows.Forms.Panel
Friend WithEvents NpiLabel2 As PlanningS.NPILabel
Friend WithEvents NpiLabel1 As PlanningS.NPILabel
Friend WithEvents txtVersion As PlanningS.NPIText
Friend WithEvents txtOrder As PlanningS.NPIText
Friend WithEvents Splitter1 As System.Windows.Forms.Splitter
Friend WithEvents cmdSave As PlanningS.NPIButton
Friend WithEvents cmdImport As PlanningS.NPIButton
Friend WithEvents dtgItem As System.Windows.Forms.DataGridView
End Class
|
100dej/PlanningS
|
Form/800/FrmPreGIverCCtr.Designer.vb
|
Visual Basic
|
mit
| 7,528
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.